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