KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > util > LocaleUtils


1 /**
2  * $RCSfile: LocaleUtils.java,v $
3  * $Revision: 1.6 $
4  * $Date: 2005/04/11 21:05:19 $
5  *
6  * Copyright (C) 2004 Jive Software. All rights reserved.
7  *
8  * This software is published under the terms of the GNU Public License (GPL),
9  * a copy of which is included in this distribution.
10  */

11
12 package org.jivesoftware.util;
13
14 import java.text.*;
15 import java.util.*;
16
17 /**
18  * A set of methods for retrieving and converting locale specific strings and numbers.
19  *
20  * @author Jive Software
21  */

22 public class LocaleUtils {
23
24     private static String JavaDoc[][] timeZoneList = null;
25
26     private static Object JavaDoc timeZoneLock = new Object JavaDoc();
27
28     // The basename to use for looking up the appropriate resource bundles
29
// TODO - extract this out into a test that grabs the resource name from JiveGlobals
30
// and defaults to messenger_i18n if nothing set.
31
private static final String JavaDoc resourceBaseName = "messenger_i18n";
32
33     private LocaleUtils() {
34     }
35
36     /**
37      * Converts a locale string like "en", "en_US" or "en_US_win" to a Java
38      * locale object. If the conversion fails, null is returned.
39      *
40      * @param localeCode the locale code for a Java locale. See the {@link java.util.Locale}
41      * class for more details.
42      */

43     public static Locale localeCodeToLocale(String JavaDoc localeCode) {
44         Locale locale = null;
45         if (localeCode != null) {
46             String JavaDoc language = null;
47             String JavaDoc country = null;
48             String JavaDoc variant = null;
49             if (localeCode != null) {
50                 StringTokenizer tokenizer = new StringTokenizer(localeCode, "_");
51                 if (tokenizer.hasMoreTokens()) {
52                     language = tokenizer.nextToken();
53                     if (tokenizer.hasMoreTokens()) {
54                         country = tokenizer.nextToken();
55                         if (tokenizer.hasMoreTokens()) {
56                             variant = tokenizer.nextToken();
57                         }
58                     }
59                 }
60             }
61             locale = new Locale(language,
62                     ((country != null) ? country : ""),
63                     ((variant != null) ? variant : ""));
64         }
65         return locale;
66     }
67
68     /**
69      * Returns a list of all available time zone's as a String [][]. The first
70      * entry in each list item is the timeZoneID, and the second is the
71      * display name.<p>
72      * <p/>
73      * Normally, there are many ID's that correspond to a single display name.
74      * However, the list has been paired down so that a display name only
75      * appears once. Normally, the time zones will be returned in order:
76      * -12 GMT,..., +0GMT,... +12GMT..., etc.
77      *
78      * @return a list of time zones, as a tuple of the zime zone ID, and its
79      * display name.
80      */

81     public static String JavaDoc[][] getTimeZoneList() {
82         if (timeZoneList == null) {
83             synchronized (timeZoneLock) {
84                 if (timeZoneList == null) {
85                     Date now = new Date();
86
87                     String JavaDoc[] timeZoneIDs = TimeZone.getAvailableIDs();
88                     Locale jiveLocale = JiveGlobals.getLocale();
89                     // Now, create String[][] using the unique zones.
90
timeZoneList = new String JavaDoc[timeZoneIDs.length][2];
91                     for (int i = 0; i < timeZoneList.length; i++) {
92                         String JavaDoc zoneID = timeZoneIDs[i];
93                         timeZoneList[i][0] = zoneID;
94                         timeZoneList[i][1] = getTimeZoneName(zoneID, now, jiveLocale);
95                     }
96                 }
97             }
98         }
99         return timeZoneList;
100     }
101
102     /**
103      * Returns the display name for a time zone. The display name is the name
104      * specified by the Java TimeZone class, with the addition of the GMT offset
105      * for human readability.
106      *
107      * @param zoneID the time zone to get the name for.
108      * @param now the current date.
109      * @param locale the locale to use.
110      * @return the display name for the time zone.
111      */

112     private static String JavaDoc getTimeZoneName(String JavaDoc zoneID, Date now, Locale locale) {
113         TimeZone zone = TimeZone.getTimeZone(zoneID);
114         StringBuilder JavaDoc buf = new StringBuilder JavaDoc();
115         // Add in the GMT part to the name. First, figure out the offset.
116
int offset = zone.getRawOffset();
117         if (zone.inDaylightTime(now) && zone.useDaylightTime()) {
118             offset += (int)JiveConstants.HOUR;
119         }
120
121         if (offset < 0) {
122             buf.append("GMT-");
123         }
124         else {
125             buf.append("GMT+");
126         }
127         offset = Math.abs(offset);
128         int hours = offset / (int)JiveConstants.HOUR;
129         int minutes = (offset % (int)JiveConstants.HOUR) / (int)JiveConstants.MINUTE;
130         buf.append(hours).append(":");
131         if (minutes < 10) {
132             buf.append("0").append(minutes);
133         }
134         else {
135             buf.append(minutes);
136         }
137         buf.append(" - ").append(zoneID.replace('_', ' ').replace('/', ' ')).append(" ");
138         buf.append(zone.getDisplayName(true, TimeZone.SHORT, locale).replace('_', ' ').replace('/', ' '));
139         return buf.toString();
140     }
141
142     /**
143      * Returns the specified resource bundle, which is a properties file
144      * that aids in localization of skins. This method is handy since it
145      * uses the class loader that other Jive classes are loaded from (hence,
146      * it can load bundles that are stored in jive.jar).
147      *
148      * @param baseName the name of the resource bundle to load.
149      * @param locale the desired Locale.
150      * @return the specified resource bundle, if it exists.
151      */

152     public static ResourceBundle getResourceBundle(String JavaDoc baseName,
153                                                    Locale locale) {
154         return ResourceBundle.getBundle(baseName, locale);
155     }
156
157     /**
158      * Returns an internationalized string loaded from a resource bundle.
159      * The locale used will be the locale specified by JiveGlobals.getLocale().
160      *
161      * @param key the key to use for retrieving the string from the
162      * appropriate resource bundle.
163      * @return the localized string.
164      */

165     public static String JavaDoc getLocalizedString(String JavaDoc key) {
166         return getLocalizedString(key, JiveGlobals.getLocale(), null);
167     }
168
169     /**
170      * Returns an internationalized string loaded from a resource bundle using
171      * the passed in Locale.
172      *
173      * @param key the key to use for retrieving the string from the
174      * appropriate resource bundle.
175      * @param locale the locale to use for retrieving the appropriate
176      * locale-specific string.
177      * @return the localized string.
178      */

179     public static String JavaDoc getLocalizedString(String JavaDoc key, Locale locale) {
180         return getLocalizedString(key, locale, null);
181     }
182
183     /**
184      * Returns an internationalized string loaded from a resource bundle using
185      * the locale specified by JiveGlobals.getLocale() substituting the passed
186      * in arguments. Substitution is handled using the
187      * {@link java.text.MessageFormat} class.
188      *
189      * @param key the key to use for retrieving the string from the
190      * appropriate resource bundle.
191      * @param arguments a list of objects to use which are formatted, then
192      * inserted into the pattern at the appropriate places.
193      * @return the localized string.
194      */

195     public static String JavaDoc getLocalizedString(String JavaDoc key, List arguments) {
196         return getLocalizedString(key, JiveGlobals.getLocale(), arguments);
197     }
198
199     /**
200      * Returns an internationalized string loaded from a resource bundle using
201      * the passed in Locale substituting the passed in arguments. Substitution
202      * is handled using the {@link java.text.MessageFormat} class.
203      *
204      * @param key the key to use for retrieving the string from the
205      * appropriate resource bundle.
206      * @param locale the locale to use for retrieving the appropriate
207      * locale-specific string.
208      * @param arguments a list of objects to use which are formatted, then
209      * inserted into the pattern at the appropriate places.
210      * @return the localized string.
211      */

212     public static String JavaDoc getLocalizedString(String JavaDoc key, Locale locale, List arguments) {
213         if (key == null) {
214             throw new NullPointerException JavaDoc("Key cannot be null");
215         }
216         if (locale == null) {
217             locale = JiveGlobals.getLocale();
218         }
219
220         String JavaDoc value = "";
221
222         // See if the bundle has a value
223
try {
224             // The jdk caches resource bundles on it's own, so we won't bother.
225
ResourceBundle bundle = ResourceBundle.getBundle(resourceBaseName, locale);
226             value = bundle.getString(key);
227             // perform argument substitutions
228
if (arguments != null) {
229                 MessageFormat messageFormat = new MessageFormat("");
230                 messageFormat.setLocale(bundle.getLocale());
231                 messageFormat.applyPattern(value);
232                 try {
233                     // This isn't fool-proof, but it's better than nothing
234
// The idea is to try and convert strings into the
235
// types of objects that the formatters expects
236
// i.e. Numbers and Dates
237
Format[] formats = messageFormat.getFormats();
238                     for (int i = 0; i < formats.length; i++) {
239                         Format format = formats[i];
240                         if (format != null) {
241                             if (format instanceof DateFormat) {
242                                 if (arguments.size() > i) {
243                                     Object JavaDoc val = arguments.get(i);
244                                     if (val instanceof String JavaDoc) {
245                                         DateFormat dateFmt = (DateFormat)format;
246                                         try {
247                                             val = dateFmt.parse((String JavaDoc)val);
248                                             arguments.set(i, val);
249                                         }
250                                         catch (ParseException e) {
251                                             Log.error(e);
252                                         }
253                                     }
254                                 }
255                             }
256                             else if (format instanceof NumberFormat) {
257                                 if (arguments.size() > i) {
258                                     Object JavaDoc val = arguments.get(i);
259                                     if (val instanceof String JavaDoc) {
260                                         NumberFormat nbrFmt = (NumberFormat)format;
261                                         try {
262                                             val = nbrFmt.parse((String JavaDoc)val);
263                                             arguments.set(i, val);
264                                         }
265                                         catch (ParseException e) {
266                                             Log.error(e);
267                                         }
268                                     }
269                                 }
270                             }
271                         }
272                     }
273                     value = messageFormat.format(arguments.toArray());
274                 }
275                 catch (IllegalArgumentException JavaDoc e) {
276                     Log.error("Unable to format resource string for key: "
277                             + key + ", argument type not supported");
278                     value = "";
279                 }
280             }
281         }
282         catch (java.util.MissingResourceException JavaDoc mre) {
283             Log.warn("Missing resource for key: " + key
284                     + " in locale " + locale.toString());
285             value = "";
286         }
287
288         return value;
289     }
290
291     /**
292      *
293      */

294     public static String JavaDoc getLocalizedNumber(long number) {
295         return NumberFormat.getInstance().format(number);
296     }
297
298     /**
299      *
300      */

301     public static String JavaDoc getLocalizedNumber(long number, Locale locale) {
302         return NumberFormat.getInstance(locale).format(number);
303     }
304
305     /**
306      *
307      */

308     public static String JavaDoc getLocalizedNumber(double number) {
309         return NumberFormat.getInstance().format(number);
310     }
311
312     /**
313      *
314      */

315     public static String JavaDoc getLocalizedNumber(double number, Locale locale) {
316         return NumberFormat.getInstance(locale).format(number);
317     }
318 }
319
Popular Tags