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