1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package net.mchaplin.commons.i18n;
22
23 import java.util.Hashtable;
24 import java.util.Locale;
25 import java.util.Map;
26 import java.util.ResourceBundle;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31
32
33 /***
34 * Static Helper Class for reading messages from properties file.
35 *
36 * @author mchaplin@users.sourceforge.net
37 *
38 * $Header:
39 * $Revision:
40 * $Date:
41 */
42 public class I18n {
43
44 private static Log logger = LogFactory.getLog(I18n.class);
45 private static Map<String, ResourceBundle> messageResources = messageResources = new Hashtable<String,ResourceBundle>();
46
47
48 /***
49 * Retrieve a message in a properties file according to
50 * the given key
51 *
52 * @param propsFile name of the property file to load message from
53 * @param key name of the key identifying the message
54 * @return message identified by key or ""
55 */
56 public static String getMessage(String propsFile, String key) {
57 return getMessage(propsFile, key, null);
58 }
59
60 /***
61 * Retrieve a message in a properties file according to
62 * the given key & locale
63 *
64 * @param propsFile name of the property file to load message from
65 * @param key name of the key identifying the message
66 * @param locale ISO-639 locale to use
67 * @return message identified by key or ""
68 */
69 public static String getMessage(String propsFile, String key, String locale) {
70 ResourceBundle props = null;
71 String message = null;
72 if (messageResources.containsKey(propsFile+locale)) {
73 props = (ResourceBundle) messageResources.get(propsFile);
74 } else {
75 if (locale != null) {
76 props = getBundleFromDisk(propsFile, locale);
77 } else {
78 props = getBundleFromDisk(propsFile, null);
79 }
80
81 }
82 message = props.getString(key);
83 logger.debug(propsFile+"."+key+"=["+message+"]");
84 return message;
85 }
86
87 /***
88 * Load a ResourceBundle from Disk
89 *
90 * @param propsFile name of the property file to load.
91 * @param locale ISO-639 locale to use, if any.
92 *
93 * @return a ResourceBundle instance or null.
94 */
95 private static ResourceBundle getBundleFromDisk(String propsFile, String locale) {
96 ResourceBundle props = null;
97 if (locale != null) {
98 props = ResourceBundle.getBundle(propsFile, new Locale(locale));
99 } else {
100 props = ResourceBundle.getBundle(propsFile);
101 }
102
103
104 if (props != null) {
105 logger.debug("Adding ["+propsFile+"("+locale != null ? locale : "unknown_locale"+")] to know properties file list.");
106 if (messageResources != null) {
107 messageResources.put(propsFile+locale, props);
108 }
109 }
110 return props;
111 }
112
113 public static Map<String,ResourceBundle> getMessageResources() {
114 return messageResources;
115 }
116 /***
117 * @see net.mchaplin.ioc.ComponentI#reset()
118 */
119 public void reset() {
120 messageResources = null;
121 }
122 }