View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package javax.faces.component;
20  
21  import java.util.ArrayList;
22  import java.util.Arrays;
23  import java.util.Collections;
24  import java.util.HashSet;
25  import java.util.List;
26  import java.util.Locale;
27  import java.util.Set;
28  import java.util.concurrent.ConcurrentHashMap;
29  import java.util.concurrent.ConcurrentMap;
30  
31  /**
32   * <p>Operations to assist when working with a {@link Locale}.</p>
33   *
34   * <p>This class tries to handle {@code null} input gracefully.
35   * An exception will not be thrown for a {@code null} input.
36   * Each method documents its behaviour in more detail.</p>
37   *
38   * NOTE: This a copy of commons lang LocaleUtils, to use it inside MyFaces 
39   *
40   * @since 2.2
41   * @version $Id$
42   */
43  class _LocaleUtils
44  {
45  
46      /** Concurrent map of language locales by country. */
47      private static final ConcurrentMap<String, List<Locale>> LANGUAGES_BY_COUNTRY =
48              new ConcurrentHashMap<String, List<Locale>>();
49  
50      /** Concurrent map of country locales by language. */
51      private static final ConcurrentMap<String, List<Locale>> COUNTRIES_BY_LANGUAGE =
52              new ConcurrentHashMap<String, List<Locale>>();
53  
54      /**
55       * <p>{@code _LocaleUtils} instances should NOT be constructed in standard programming.
56       * Instead, the class should be used as {@code _LocaleUtils.toLocale("en_GB");}.</p>
57       *
58       * <p>This constructor is public to permit tools that require a JavaBean instance
59       * to operate.</p>
60       */
61      public _LocaleUtils()
62      {
63          super();
64      }
65  
66      //-----------------------------------------------------------------------
67  
68      /**
69       * <p>Converts a String to a Locale.</p>
70       *
71       * <p>This method takes the string format of a locale and creates the
72       * locale object from it.</p>
73       *
74       * <pre>
75       *   _LocaleUtils.toLocale("en")         = new Locale("en", "")
76       *   _LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
77       *   _LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
78       * </pre>
79       *
80       * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
81       * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
82       * Thus, the result from getVariant() may vary depending on your JDK.</p>
83       *
84       * <p>This method validates the input strictly.
85       * The language code must be lowercase.
86       * The country code must be uppercase.
87       * The separator must be an underscore.
88       * The length must be correct.
89       * </p>
90       *
91       * @param str  the locale String to convert, null returns null
92       * @return a Locale, null if null input
93       * @throws IllegalArgumentException if the string is an invalid format
94       */
95      public static Locale toLocale(String str)
96      {
97          if (str == null)
98          {
99              return null;
100         }
101         int len = str.length();
102         if (len != 2 && len != 5 && len < 7)
103         {
104             throw new IllegalArgumentException("Invalid locale format: " + str);
105         }
106         char ch0 = str.charAt(0);
107         char ch1 = str.charAt(1);
108         if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z')
109         {
110             throw new IllegalArgumentException("Invalid locale format: " + str);
111         }
112         if (len == 2)
113         {
114             return new Locale(str, "");
115         }
116         else
117         {
118             if (str.charAt(2) != '_')
119             {
120                 throw new IllegalArgumentException("Invalid locale format: " + str);
121             }
122             char ch3 = str.charAt(3);
123             if (ch3 == '_')
124             {
125                 return new Locale(str.substring(0, 2), "", str.substring(4));
126             }
127             char ch4 = str.charAt(4);
128             if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z')
129             {
130                 throw new IllegalArgumentException("Invalid locale format: " + str);
131             }
132             if (len == 5)
133             {
134                 return new Locale(str.substring(0, 2), str.substring(3, 5));
135             }
136             else
137             {
138                 if (str.charAt(5) != '_')
139                 {
140                     throw new IllegalArgumentException("Invalid locale format: " + str);
141                 }
142                 return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
143             }
144         }
145     }
146 
147     //-----------------------------------------------------------------------
148 
149     /**
150      * <p>Obtains the list of locales to search through when performing
151      * a locale search.</p>
152      *
153      * <pre>
154      * localeLookupList(Locale("fr","CA","xxx"))
155      *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
156      * </pre>
157      *
158      * @param locale  the locale to start from
159      * @return the unmodifiable list of Locale objects, 0 being locale, not null
160      */
161     public static List<Locale> localeLookupList(Locale locale)
162     {
163         return localeLookupList(locale, locale);
164     }
165 
166     //-----------------------------------------------------------------------
167 
168     /**
169      * <p>Obtains the list of locales to search through when performing
170      * a locale search.</p>
171      *
172      * <pre>
173      * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
174      *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
175      * </pre>
176      *
177      * <p>The result list begins with the most specific locale, then the
178      * next more general and so on, finishing with the default locale.
179      * The list will never contain the same locale twice.</p>
180      *
181      * @param locale  the locale to start from, null returns empty list
182      * @param defaultLocale  the default locale to use if no other is found
183      * @return the unmodifiable list of Locale objects, 0 being locale, not null
184      */
185     public static List<Locale> localeLookupList(Locale locale, Locale defaultLocale)
186     {
187         List<Locale> list = new ArrayList<Locale>(4);
188         if (locale != null)
189         {
190             list.add(locale);
191             if (locale.getVariant().length() > 0)
192             {
193                 list.add(new Locale(locale.getLanguage(), locale.getCountry()));
194             }
195             if (locale.getCountry().length() > 0)
196             {
197                 list.add(new Locale(locale.getLanguage(), ""));
198             }
199             if (!list.contains(defaultLocale))
200             {
201                 list.add(defaultLocale);
202             }
203         }
204         return Collections.unmodifiableList(list);
205     }
206 
207     //-----------------------------------------------------------------------
208 
209     /**
210      * <p>Obtains an unmodifiable list of installed locales.</p>
211      *
212      * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
213      * It is more efficient, as the JDK method must create a new array each
214      * time it is called.</p>
215      *
216      * @return the unmodifiable list of available locales
217      */
218     public static List<Locale> availableLocaleList()
219     {
220         return SyncAvoid.AVAILABLE_LOCALE_LIST;
221     }
222 
223     //-----------------------------------------------------------------------
224 
225     /**
226      * <p>Obtains an unmodifiable set of installed locales.</p>
227      *
228      * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
229      * It is more efficient, as the JDK method must create a new array each
230      * time it is called.</p>
231      *
232      * @return the unmodifiable set of available locales
233      */
234     public static Set<Locale> availableLocaleSet()
235     {
236         return SyncAvoid.AVAILABLE_LOCALE_SET;
237     }
238 
239     //-----------------------------------------------------------------------
240 
241     /**
242      * <p>Checks if the locale specified is in the list of available locales.</p>
243      *
244      * @param locale the Locale object to check if it is available
245      * @return true if the locale is a known locale
246      */
247     public static boolean isAvailableLocale(Locale locale)
248     {
249         return availableLocaleList().contains(locale);
250     }
251 
252     //-----------------------------------------------------------------------
253 
254     /**
255      * <p>Obtains the list of languages supported for a given country.</p>
256      *
257      * <p>This method takes a country code and searches to find the
258      * languages available for that country. Variant locales are removed.</p>
259      *
260      * @param countryCode  the 2 letter country code, null returns empty
261      * @return an unmodifiable List of Locale objects, not null
262      */
263     public static List<Locale> languagesByCountry(String countryCode)
264     {
265         if (countryCode == null)
266         {
267             return Collections.emptyList();
268         }
269         List<Locale> langs = LANGUAGES_BY_COUNTRY.get(countryCode);
270         if (langs == null)
271         {
272             langs = new ArrayList<Locale>();
273             List<Locale> locales = availableLocaleList();
274             for (int i = 0; i < locales.size(); i++)
275             {
276                 Locale locale = locales.get(i);
277                 if (countryCode.equals(locale.getCountry()) &&
278                         locale.getVariant().length() == 0)
279                 {
280                     langs.add(locale);
281                 }
282             }
283             langs = Collections.unmodifiableList(langs);
284             LANGUAGES_BY_COUNTRY.putIfAbsent(countryCode, langs);
285             langs = LANGUAGES_BY_COUNTRY.get(countryCode);
286         }
287         return langs;
288     }
289 
290     //-----------------------------------------------------------------------
291 
292     /**
293      * <p>Obtains the list of countries supported for a given language.</p>
294      *
295      * <p>This method takes a language code and searches to find the
296      * countries available for that language. Variant locales are removed.</p>
297      *
298      * @param languageCode  the 2 letter language code, null returns empty
299      * @return an unmodifiable List of Locale objects, not null
300      */
301     public static List<Locale> countriesByLanguage(String languageCode)
302     {
303         if (languageCode == null)
304         {
305             return Collections.emptyList();
306         }
307         List<Locale> countries = COUNTRIES_BY_LANGUAGE.get(languageCode);
308         if (countries == null)
309         {
310             countries = new ArrayList<Locale>();
311             List<Locale> locales = availableLocaleList();
312             for (int i = 0; i < locales.size(); i++)
313             {
314                 Locale locale = locales.get(i);
315                 if (languageCode.equals(locale.getLanguage()) &&
316                         locale.getCountry().length() != 0 &&
317                         locale.getVariant().length() == 0)
318                 {
319                     countries.add(locale);
320                 }
321             }
322             countries = Collections.unmodifiableList(countries);
323             COUNTRIES_BY_LANGUAGE.putIfAbsent(languageCode, countries);
324             countries = COUNTRIES_BY_LANGUAGE.get(languageCode);
325         }
326         return countries;
327     }
328 
329     //-----------------------------------------------------------------------
330     // class to avoid synchronization
331     static class SyncAvoid
332     {
333         /** Unmodifiable list of available locales. */
334         private static final List<Locale> AVAILABLE_LOCALE_LIST;
335         /** Unmodifiable set of available locales. */
336         private static final Set<Locale> AVAILABLE_LOCALE_SET;
337 
338         static
339         {
340             List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
341             AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
342             AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(availableLocaleList()));
343         }
344     }
345 
346 }