1 package net.sf.cantina.util;
2 import org.apache.log4j.Logger;
3
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.Locale;
7
8 /***
9 * This class provides the reverse toString() operation for a Locale object.
10 * Given a String obtained using <code>locale.toString()</code> reconstructs
11 * the locale object by splitting the string in two at the place of the underscore.
12 * @author Stephane JAIS
13 */
14
15 public abstract class Localizer {
16
17 public static Logger logger = Logger.getLogger(Localizer.class);
18 /***
19 * Given a string representing a locale, will try to get the most relevant
20 * locale in the system's supported locales.
21 * @param localeString a string like 'en_US' or 'fr_FR'
22 */
23
24 public static Locale parseLocaleString(String localeString)
25 {
26 Locale result;
27 String[] tokens = localeString.split("_");
28 if (tokens.length == 1)
29 result = new Locale(tokens[0]);
30 else if (tokens.length == 2)
31 result = new Locale(tokens[0],tokens[1]);
32 else if (tokens.length == 3)
33 result = new Locale(tokens[0],tokens[1],tokens[2]);
34 else
35 throw new IllegalArgumentException("["+localeString+"] token not the right format.");
36
37 Collection allLocales = Arrays.asList(Locale.getAvailableLocales());
38 if (!allLocales.contains(result))
39 throw new IllegalArgumentException("["+localeString+"] token does not correspond to a valid locale.");
40 return result;
41 }
42 }
43