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  
  * @version $Id$
 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
         final String[] split = str.split("_", -1);
 127  178
         final 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  
                 }
 133  4
             throw new IllegalArgumentException("Invalid locale format: " + str);
 134  
                 
 135  
             case 1:
 136  115
                 if (StringUtils.isAllLowerCase(split[0]) &&
 137  
                     (split[0].length() == 2 || split[0].length() == 3) &&
 138  
                      split[1].length() == 2 && StringUtils.isAllUpperCase(split[1])) {
 139  108
                     return new Locale(split[0], split[1]);
 140  
                 }
 141  7
             throw new IllegalArgumentException("Invalid locale format: " + str);
 142  
 
 143  
             case 2:
 144  9
                 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  8
                     return new Locale(split[0], split[1], split[2]);
 149  
                 }
 150  
 
 151  
                 //$FALL-THROUGH$
 152  
             default:
 153  1
                 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  7
         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  16
         final List<Locale> list = new ArrayList<Locale>(4);
 194  16
         if (locale != null) {
 195  15
             list.add(locale);
 196  15
             if (locale.getVariant().length() > 0) {
 197  5
                 list.add(new Locale(locale.getLanguage(), locale.getCountry()));
 198  
             }
 199  15
             if (locale.getCountry().length() > 0) {
 200  10
                 list.add(new Locale(locale.getLanguage(), ""));
 201  
             }
 202  15
             if (list.contains(defaultLocale) == false) {
 203  5
                 list.add(defaultLocale);
 204  
             }
 205  
         }
 206  16
         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  30
         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  3
         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  22
         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  8
         if (countryCode == null) {
 260  2
             return Collections.emptyList();
 261  
         }
 262  6
         List<Locale> langs = cLanguagesByCountry.get(countryCode);
 263  6
         if (langs == null) {
 264  3
             langs = new ArrayList<Locale>();
 265  3
             final List<Locale> locales = availableLocaleList();
 266  471
             for (int i = 0; i < locales.size(); i++) {
 267  468
                 final Locale locale = locales.get(i);
 268  468
                 if (countryCode.equals(locale.getCountry()) &&
 269  
                         locale.getVariant().isEmpty()) {
 270  4
                     langs.add(locale);
 271  
                 }
 272  
             }
 273  3
             langs = Collections.unmodifiableList(langs);
 274  3
             cLanguagesByCountry.putIfAbsent(countryCode, langs);
 275  3
             langs = cLanguagesByCountry.get(countryCode);
 276  
         }
 277  6
         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  8
         if (languageCode == null) {
 292  2
             return Collections.emptyList();
 293  
         }
 294  6
         List<Locale> countries = cCountriesByLanguage.get(languageCode);
 295  6
         if (countries == null) {
 296  3
             countries = new ArrayList<Locale>();
 297  3
             final List<Locale> locales = availableLocaleList();
 298  471
             for (int i = 0; i < locales.size(); i++) {
 299  468
                 final Locale locale = locales.get(i);
 300  468
                 if (languageCode.equals(locale.getLanguage()) &&
 301  
                         locale.getCountry().length() != 0 &&
 302  
                         locale.getVariant().isEmpty()) {
 303  6
                     countries.add(locale);
 304  
                 }
 305  
             }
 306  3
             countries = Collections.unmodifiableList(countries);
 307  3
             cCountriesByLanguage.putIfAbsent(languageCode, countries);
 308  3
             countries = cCountriesByLanguage.get(languageCode);
 309  
         }
 310  6
         return countries;
 311  
     }
 312  
 
 313  
     //-----------------------------------------------------------------------
 314  
     // class to avoid synchronization (Init on demand)
 315  33
     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  1
             final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales()));  // extra safe
 323  1
             AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
 324  1
             AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
 325  1
         }
 326  
     }
 327  
 
 328  
 }