View Javadoc
1   package com.nilhcem.fakesmtp.core;
2   
3   import java.util.Locale;
4   import java.util.MissingResourceException;
5   import java.util.ResourceBundle;
6   import org.slf4j.Logger;
7   import org.slf4j.LoggerFactory;
8   
9   /**
10   * Initializes resource bundle and get messages from keys.
11   * <p>
12   * This class will be instantiated only once and will use the JVM's default locale.
13   * </p>
14   *
15   * @author Nilhcem
16   * @since 1.0
17   */
18  public enum I18n {
19  	INSTANCE;
20  
21  	public static final String UTF8 = "UTF-8";
22  	private static final String RESOURCE_FILE = "i18n/messages";
23  	private final Logger logger = LoggerFactory.getLogger(I18n.class);
24  	private final ResourceBundle resources;
25  
26  	/**
27  	 * Initializes resource bundle with the JVM's default locale.
28  	 * <p>
29  	 * If the JVM's default locale doesn't have any resource file, will take the en_US resources instead.
30  	 * </p>
31  	 */
32  	I18n() {
33  		ResourceBundle bundle;
34  
35  		try {
36  			bundle = ResourceBundle.getBundle(I18n.RESOURCE_FILE, Locale.getDefault());
37  		} catch (MissingResourceException mre) {
38  			logger.error("{}", mre.getMessage());
39  			logger.info("Will use default bundle (en_US) instead");
40  			bundle = ResourceBundle.getBundle(I18n.RESOURCE_FILE, Locale.US);
41  		}
42  		resources = bundle;
43  	}
44  
45  	/**
46  	 * Returns the resource for the key passed in parameters.
47  	 * <p>
48  	 * If the key is not found, returns an empty string.
49  	 * </p>
50  	 *
51  	 * @param key a String representing the key we want to get the resource from.
52  	 * @return The text corresponding to the key passed in parameters, or an empty string if not found.
53  	 */
54  	public String get(String key) {
55  		try {
56  			return resources.getString(key);
57  		} catch (MissingResourceException e) {
58  			logger.error("{}", e.getMessage());
59  			return "";
60  		}
61  	}
62  }