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 */ 017 package org.apache.commons.lang3; 018 019 import java.util.ArrayList; 020 import java.util.Arrays; 021 import java.util.Collections; 022 import java.util.HashSet; 023 import java.util.List; 024 import java.util.Locale; 025 import java.util.Set; 026 import java.util.concurrent.ConcurrentHashMap; 027 import 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 1090563 2011-04-09 11:00:10Z sebb $ 038 */ 039 public 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 */ 088 public static Locale toLocale(String str) { 089 if (str == null) { 090 return null; 091 } 092 int len = str.length(); 093 if (len != 2 && len != 5 && len < 7) { 094 throw new IllegalArgumentException("Invalid locale format: " + str); 095 } 096 char ch0 = str.charAt(0); 097 char ch1 = str.charAt(1); 098 if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { 099 throw new IllegalArgumentException("Invalid locale format: " + str); 100 } 101 if (len == 2) { 102 return new Locale(str, ""); 103 } else { 104 if (str.charAt(2) != '_') { 105 throw new IllegalArgumentException("Invalid locale format: " + str); 106 } 107 char ch3 = str.charAt(3); 108 if (ch3 == '_') { 109 return new Locale(str.substring(0, 2), "", str.substring(4)); 110 } 111 char ch4 = str.charAt(4); 112 if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { 113 throw new IllegalArgumentException("Invalid locale format: " + str); 114 } 115 if (len == 5) { 116 return new Locale(str.substring(0, 2), str.substring(3, 5)); 117 } else { 118 if (str.charAt(5) != '_') { 119 throw new IllegalArgumentException("Invalid locale format: " + str); 120 } 121 return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); 122 } 123 } 124 } 125 126 //----------------------------------------------------------------------- 127 /** 128 * <p>Obtains the list of locales to search through when performing 129 * a locale search.</p> 130 * 131 * <pre> 132 * localeLookupList(Locale("fr","CA","xxx")) 133 * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")] 134 * </pre> 135 * 136 * @param locale the locale to start from 137 * @return the unmodifiable list of Locale objects, 0 being locale, not null 138 */ 139 public static List<Locale> localeLookupList(Locale locale) { 140 return localeLookupList(locale, locale); 141 } 142 143 //----------------------------------------------------------------------- 144 /** 145 * <p>Obtains the list of locales to search through when performing 146 * a locale search.</p> 147 * 148 * <pre> 149 * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en")) 150 * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"] 151 * </pre> 152 * 153 * <p>The result list begins with the most specific locale, then the 154 * next more general and so on, finishing with the default locale. 155 * The list will never contain the same locale twice.</p> 156 * 157 * @param locale the locale to start from, null returns empty list 158 * @param defaultLocale the default locale to use if no other is found 159 * @return the unmodifiable list of Locale objects, 0 being locale, not null 160 */ 161 public static List<Locale> localeLookupList(Locale locale, Locale defaultLocale) { 162 List<Locale> list = new ArrayList<Locale>(4); 163 if (locale != null) { 164 list.add(locale); 165 if (locale.getVariant().length() > 0) { 166 list.add(new Locale(locale.getLanguage(), locale.getCountry())); 167 } 168 if (locale.getCountry().length() > 0) { 169 list.add(new Locale(locale.getLanguage(), "")); 170 } 171 if (list.contains(defaultLocale) == false) { 172 list.add(defaultLocale); 173 } 174 } 175 return Collections.unmodifiableList(list); 176 } 177 178 //----------------------------------------------------------------------- 179 /** 180 * <p>Obtains an unmodifiable list of installed locales.</p> 181 * 182 * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}. 183 * It is more efficient, as the JDK method must create a new array each 184 * time it is called.</p> 185 * 186 * @return the unmodifiable list of available locales 187 */ 188 public static List<Locale> availableLocaleList() { 189 return SyncAvoid.AVAILABLE_LOCALE_LIST; 190 } 191 192 //----------------------------------------------------------------------- 193 /** 194 * <p>Obtains an unmodifiable set of installed locales.</p> 195 * 196 * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}. 197 * It is more efficient, as the JDK method must create a new array each 198 * time it is called.</p> 199 * 200 * @return the unmodifiable set of available locales 201 */ 202 public static Set<Locale> availableLocaleSet() { 203 return SyncAvoid.AVAILABLE_LOCALE_SET; 204 } 205 206 //----------------------------------------------------------------------- 207 /** 208 * <p>Checks if the locale specified is in the list of available locales.</p> 209 * 210 * @param locale the Locale object to check if it is available 211 * @return true if the locale is a known locale 212 */ 213 public static boolean isAvailableLocale(Locale locale) { 214 return availableLocaleList().contains(locale); 215 } 216 217 //----------------------------------------------------------------------- 218 /** 219 * <p>Obtains the list of languages supported for a given country.</p> 220 * 221 * <p>This method takes a country code and searches to find the 222 * languages available for that country. Variant locales are removed.</p> 223 * 224 * @param countryCode the 2 letter country code, null returns empty 225 * @return an unmodifiable List of Locale objects, not null 226 */ 227 public static List<Locale> languagesByCountry(String countryCode) { 228 if (countryCode == null) { 229 return Collections.emptyList(); 230 } 231 List<Locale> langs = cLanguagesByCountry.get(countryCode); 232 if (langs == null) { 233 langs = new ArrayList<Locale>(); 234 List<Locale> locales = availableLocaleList(); 235 for (int i = 0; i < locales.size(); i++) { 236 Locale locale = locales.get(i); 237 if (countryCode.equals(locale.getCountry()) && 238 locale.getVariant().length() == 0) { 239 langs.add(locale); 240 } 241 } 242 langs = Collections.unmodifiableList(langs); 243 cLanguagesByCountry.putIfAbsent(countryCode, langs); 244 langs = cLanguagesByCountry.get(countryCode); 245 } 246 return langs; 247 } 248 249 //----------------------------------------------------------------------- 250 /** 251 * <p>Obtains the list of countries supported for a given language.</p> 252 * 253 * <p>This method takes a language code and searches to find the 254 * countries available for that language. Variant locales are removed.</p> 255 * 256 * @param languageCode the 2 letter language code, null returns empty 257 * @return an unmodifiable List of Locale objects, not null 258 */ 259 public static List<Locale> countriesByLanguage(String languageCode) { 260 if (languageCode == null) { 261 return Collections.emptyList(); 262 } 263 List<Locale> countries = cCountriesByLanguage.get(languageCode); 264 if (countries == null) { 265 countries = new ArrayList<Locale>(); 266 List<Locale> locales = availableLocaleList(); 267 for (int i = 0; i < locales.size(); i++) { 268 Locale locale = locales.get(i); 269 if (languageCode.equals(locale.getLanguage()) && 270 locale.getCountry().length() != 0 && 271 locale.getVariant().length() == 0) { 272 countries.add(locale); 273 } 274 } 275 countries = Collections.unmodifiableList(countries); 276 cCountriesByLanguage.putIfAbsent(languageCode, countries); 277 countries = cCountriesByLanguage.get(languageCode); 278 } 279 return countries; 280 } 281 282 //----------------------------------------------------------------------- 283 // class to avoid synchronization 284 static class SyncAvoid { 285 /** Unmodifiable list of available locales. */ 286 private static List<Locale> AVAILABLE_LOCALE_LIST; 287 /** Unmodifiable set of available locales. */ 288 private static Set<Locale> AVAILABLE_LOCALE_SET; 289 290 static { 291 List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales())); // extra safe 292 AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list); 293 AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(availableLocaleList())); 294 } 295 } 296 297 }