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 1552123 2013-12-18 21:58:08Z 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("en")         = new Locale("en", "")
069     *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
070     *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
071     * </pre>
072     *
073     * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
074     * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
075     * Thus, the result from getVariant() may vary depending on your JDK.</p>
076     *
077     * <p>This method validates the input strictly.
078     * The language code must be lowercase.
079     * The country code must be uppercase.
080     * The separator must be an underscore.
081     * The length must be correct.
082     * </p>
083     *
084     * @param str  the locale String to convert, null returns null
085     * @return a Locale, null if null input
086     * @throws IllegalArgumentException if the string is an invalid format
087     * @see Locale#forLanguageTag(String)
088     */
089    public static Locale toLocale(final String str) {
090        if (str == null) {
091            return null;
092        }
093        if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
094            throw new IllegalArgumentException("Invalid locale format: " + str);
095        }
096        final int len = str.length();
097        if (len < 2) {
098            throw new IllegalArgumentException("Invalid locale format: " + str);
099        }
100        final char ch0 = str.charAt(0);
101        if (ch0 == '_') {
102            if (len < 3) {
103                throw new IllegalArgumentException("Invalid locale format: " + str);
104            }
105            final char ch1 = str.charAt(1);
106            final char ch2 = str.charAt(2);
107            if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
108                throw new IllegalArgumentException("Invalid locale format: " + str);
109            }
110            if (len == 3) {
111                return new Locale("", str.substring(1, 3));
112            }
113            if (len < 5) {
114                throw new IllegalArgumentException("Invalid locale format: " + str);
115            }
116            if (str.charAt(3) != '_') {
117                throw new IllegalArgumentException("Invalid locale format: " + str);
118            }
119            return new Locale("", str.substring(1, 3), str.substring(4));
120        }
121        final char ch1 = str.charAt(1);
122        if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
123            throw new IllegalArgumentException("Invalid locale format: " + str);
124        }
125        if (len == 2) {
126            return new Locale(str);
127        }
128        if (len < 5) {
129            throw new IllegalArgumentException("Invalid locale format: " + str);
130        }
131        if (str.charAt(2) != '_') {
132            throw new IllegalArgumentException("Invalid locale format: " + str);
133        }
134        final char ch3 = str.charAt(3);
135        if (ch3 == '_') {
136            return new Locale(str.substring(0, 2), "", str.substring(4));
137        }
138        final char ch4 = str.charAt(4);
139        if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
140            throw new IllegalArgumentException("Invalid locale format: " + str);
141        }
142        if (len == 5) {
143            return new Locale(str.substring(0, 2), str.substring(3, 5));
144        }
145        if (len < 7) {
146            throw new IllegalArgumentException("Invalid locale format: " + str);
147        }
148        if (str.charAt(5) != '_') {
149            throw new IllegalArgumentException("Invalid locale format: " + str);
150        }
151        return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
152    }
153
154    //-----------------------------------------------------------------------
155    /**
156     * <p>Obtains the list of locales to search through when performing
157     * a locale search.</p>
158     *
159     * <pre>
160     * localeLookupList(Locale("fr","CA","xxx"))
161     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
162     * </pre>
163     *
164     * @param locale  the locale to start from
165     * @return the unmodifiable list of Locale objects, 0 being locale, not null
166     */
167    public static List<Locale> localeLookupList(final Locale locale) {
168        return localeLookupList(locale, locale);
169    }
170
171    //-----------------------------------------------------------------------
172    /**
173     * <p>Obtains the list of locales to search through when performing
174     * a locale search.</p>
175     *
176     * <pre>
177     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
178     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
179     * </pre>
180     *
181     * <p>The result list begins with the most specific locale, then the
182     * next more general and so on, finishing with the default locale.
183     * The list will never contain the same locale twice.</p>
184     *
185     * @param locale  the locale to start from, null returns empty list
186     * @param defaultLocale  the default locale to use if no other is found
187     * @return the unmodifiable list of Locale objects, 0 being locale, not null
188     */
189    public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
190        final List<Locale> list = new ArrayList<Locale>(4);
191        if (locale != null) {
192            list.add(locale);
193            if (locale.getVariant().length() > 0) {
194                list.add(new Locale(locale.getLanguage(), locale.getCountry()));
195            }
196            if (locale.getCountry().length() > 0) {
197                list.add(new Locale(locale.getLanguage(), ""));
198            }
199            if (list.contains(defaultLocale) == false) {
200                list.add(defaultLocale);
201            }
202        }
203        return Collections.unmodifiableList(list);
204    }
205
206    //-----------------------------------------------------------------------
207    /**
208     * <p>Obtains an unmodifiable list of installed locales.</p>
209     * 
210     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
211     * It is more efficient, as the JDK method must create a new array each
212     * time it is called.</p>
213     *
214     * @return the unmodifiable list of available locales
215     */
216    public static List<Locale> availableLocaleList() {
217        return SyncAvoid.AVAILABLE_LOCALE_LIST;
218    }
219
220    //-----------------------------------------------------------------------
221    /**
222     * <p>Obtains an unmodifiable set of installed locales.</p>
223     * 
224     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
225     * It is more efficient, as the JDK method must create a new array each
226     * time it is called.</p>
227     *
228     * @return the unmodifiable set of available locales
229     */
230    public static Set<Locale> availableLocaleSet() {
231        return SyncAvoid.AVAILABLE_LOCALE_SET;
232    }
233
234    //-----------------------------------------------------------------------
235    /**
236     * <p>Checks if the locale specified is in the list of available locales.</p>
237     *
238     * @param locale the Locale object to check if it is available
239     * @return true if the locale is a known locale
240     */
241    public static boolean isAvailableLocale(final Locale locale) {
242        return availableLocaleList().contains(locale);
243    }
244
245    //-----------------------------------------------------------------------
246    /**
247     * <p>Obtains the list of languages supported for a given country.</p>
248     *
249     * <p>This method takes a country code and searches to find the
250     * languages available for that country. Variant locales are removed.</p>
251     *
252     * @param countryCode  the 2 letter country code, null returns empty
253     * @return an unmodifiable List of Locale objects, not null
254     */
255    public static List<Locale> languagesByCountry(final String countryCode) {
256        if (countryCode == null) {
257            return Collections.emptyList();
258        }
259        List<Locale> langs = cLanguagesByCountry.get(countryCode);
260        if (langs == null) {
261            langs = new ArrayList<Locale>();
262            final List<Locale> locales = availableLocaleList();
263            for (int i = 0; i < locales.size(); i++) {
264                final Locale locale = locales.get(i);
265                if (countryCode.equals(locale.getCountry()) &&
266                        locale.getVariant().isEmpty()) {
267                    langs.add(locale);
268                }
269            }
270            langs = Collections.unmodifiableList(langs);
271            cLanguagesByCountry.putIfAbsent(countryCode, langs);
272            langs = cLanguagesByCountry.get(countryCode);
273        }
274        return langs;
275    }
276
277    //-----------------------------------------------------------------------
278    /**
279     * <p>Obtains the list of countries supported for a given language.</p>
280     * 
281     * <p>This method takes a language code and searches to find the
282     * countries available for that language. Variant locales are removed.</p>
283     *
284     * @param languageCode  the 2 letter language code, null returns empty
285     * @return an unmodifiable List of Locale objects, not null
286     */
287    public static List<Locale> countriesByLanguage(final String languageCode) {
288        if (languageCode == null) {
289            return Collections.emptyList();
290        }
291        List<Locale> countries = cCountriesByLanguage.get(languageCode);
292        if (countries == null) {
293            countries = new ArrayList<Locale>();
294            final List<Locale> locales = availableLocaleList();
295            for (int i = 0; i < locales.size(); i++) {
296                final Locale locale = locales.get(i);
297                if (languageCode.equals(locale.getLanguage()) &&
298                        locale.getCountry().length() != 0 &&
299                        locale.getVariant().isEmpty()) {
300                    countries.add(locale);
301                }
302            }
303            countries = Collections.unmodifiableList(countries);
304            cCountriesByLanguage.putIfAbsent(languageCode, countries);
305            countries = cCountriesByLanguage.get(languageCode);
306        }
307        return countries;
308    }
309
310    //-----------------------------------------------------------------------
311    // class to avoid synchronization (Init on demand)
312    static class SyncAvoid {
313        /** Unmodifiable list of available locales. */
314        private static final List<Locale> AVAILABLE_LOCALE_LIST;
315        /** Unmodifiable set of available locales. */
316        private static final Set<Locale> AVAILABLE_LOCALE_SET;
317        
318        static {
319            final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
320            AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
321            AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
322        }
323    }
324
325}