001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 * 
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 * 
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3;
018
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.Collections;
022import java.util.HashSet;
023import java.util.List;
024import java.util.Locale;
025import java.util.Set;
026import java.util.concurrent.ConcurrentHashMap;
027import java.util.concurrent.ConcurrentMap;
028
029/**
030 * <p>Operations to assist when working with a {@link Locale}.</p>
031 *
032 * <p>This class tries to handle {@code null} input gracefully.
033 * An exception will not be thrown for a {@code null} input.
034 * Each method documents its behaviour in more detail.</p>
035 *
036 * @since 2.2
037 * @version $Id: LocaleUtils.java 1565235 2014-02-06 13:31:43Z sebb $
038 */
039public class LocaleUtils {
040
041    /** Concurrent map of language locales by country. */
042    private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = 
043        new ConcurrentHashMap<String, List<Locale>>();
044
045    /** Concurrent map of country locales by language. */
046    private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = 
047        new ConcurrentHashMap<String, List<Locale>>();
048
049    /**
050     * <p>{@code LocaleUtils} instances should NOT be constructed in standard programming.
051     * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.</p>
052     *
053     * <p>This constructor is public to permit tools that require a JavaBean instance
054     * to operate.</p>
055     */
056    public LocaleUtils() {
057      super();
058    }
059
060    //-----------------------------------------------------------------------
061    /**
062     * <p>Converts a String to a Locale.</p>
063     *
064     * <p>This method takes the string format of a locale and creates the
065     * locale object from it.</p>
066     *
067     * <pre>
068     *   LocaleUtils.toLocale("")           = new Locale("", "")
069     *   LocaleUtils.toLocale("en")         = new Locale("en", "")
070     *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
071     *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
072     * </pre>
073     *
074     * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
075     * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
076     * Thus, the result from getVariant() may vary depending on your JDK.</p>
077     *
078     * <p>This method validates the input strictly.
079     * The language code must be lowercase.
080     * The country code must be uppercase.
081     * The separator must be an underscore.
082     * The length must be correct.
083     * </p>
084     *
085     * @param str  the locale String to convert, null returns null
086     * @return a Locale, null if null input
087     * @throws IllegalArgumentException if the string is an invalid format
088     * @see Locale#forLanguageTag(String)
089     */
090    public static Locale toLocale(final String str) {
091        if (str == null) {
092            return null;
093        }
094        if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
095            return new Locale("", "");
096        }
097        if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
098            throw new IllegalArgumentException("Invalid locale format: " + str);
099        }
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        String[] split = str.split("_", -1);
127        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                } else {
133                    throw new IllegalArgumentException("Invalid locale format: " + str);
134                }
135                
136            case 1:
137                if (StringUtils.isAllLowerCase(split[0]) &&
138                    (split[0].length() == 2 || split[0].length() == 3) &&
139                     split[1].length() == 2 && StringUtils.isAllUpperCase(split[1])) {
140                    return new Locale(split[0], split[1]);
141                } else {
142                    throw new IllegalArgumentException("Invalid locale format: " + str);
143                }
144
145            case 2:
146                if (StringUtils.isAllLowerCase(split[0]) && 
147                    (split[0].length() == 2 || split[0].length() == 3) &&
148                    (split[1].length() == 0 || (split[1].length() == 2 && StringUtils.isAllUpperCase(split[1]))) &&
149                     split[2].length() > 0) {
150                    return new Locale(split[0], split[1], split[2]);
151                }
152
153                //$FALL-THROUGH$
154            default:
155                throw new IllegalArgumentException("Invalid locale format: " + str);
156        }
157    }
158
159    //-----------------------------------------------------------------------
160    /**
161     * <p>Obtains the list of locales to search through when performing
162     * a locale search.</p>
163     *
164     * <pre>
165     * localeLookupList(Locale("fr","CA","xxx"))
166     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
167     * </pre>
168     *
169     * @param locale  the locale to start from
170     * @return the unmodifiable list of Locale objects, 0 being locale, not null
171     */
172    public static List<Locale> localeLookupList(final Locale locale) {
173        return localeLookupList(locale, locale);
174    }
175
176    //-----------------------------------------------------------------------
177    /**
178     * <p>Obtains the list of locales to search through when performing
179     * a locale search.</p>
180     *
181     * <pre>
182     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
183     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
184     * </pre>
185     *
186     * <p>The result list begins with the most specific locale, then the
187     * next more general and so on, finishing with the default locale.
188     * The list will never contain the same locale twice.</p>
189     *
190     * @param locale  the locale to start from, null returns empty list
191     * @param defaultLocale  the default locale to use if no other is found
192     * @return the unmodifiable list of Locale objects, 0 being locale, not null
193     */
194    public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
195        final List<Locale> list = new ArrayList<Locale>(4);
196        if (locale != null) {
197            list.add(locale);
198            if (locale.getVariant().length() > 0) {
199                list.add(new Locale(locale.getLanguage(), locale.getCountry()));
200            }
201            if (locale.getCountry().length() > 0) {
202                list.add(new Locale(locale.getLanguage(), ""));
203            }
204            if (list.contains(defaultLocale) == false) {
205                list.add(defaultLocale);
206            }
207        }
208        return Collections.unmodifiableList(list);
209    }
210
211    //-----------------------------------------------------------------------
212    /**
213     * <p>Obtains an unmodifiable list of installed locales.</p>
214     * 
215     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
216     * It is more efficient, as the JDK method must create a new array each
217     * time it is called.</p>
218     *
219     * @return the unmodifiable list of available locales
220     */
221    public static List<Locale> availableLocaleList() {
222        return SyncAvoid.AVAILABLE_LOCALE_LIST;
223    }
224
225    //-----------------------------------------------------------------------
226    /**
227     * <p>Obtains an unmodifiable set of installed locales.</p>
228     * 
229     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
230     * It is more efficient, as the JDK method must create a new array each
231     * time it is called.</p>
232     *
233     * @return the unmodifiable set of available locales
234     */
235    public static Set<Locale> availableLocaleSet() {
236        return SyncAvoid.AVAILABLE_LOCALE_SET;
237    }
238
239    //-----------------------------------------------------------------------
240    /**
241     * <p>Checks if the locale specified is in the list of available locales.</p>
242     *
243     * @param locale the Locale object to check if it is available
244     * @return true if the locale is a known locale
245     */
246    public static boolean isAvailableLocale(final Locale locale) {
247        return availableLocaleList().contains(locale);
248    }
249
250    //-----------------------------------------------------------------------
251    /**
252     * <p>Obtains the list of languages supported for a given country.</p>
253     *
254     * <p>This method takes a country code and searches to find the
255     * languages available for that country. Variant locales are removed.</p>
256     *
257     * @param countryCode  the 2 letter country code, null returns empty
258     * @return an unmodifiable List of Locale objects, not null
259     */
260    public static List<Locale> languagesByCountry(final String countryCode) {
261        if (countryCode == null) {
262            return Collections.emptyList();
263        }
264        List<Locale> langs = cLanguagesByCountry.get(countryCode);
265        if (langs == null) {
266            langs = new ArrayList<Locale>();
267            final List<Locale> locales = availableLocaleList();
268            for (int i = 0; i < locales.size(); i++) {
269                final Locale locale = locales.get(i);
270                if (countryCode.equals(locale.getCountry()) &&
271                        locale.getVariant().isEmpty()) {
272                    langs.add(locale);
273                }
274            }
275            langs = Collections.unmodifiableList(langs);
276            cLanguagesByCountry.putIfAbsent(countryCode, langs);
277            langs = cLanguagesByCountry.get(countryCode);
278        }
279        return langs;
280    }
281
282    //-----------------------------------------------------------------------
283    /**
284     * <p>Obtains the list of countries supported for a given language.</p>
285     * 
286     * <p>This method takes a language code and searches to find the
287     * countries available for that language. Variant locales are removed.</p>
288     *
289     * @param languageCode  the 2 letter language code, null returns empty
290     * @return an unmodifiable List of Locale objects, not null
291     */
292    public static List<Locale> countriesByLanguage(final String languageCode) {
293        if (languageCode == null) {
294            return Collections.emptyList();
295        }
296        List<Locale> countries = cCountriesByLanguage.get(languageCode);
297        if (countries == null) {
298            countries = new ArrayList<Locale>();
299            final List<Locale> locales = availableLocaleList();
300            for (int i = 0; i < locales.size(); i++) {
301                final Locale locale = locales.get(i);
302                if (languageCode.equals(locale.getLanguage()) &&
303                        locale.getCountry().length() != 0 &&
304                        locale.getVariant().isEmpty()) {
305                    countries.add(locale);
306                }
307            }
308            countries = Collections.unmodifiableList(countries);
309            cCountriesByLanguage.putIfAbsent(languageCode, countries);
310            countries = cCountriesByLanguage.get(languageCode);
311        }
312        return countries;
313    }
314
315    //-----------------------------------------------------------------------
316    // class to avoid synchronization (Init on demand)
317    static class SyncAvoid {
318        /** Unmodifiable list of available locales. */
319        private static final List<Locale> AVAILABLE_LOCALE_LIST;
320        /** Unmodifiable set of available locales. */
321        private static final Set<Locale> AVAILABLE_LOCALE_SET;
322        
323        static {
324            final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
325            AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
326            AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
327        }
328    }
329
330}