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 1555043 2014-01-03 10:26:54Z britter $
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        final char ch1 = str.charAt(1);
126        if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
127            throw new IllegalArgumentException("Invalid locale format: " + str);
128        }
129        if (len == 2) {
130            return new Locale(str);
131        }
132        if (len < 5) {
133            throw new IllegalArgumentException("Invalid locale format: " + str);
134        }
135        if (str.charAt(2) != '_') {
136            throw new IllegalArgumentException("Invalid locale format: " + str);
137        }
138        final char ch3 = str.charAt(3);
139        if (ch3 == '_') {
140            return new Locale(str.substring(0, 2), "", str.substring(4));
141        }
142        final char ch4 = str.charAt(4);
143        if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
144            throw new IllegalArgumentException("Invalid locale format: " + str);
145        }
146        if (len == 5) {
147            return new Locale(str.substring(0, 2), str.substring(3, 5));
148        }
149        if (len < 7) {
150            throw new IllegalArgumentException("Invalid locale format: " + str);
151        }
152        if (str.charAt(5) != '_') {
153            throw new IllegalArgumentException("Invalid locale format: " + str);
154        }
155        return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
156    }
157
158    //-----------------------------------------------------------------------
159    /**
160     * <p>Obtains the list of locales to search through when performing
161     * a locale search.</p>
162     *
163     * <pre>
164     * localeLookupList(Locale("fr","CA","xxx"))
165     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
166     * </pre>
167     *
168     * @param locale  the locale to start from
169     * @return the unmodifiable list of Locale objects, 0 being locale, not null
170     */
171    public static List<Locale> localeLookupList(final Locale locale) {
172        return localeLookupList(locale, locale);
173    }
174
175    //-----------------------------------------------------------------------
176    /**
177     * <p>Obtains the list of locales to search through when performing
178     * a locale search.</p>
179     *
180     * <pre>
181     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
182     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
183     * </pre>
184     *
185     * <p>The result list begins with the most specific locale, then the
186     * next more general and so on, finishing with the default locale.
187     * The list will never contain the same locale twice.</p>
188     *
189     * @param locale  the locale to start from, null returns empty list
190     * @param defaultLocale  the default locale to use if no other is found
191     * @return the unmodifiable list of Locale objects, 0 being locale, not null
192     */
193    public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
194        final List<Locale> list = new ArrayList<Locale>(4);
195        if (locale != null) {
196            list.add(locale);
197            if (locale.getVariant().length() > 0) {
198                list.add(new Locale(locale.getLanguage(), locale.getCountry()));
199            }
200            if (locale.getCountry().length() > 0) {
201                list.add(new Locale(locale.getLanguage(), ""));
202            }
203            if (list.contains(defaultLocale) == false) {
204                list.add(defaultLocale);
205            }
206        }
207        return Collections.unmodifiableList(list);
208    }
209
210    //-----------------------------------------------------------------------
211    /**
212     * <p>Obtains an unmodifiable list of installed locales.</p>
213     * 
214     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
215     * It is more efficient, as the JDK method must create a new array each
216     * time it is called.</p>
217     *
218     * @return the unmodifiable list of available locales
219     */
220    public static List<Locale> availableLocaleList() {
221        return SyncAvoid.AVAILABLE_LOCALE_LIST;
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        return SyncAvoid.AVAILABLE_LOCALE_SET;
236    }
237
238    //-----------------------------------------------------------------------
239    /**
240     * <p>Checks if the locale specified is in the list of available locales.</p>
241     *
242     * @param locale the Locale object to check if it is available
243     * @return true if the locale is a known locale
244     */
245    public static boolean isAvailableLocale(final Locale locale) {
246        return availableLocaleList().contains(locale);
247    }
248
249    //-----------------------------------------------------------------------
250    /**
251     * <p>Obtains the list of languages supported for a given country.</p>
252     *
253     * <p>This method takes a country code and searches to find the
254     * languages available for that country. Variant locales are removed.</p>
255     *
256     * @param countryCode  the 2 letter country code, null returns empty
257     * @return an unmodifiable List of Locale objects, not null
258     */
259    public static List<Locale> languagesByCountry(final String countryCode) {
260        if (countryCode == null) {
261            return Collections.emptyList();
262        }
263        List<Locale> langs = cLanguagesByCountry.get(countryCode);
264        if (langs == null) {
265            langs = new ArrayList<Locale>();
266            final List<Locale> locales = availableLocaleList();
267            for (int i = 0; i < locales.size(); i++) {
268                final Locale locale = locales.get(i);
269                if (countryCode.equals(locale.getCountry()) &&
270                        locale.getVariant().isEmpty()) {
271                    langs.add(locale);
272                }
273            }
274            langs = Collections.unmodifiableList(langs);
275            cLanguagesByCountry.putIfAbsent(countryCode, langs);
276            langs = cLanguagesByCountry.get(countryCode);
277        }
278        return langs;
279    }
280
281    //-----------------------------------------------------------------------
282    /**
283     * <p>Obtains the list of countries supported for a given language.</p>
284     * 
285     * <p>This method takes a language code and searches to find the
286     * countries available for that language. Variant locales are removed.</p>
287     *
288     * @param languageCode  the 2 letter language code, null returns empty
289     * @return an unmodifiable List of Locale objects, not null
290     */
291    public static List<Locale> countriesByLanguage(final String languageCode) {
292        if (languageCode == null) {
293            return Collections.emptyList();
294        }
295        List<Locale> countries = cCountriesByLanguage.get(languageCode);
296        if (countries == null) {
297            countries = new ArrayList<Locale>();
298            final List<Locale> locales = availableLocaleList();
299            for (int i = 0; i < locales.size(); i++) {
300                final Locale locale = locales.get(i);
301                if (languageCode.equals(locale.getLanguage()) &&
302                        locale.getCountry().length() != 0 &&
303                        locale.getVariant().isEmpty()) {
304                    countries.add(locale);
305                }
306            }
307            countries = Collections.unmodifiableList(countries);
308            cCountriesByLanguage.putIfAbsent(languageCode, countries);
309            countries = cCountriesByLanguage.get(languageCode);
310        }
311        return countries;
312    }
313
314    //-----------------------------------------------------------------------
315    // class to avoid synchronization (Init on demand)
316    static class SyncAvoid {
317        /** Unmodifiable list of available locales. */
318        private static final List<Locale> AVAILABLE_LOCALE_LIST;
319        /** Unmodifiable set of available locales. */
320        private static final Set<Locale> AVAILABLE_LOCALE_SET;
321        
322        static {
323            final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
324            AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
325            AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
326        }
327    }
328
329}