1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.commons.util;
20
21 import java.util.Locale;
22 import java.util.StringTokenizer;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27
28
29
30
31
32
33 public final class LocaleUtils
34 {
35 private static final Log log = LogFactory.getLog(LocaleUtils.class);
36
37
38 private LocaleUtils()
39 {
40
41 }
42
43
44
45
46
47
48
49
50 public static Locale toLocale(String localeString)
51 {
52 if ((localeString == null) || (localeString.length() == 0))
53 {
54 Locale locale = Locale.getDefault();
55 if(log.isWarnEnabled())
56 log.warn("Locale name in faces-config.xml null or empty, setting locale to default locale : "+locale.toString());
57 return locale;
58 }
59
60 int separatorCountry = localeString.indexOf('_');
61 char separator;
62 if (separatorCountry >= 0) {
63 separator = '_';
64 }
65 else
66 {
67 separatorCountry = localeString.indexOf('-');
68 separator = '-';
69 }
70
71 String language, country, variant;
72 if (separatorCountry < 0)
73 {
74 language = localeString;
75 country = variant = "";
76 }
77 else
78 {
79 language = localeString.substring(0, separatorCountry);
80
81 int separatorVariant = localeString.indexOf(separator, separatorCountry + 1);
82 if (separatorVariant < 0)
83 {
84 country = localeString.substring(separatorCountry + 1);
85 variant = "";
86 }
87 else
88 {
89 country = localeString.substring(separatorCountry + 1, separatorVariant);
90 variant = localeString.substring(separatorVariant + 1);
91 }
92 }
93
94 return new Locale(language, country, variant);
95 }
96
97
98
99
100
101
102
103
104 public static Locale converterTagLocaleFromString(String name)
105 {
106 try
107 {
108 Locale locale;
109 StringTokenizer st = new StringTokenizer(name, "_");
110 String language = st.nextToken();
111
112 if(st.hasMoreTokens())
113 {
114 String country = st.nextToken();
115
116 if(st.hasMoreTokens())
117 {
118 String variant = st.nextToken();
119 locale = new Locale(language, country, variant);
120 }
121 else
122 {
123 locale = new Locale(language, country);
124 }
125 }
126 else
127 {
128 locale = new Locale(language);
129 }
130
131
132 return locale;
133 }
134 catch(Exception e)
135 {
136 throw new IllegalArgumentException("Locale parsing exception - " +
137 "invalid string representation '" + name + "'");
138 }
139 }
140 }