001package org.hl7.fhir.utilities.i18n;
002
003import java.text.MessageFormat;
004import java.util.Collections;
005import java.util.Locale;
006import java.util.Objects;
007import java.util.ResourceBundle;
008import java.util.Set;
009import java.util.stream.Collectors;
010
011import javax.annotation.Nonnull;
012
013import com.ibm.icu.text.PluralRules;
014
015
016/**
017 * Handles the locale, ResourceBundle and String formatting for i18n
018 * This abstract class should be extended when implementing a IWorkerContext Interface.
019 */
020public abstract class I18nBase {
021
022  public static final String PLURAL_SUFFIX = "PLURAL";
023  public static final String KEY_DELIMITER = "_";
024  protected Locale locale;
025  private ResourceBundle messages;
026  private PluralRules pluralRules;
027  private boolean warnAboutMissingMessages = true;
028
029  public Locale getLocale() {
030    if (Objects.nonNull(locale)) {
031      return locale;
032    } else {
033      return Locale.getDefault();
034    }
035  }
036
037  public void setLocale(Locale locale) {
038    this.locale = locale;
039    setValidationMessageLanguage(getLocale());
040  }
041
042  /**
043   * Verifies if a {@link ResourceBundle} has been loaded for the current {@link Locale}. If not, it triggers a load.
044   */
045  private void checkResourceBundleIsLoaded() {
046    if (messages == null) {
047      setValidationMessageLanguage(getLocale());
048    }
049  }
050
051  private void checkPluralRulesAreLoaded() {
052    if (pluralRules == null) {
053      setPluralRules(getLocale());
054    }
055  }
056
057  /**
058   * Checks the loaded {@link ResourceBundle} to see if the passed in message exists with the current loaded {@link Locale}.
059   * If no {@link Locale} is currently loaded, it will load the {@link Locale} (default {@link Locale#US} is none is
060   * specified), and search.
061   * @param message The {@link String} message to search for within the current {@link Locale}
062   * @return {@link Boolean#TRUE} if the message exists within the loaded {@link Locale}.
063   */
064  private boolean messageExistsForLocale(String message, boolean hasArgs) {
065    checkResourceBundleIsLoaded();
066    if (!messageKeyExistsForLocale(message)) {
067      if (!message.contains(" ")) {
068        if (warnAboutMissingMessages && (hasArgs || !message.contains(" "))) {
069          System.out.println("Attempting to localize "+typeOfString()+" " + message + ", but no such equivalent message exists for" +
070              " the locale " + getLocale());
071        }
072      }
073    }
074    return messageKeyExistsForLocale(message);
075  }
076
077  protected String typeOfString() {
078    return "message";
079  }
080
081  protected boolean messageKeyExistsForLocale(String message) {
082    return messages.containsKey(message);
083  }
084
085
086  /**
087   * Formats the given message, if needed, with the passed in message arguments.
088   * @param theMessage Base message to format.
089   * @param theMessageArguments Placeholder arguments, if needed.
090   * @return The formatted, internationalized, {@link String}
091   */
092  public String formatMessage(String theMessage, Object... theMessageArguments) {
093    return formatMessageForLocale(theMessage, theMessageArguments);
094  }
095
096  protected String getPluralKey(Integer number, String baseKey) {
097    return baseKey + KEY_DELIMITER + pluralRules.select(number);
098  }
099
100  protected Set<String> getPluralKeys(String baseKey) {
101    return pluralRules
102      .getKeywords().stream()
103      .map(entry -> baseKey + KEY_DELIMITER + entry).collect(Collectors.toSet());
104  }
105
106
107  protected Set<String> getPluralSuffixes() {
108    return Collections.unmodifiableSet(pluralRules.getKeywords());
109  }
110  
111  protected String getRootKeyFromPlural(@Nonnull String pluralKey) {
112    checkPluralRulesAreLoaded();
113    for (String keyword : pluralRules
114      .getKeywords()) {
115        final String suffix = KEY_DELIMITER + keyword;
116        if (pluralKey.endsWith(suffix)) {
117          return pluralKey.substring(0, pluralKey.length() - suffix.length());
118        }
119    }
120    return null;
121  }
122  private String formatMessageForLocale(String theMessage, Object... theMessageArguments) {
123    String message = theMessage;
124    if (messageExistsForLocale(theMessage, (theMessageArguments != null && theMessageArguments.length > 0))) {
125      if (Objects.nonNull(theMessageArguments) && theMessageArguments.length > 0) {
126        message = MessageFormat.format(messages.getString(theMessage).trim(), theMessageArguments);
127      } else {
128        message = MessageFormat.format(messages.getString(theMessage).trim(), (Object) null);
129      }
130    }
131    return message;
132  }
133
134  /**
135   * Formats the message with locale correct pluralization using the passed in
136   * message arguments.
137   *
138   * In the message properties files, each plural specific message will have a
139   * key consisting of a root key and a suffix denoting the plurality rule (_one
140   * for singular, _other for multiple in English, for example). Suffixes are
141   * provided by th ICU4J library from unicode.org
142   *
143   * @param plural The number that indicates the plurality of the phrase
144   * @param theMessage the root key of the phrase.
145   * @param theMessageArguments Placeholder arguments, if needed.
146   * @return The formatted, internationalized, {@link String}
147   */
148  public String formatMessagePlural(Integer plural, String theMessage, Object... theMessageArguments) {
149
150    Object[] args = new Object[theMessageArguments.length+1];
151    args[0] = plural;
152    for (int i = 0; i < theMessageArguments.length; i++) {
153      args[i+1] = theMessageArguments[i];
154    }
155    checkPluralRulesAreLoaded();
156    String pluralKey = getPluralKey(plural, theMessage);
157    return formatMessageForLocale(pluralKey, args);
158  }
159
160  /**
161   * Loads the corresponding {@link ResourceBundle} for the passed in {@link Locale}.
162   * @param locale {@link Locale} to load resources for.
163   */
164  public void setValidationMessageLanguage(Locale locale) {
165    messages = ResourceBundle.getBundle(getMessagesSourceFileName(), locale);
166  }
167
168  protected String getMessagesSourceFileName() {
169    return "Messages";
170  }
171
172  public void setPluralRules(Locale locale) {
173    pluralRules = PluralRules.forLocale(locale);
174  }
175
176  public boolean isWarnAboutMissingMessages() {
177    return warnAboutMissingMessages;
178  }
179
180  public void setWarnAboutMissingMessages(boolean warnAboutMissingMessages) {
181    this.warnAboutMissingMessages = warnAboutMissingMessages;
182  }
183  
184  
185}