Coverage Report - org.apache.commons.lang3.LocaleUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
LocaleUtils
100%
82/82
86%
74/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  
  * @version $Id: LocaleUtils.java 1565235 2014-02-06 13:31:43Z sebb $
 38  
  */
 39  
 public class LocaleUtils {
 40  
 
 41  
     /** Concurrent map of language locales by country. */
 42  1
     private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = 
 43  
         new ConcurrentHashMap<String, List<Locale>>();
 44  
 
 45  
     /** Concurrent map of country locales by language. */
 46  1
     private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = 
 47  
         new ConcurrentHashMap<String, List<Locale>>();
 48  
 
 49  
     /**
 50  
      * <p>{@code LocaleUtils} instances should NOT be constructed in standard programming.
 51  
      * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.</p>
 52  
      *
 53  
      * <p>This constructor is public to permit tools that require a JavaBean instance
 54  
      * to operate.</p>
 55  
      */
 56  
     public LocaleUtils() {
 57  1
       super();
 58  1
     }
 59  
 
 60  
     //-----------------------------------------------------------------------
 61  
     /**
 62  
      * <p>Converts a String to a Locale.</p>
 63  
      *
 64  
      * <p>This method takes the string format of a locale and creates the
 65  
      * locale object from it.</p>
 66  
      *
 67  
      * <pre>
 68  
      *   LocaleUtils.toLocale("")           = new Locale("", "")
 69  
      *   LocaleUtils.toLocale("en")         = new Locale("en", "")
 70  
      *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
 71  
      *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
 72  
      * </pre>
 73  
      *
 74  
      * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
 75  
      * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
 76  
      * Thus, the result from getVariant() may vary depending on your JDK.</p>
 77  
      *
 78  
      * <p>This method validates the input strictly.
 79  
      * The language code must be lowercase.
 80  
      * The country code must be uppercase.
 81  
      * The separator must be an underscore.
 82  
      * The length must be correct.
 83  
      * </p>
 84  
      *
 85  
      * @param str  the locale String to convert, null returns null
 86  
      * @return a Locale, null if null input
 87  
      * @throws IllegalArgumentException if the string is an invalid format
 88  
      * @see Locale#forLanguageTag(String)
 89  
      */
 90  
     public static Locale toLocale(final String str) {
 91  194
         if (str == null) {
 92  1
             return null;
 93  
         }
 94  193
         if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
 95  1
             return new Locale("", "");
 96  
         }
 97  192
         if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
 98  3
             throw new IllegalArgumentException("Invalid locale format: " + str);
 99  
         }
 100  189
         final int len = str.length();
 101  189
         if (len < 2) {
 102  1
             throw new IllegalArgumentException("Invalid locale format: " + str);
 103  
         }
 104  188
         final char ch0 = str.charAt(0);
 105  188
         if (ch0 == '_') {
 106  10
             if (len < 3) {
 107  1
                 throw new IllegalArgumentException("Invalid locale format: " + str);
 108  
             }
 109  9
             final char ch1 = str.charAt(1);
 110  9
             final char ch2 = str.charAt(2);
 111  9
             if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
 112  4
                 throw new IllegalArgumentException("Invalid locale format: " + str);
 113  
             }
 114  5
             if (len == 3) {
 115  1
                 return new Locale("", str.substring(1, 3));
 116  
             }
 117  4
             if (len < 5) {
 118  1
                 throw new IllegalArgumentException("Invalid locale format: " + str);
 119  
             }
 120  3
             if (str.charAt(3) != '_') {
 121  1
                 throw new IllegalArgumentException("Invalid locale format: " + str);
 122  
             }
 123  2
             return new Locale("", str.substring(1, 3), str.substring(4));
 124  
         }
 125  
         
 126  178
         String[] split = str.split("_", -1);
 127  178
         int occurrences = split.length -1;
 128  178
         switch (occurrences) {
 129  
             case 0:
 130  54
                 if (StringUtils.isAllLowerCase(str) && (len == 2 || len == 3)) {
 131  50
                     return new Locale(str);
 132  
                 } else {
 133  4
                     throw new IllegalArgumentException("Invalid locale format: " + str);
 134  
                 }
 135  
                 
 136  
             case 1:
 137  115
                 if (StringUtils.isAllLowerCase(split[0]) &&
 138  
                     (split[0].length() == 2 || split[0].length() == 3) &&
 139  
                      split[1].length() == 2 && StringUtils.isAllUpperCase(split[1])) {
 140  108
                     return new Locale(split[0], split[1]);
 141  
                 } else {
 142  7
                     throw new IllegalArgumentException("Invalid locale format: " + str);
 143  
                 }
 144  
 
 145  
             case 2:
 146  9
                 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  8
                     return new Locale(split[0], split[1], split[2]);
 151  
                 }
 152  
 
 153  
                 //$FALL-THROUGH$
 154  
             default:
 155  1
                 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  7
         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  16
         final List<Locale> list = new ArrayList<Locale>(4);
 196  16
         if (locale != null) {
 197  15
             list.add(locale);
 198  15
             if (locale.getVariant().length() > 0) {
 199  5
                 list.add(new Locale(locale.getLanguage(), locale.getCountry()));
 200  
             }
 201  15
             if (locale.getCountry().length() > 0) {
 202  10
                 list.add(new Locale(locale.getLanguage(), ""));
 203  
             }
 204  15
             if (list.contains(defaultLocale) == false) {
 205  5
                 list.add(defaultLocale);
 206  
             }
 207  
         }
 208  16
         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  30
         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  3
         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  22
         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  8
         if (countryCode == null) {
 262  2
             return Collections.emptyList();
 263  
         }
 264  6
         List<Locale> langs = cLanguagesByCountry.get(countryCode);
 265  6
         if (langs == null) {
 266  3
             langs = new ArrayList<Locale>();
 267  3
             final List<Locale> locales = availableLocaleList();
 268  471
             for (int i = 0; i < locales.size(); i++) {
 269  468
                 final Locale locale = locales.get(i);
 270  468
                 if (countryCode.equals(locale.getCountry()) &&
 271  
                         locale.getVariant().isEmpty()) {
 272  4
                     langs.add(locale);
 273  
                 }
 274  
             }
 275  3
             langs = Collections.unmodifiableList(langs);
 276  3
             cLanguagesByCountry.putIfAbsent(countryCode, langs);
 277  3
             langs = cLanguagesByCountry.get(countryCode);
 278  
         }
 279  6
         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  8
         if (languageCode == null) {
 294  2
             return Collections.emptyList();
 295  
         }
 296  6
         List<Locale> countries = cCountriesByLanguage.get(languageCode);
 297  6
         if (countries == null) {
 298  3
             countries = new ArrayList<Locale>();
 299  3
             final List<Locale> locales = availableLocaleList();
 300  471
             for (int i = 0; i < locales.size(); i++) {
 301  468
                 final Locale locale = locales.get(i);
 302  468
                 if (languageCode.equals(locale.getLanguage()) &&
 303  
                         locale.getCountry().length() != 0 &&
 304  
                         locale.getVariant().isEmpty()) {
 305  6
                     countries.add(locale);
 306  
                 }
 307  
             }
 308  3
             countries = Collections.unmodifiableList(countries);
 309  3
             cCountriesByLanguage.putIfAbsent(languageCode, countries);
 310  3
             countries = cCountriesByLanguage.get(languageCode);
 311  
         }
 312  6
         return countries;
 313  
     }
 314  
 
 315  
     //-----------------------------------------------------------------------
 316  
     // class to avoid synchronization (Init on demand)
 317  33
     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  1
             final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
 325  1
             AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
 326  1
             AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
 327  1
         }
 328  
     }
 329  
 
 330  
 }