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