1
2
3
4
5
6
7
8
9
10 package nl.openedge.baritus.util;
11
12 import java.text.MessageFormat;
13 import java.util.Locale;
14 import java.util.ResourceBundle;
15
16 import org.apache.commons.logging.Log;
17 import org.apache.commons.logging.LogFactory;
18
19 /***
20 * Utility class for handling localized messages.
21 *
22 * @author Eelco Hillenius
23 */
24 public final class MessageUtils
25 {
26
27 private static Log log = LogFactory.getLog(MessageUtils.class);
28
29 /***
30 * Get localized message for given key.
31 * @param key key of message
32 * @return String localized message
33 */
34 public static String getLocalizedMessage(String key)
35 {
36 return getLocalizedMessage(key, Locale.getDefault());
37 }
38
39 /***
40 * Get localized message for given key and locale.
41 * If locale is null, the default locale will be used.
42 * @param key key of message
43 * @param locale locale for message
44 * @return String localized message
45 */
46 public static String getLocalizedMessage(String key, Locale locale)
47 {
48 String msg = null;
49 try
50 {
51 msg = getBundle(locale).getString(key);
52 }
53 catch (Exception e)
54 {
55 if (log.isDebugEnabled())
56 {
57 log.error(e.getMessage(), e);
58 }
59 }
60 return msg;
61 }
62
63 /***
64 * Get localized message for given key and locale
65 * and format it with the given parameters.
66 * If locale is null, the default locale will be used.
67 * @param key key of message
68 * @param parameters parameters for the message
69 * @return String localized message
70 */
71 public static String getLocalizedMessage(String key, Object[] parameters)
72 {
73 return getLocalizedMessage(key, null, parameters);
74 }
75
76 /***
77 * Get localized message for given key and locale
78 * and format it with the given parameters.
79 * If locale is null, the default locale will be used.
80 * @param key key of message
81 * @param locale locale for message
82 * @param parameters parameters for the message
83 * @return String localized message
84 */
85 public static String getLocalizedMessage(
86 String key,
87 Locale locale,
88 Object[] parameters)
89 {
90 String msg = null;
91 try
92 {
93 msg = getBundle(locale).getString(key);
94 msg = MessageFormat.format(msg, parameters);
95 }
96 catch (Exception e)
97 {
98 if (log.isDebugEnabled())
99 {
100 log.error(e.getMessage(), e);
101 }
102 }
103 return msg;
104 }
105
106
107 private static ResourceBundle getBundle(Locale locale)
108 {
109 ResourceBundle res = null;
110 if (locale != null)
111 {
112 res = ResourceBundle.getBundle("resources", locale);
113 }
114 else
115 {
116 res = ResourceBundle.getBundle("resources");
117 }
118 return res;
119 }
120
121 }