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 1606089 2014-06-27 13:18:55Z ggregory $
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        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}