1 |
package skrueger.i8n; |
2 |
|
3 |
import java.util.Locale; |
4 |
import java.util.Set; |
5 |
import java.util.TreeSet; |
6 |
|
7 |
import org.apache.log4j.Logger; |
8 |
|
9 |
public class I8NUtil { |
10 |
static final Logger LOGGER = Logger.getLogger(I8NUtil.class); |
11 |
|
12 |
private static Set<String> languageCodes = new TreeSet<String>(); |
13 |
static { |
14 |
for (Locale locale : java.util.Locale.getAvailableLocales()) { |
15 |
getLanguageCodes().add(locale.getLanguage()); |
16 |
} |
17 |
// for (String code : java.util.Locale.getISOLanguages()) { |
18 |
// getLanguageCodes().add(code); |
19 |
// } |
20 |
} |
21 |
|
22 |
/** |
23 |
* @author Stefan Alfons Krüger |
24 |
* @param code |
25 |
* @return true if the code paramter is a valid ISO Language code |
26 |
*/ |
27 |
public static boolean isValidISOLangCode(String code) { |
28 |
return getLanguageCodes().contains(code); |
29 |
} |
30 |
|
31 |
/** |
32 |
* @return All language codes available in |
33 |
* java.util.Locale.getISOLanguages() without duplicates. |
34 |
*/ |
35 |
public static Set<String> getLanguageCodes() { |
36 |
return languageCodes; |
37 |
} |
38 |
|
39 |
/** |
40 |
* @param code |
41 |
* A two-letter language code. |
42 |
* @return <code>null</code> or one (of many possible) {@link Locale} that |
43 |
* uses this language. |
44 |
*/ |
45 |
public static Locale getLocaleFor(String code) { |
46 |
for (Locale l : Locale.getAvailableLocales()) { |
47 |
// System.out.println(l.getLanguage()+" not = "+code); |
48 |
if (l.getLanguage().toLowerCase().equals(code.toLowerCase())) { |
49 |
return l; |
50 |
} |
51 |
} |
52 |
LOGGER.error("Can't create a Locale for code "+code+"! Returning the system default locale to avoid NPEs."); |
53 |
return Locale.getDefault(); |
54 |
} |
55 |
} |