Locale.java revision e802cf54e3be8ef2fed0e84127a8398385ef8a11
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27/* 28 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved 29 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved 30 * 31 * The original version of this source code and documentation 32 * is copyrighted and owned by Taligent, Inc., a wholly-owned 33 * subsidiary of IBM. These materials are provided under terms 34 * of a License Agreement between Taligent and Sun. This technology 35 * is protected by multiple US and International patents. 36 * 37 * This notice and attribution to Taligent may not be removed. 38 * Taligent is a registered trademark of Taligent, Inc. 39 * 40 */ 41 42package java.util; 43 44import java.io.IOException; 45import java.io.ObjectInputStream; 46import java.io.ObjectOutputStream; 47import java.io.ObjectStreamField; 48import java.io.Serializable; 49import java.security.AccessController; 50import java.text.MessageFormat; 51import java.util.spi.LocaleNameProvider; 52import libcore.icu.ICU; 53 54import sun.security.action.GetPropertyAction; 55import sun.util.LocaleServiceProviderPool; 56import sun.util.locale.BaseLocale; 57import sun.util.locale.InternalLocaleBuilder; 58import sun.util.locale.LanguageTag; 59import sun.util.locale.LocaleExtensions; 60import sun.util.locale.LocaleObjectCache; 61import sun.util.locale.LocaleSyntaxException; 62import sun.util.locale.LocaleUtils; 63import sun.util.locale.ParseStatus; 64import sun.util.locale.UnicodeLocaleExtension; 65 66/** 67 * A <code>Locale</code> object represents a specific geographical, political, 68 * or cultural region. An operation that requires a <code>Locale</code> to perform 69 * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code> 70 * to tailor information for the user. For example, displaying a number 71 * is a locale-sensitive operation— the number should be formatted 72 * according to the customs and conventions of the user's native country, 73 * region, or culture. 74 * 75 * <p> The <code>Locale</code> class implements identifiers 76 * interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying 77 * Languages"), with support for the LDML (UTS#35, "Unicode Locale 78 * Data Markup Language") BCP 47-compatible extensions for locale data 79 * exchange. 80 * 81 * <p> A <code>Locale</code> object logically consists of the fields 82 * described below. 83 * 84 * <dl> 85 * <dt><a name="def_language"/><b>language</b></dt> 86 * 87 * <dd>ISO 639 alpha-2 or alpha-3 language code, or registered 88 * language subtags up to 8 alpha letters (for future enhancements). 89 * When a language has both an alpha-2 code and an alpha-3 code, the 90 * alpha-2 code must be used. You can find a full list of valid 91 * language codes in the IANA Language Subtag Registry (search for 92 * "Type: language"). The language field is case insensitive, but 93 * <code>Locale</code> always canonicalizes to lower case.</dd><br> 94 * 95 * <dd>Well-formed language values have the form 96 * <code>[a-zA-Z]{2,8}</code>. Note that this is not the the full 97 * BCP47 language production, since it excludes extlang. They are 98 * not needed since modern three-letter language codes replace 99 * them.</dd><br> 100 * 101 * <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br> 102 * 103 * <dt><a name="def_script"/><b>script</b></dt> 104 * 105 * <dd>ISO 15924 alpha-4 script code. You can find a full list of 106 * valid script codes in the IANA Language Subtag Registry (search 107 * for "Type: script"). The script field is case insensitive, but 108 * <code>Locale</code> always canonicalizes to title case (the first 109 * letter is upper case and the rest of the letters are lower 110 * case).</dd><br> 111 * 112 * <dd>Well-formed script values have the form 113 * <code>[a-zA-Z]{4}</code></dd><br> 114 * 115 * <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br> 116 * 117 * <dt><a name="def_region"/><b>country (region)</b></dt> 118 * 119 * <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. 120 * You can find a full list of valid country and region codes in the 121 * IANA Language Subtag Registry (search for "Type: region"). The 122 * country (region) field is case insensitive, but 123 * <code>Locale</code> always canonicalizes to upper case.</dd><br> 124 * 125 * <dd>Well-formed country/region values have 126 * the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br> 127 * 128 * <dd>Example: "US" (United States), "FR" (France), "029" 129 * (Caribbean)</dd><br> 130 * 131 * <dt><a name="def_variant"/><b>variant</b></dt> 132 * 133 * <dd>Any arbitrary value used to indicate a variation of a 134 * <code>Locale</code>. Where there are two or more variant values 135 * each indicating its own semantics, these values should be ordered 136 * by importance, with most important first, separated by 137 * underscore('_'). The variant field is case sensitive.</dd><br> 138 * 139 * <dd>Note: IETF BCP 47 places syntactic restrictions on variant 140 * subtags. Also BCP 47 subtags are strictly used to indicate 141 * additional variations that define a language or its dialects that 142 * are not covered by any combinations of language, script and 143 * region subtags. You can find a full list of valid variant codes 144 * in the IANA Language Subtag Registry (search for "Type: variant"). 145 * 146 * <p>However, the variant field in <code>Locale</code> has 147 * historically been used for any kind of variation, not just 148 * language variations. For example, some supported variants 149 * available in Java SE Runtime Environments indicate alternative 150 * cultural behaviors such as calendar type or number script. In 151 * BCP 47 this kind of information, which does not identify the 152 * language, is supported by extension subtags or private use 153 * subtags.</dd><br> 154 * 155 * <dd>Well-formed variant values have the form <code>SUBTAG 156 * (('_'|'-') SUBTAG)*</code> where <code>SUBTAG = 157 * [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only 158 * uses hyphen ('-') as a delimiter, this is more lenient).</dd><br> 159 * 160 * <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br> 161 * 162 * <dt><a name="def_extensions"/><b>extensions</b></dt> 163 * 164 * <dd>A map from single character keys to string values, indicating 165 * extensions apart from language identification. The extensions in 166 * <code>Locale</code> implement the semantics and syntax of BCP 47 167 * extension subtags and private use subtags. The extensions are 168 * case insensitive, but <code>Locale</code> canonicalizes all 169 * extension keys and values to lower case. Note that extensions 170 * cannot have empty values.</dd><br> 171 * 172 * <dd>Well-formed keys are single characters from the set 173 * <code>[0-9a-zA-Z]</code>. Well-formed values have the form 174 * <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x' 175 * <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys 176 * <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows 177 * single-character subtags).</dd><br> 178 * 179 * <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar), 180 * key="x"/value="java-1-7"</dd> 181 * </dl> 182 * 183 * <b>Note:</b> Although BCP 47 requires field values to be registered 184 * in the IANA Language Subtag Registry, the <code>Locale</code> class 185 * does not provide any validation features. The <code>Builder</code> 186 * only checks if an individual field satisfies the syntactic 187 * requirement (is well-formed), but does not validate the value 188 * itself. See {@link Builder} for details. 189 * 190 * <h4><a name="def_locale_extension">Unicode locale/language extension</h4> 191 * 192 * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional 193 * attributes and keywords to override or refine the default behavior 194 * associated with a locale. A keyword is represented by a pair of 195 * key and type. For example, "nu-thai" indicates that Thai local 196 * digits (value:"thai") should be used for formatting numbers 197 * (key:"nu"). 198 * 199 * <p>The keywords are mapped to a BCP 47 extension value using the 200 * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}). The above 201 * example, "nu-thai", becomes the extension "u-nu-thai".code 202 * 203 * <p>Thus, when a <code>Locale</code> object contains Unicode locale 204 * attributes and keywords, 205 * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a 206 * String representing this information, for example, "nu-thai". The 207 * <code>Locale</code> class also provides {@link 208 * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and 209 * {@link #getUnicodeLocaleType} which allow you to access Unicode 210 * locale attributes and key/type pairs directly. When represented as 211 * a string, the Unicode Locale Extension lists attributes 212 * alphabetically, followed by key/type sequences with keys listed 213 * alphabetically (the order of subtags comprising a key's type is 214 * fixed when the type is defined) 215 * 216 * <p>A well-formed locale key has the form 217 * <code>[0-9a-zA-Z]{2}</code>. A well-formed locale type has the 218 * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it 219 * can be empty, or a series of subtags 3-8 alphanums in length). A 220 * well-formed locale attribute has the form 221 * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same 222 * form as a locale type subtag). 223 * 224 * <p>The Unicode locale extension specifies optional behavior in 225 * locale-sensitive services. Although the LDML specification defines 226 * various keys and values, actual locale-sensitive service 227 * implementations in a Java Runtime Environment might not support any 228 * particular Unicode locale attributes or key/type pairs. 229 * 230 * <h4>Creating a Locale</h4> 231 * 232 * <p>There are several different ways to create a <code>Locale</code> 233 * object. 234 * 235 * <h5>Builder</h5> 236 * 237 * <p>Using {@link Builder} you can construct a <code>Locale</code> object 238 * that conforms to BCP 47 syntax. 239 * 240 * <h5>Constructors</h5> 241 * 242 * <p>The <code>Locale</code> class provides three constructors: 243 * <blockquote> 244 * <pre> 245 * {@link #Locale(String language)} 246 * {@link #Locale(String language, String country)} 247 * {@link #Locale(String language, String country, String variant)} 248 * </pre> 249 * </blockquote> 250 * These constructors allow you to create a <code>Locale</code> object 251 * with language, country and variant, but you cannot specify 252 * script or extensions. 253 * 254 * <h5>Factory Methods</h5> 255 * 256 * <p>The method {@link #forLanguageTag} creates a <code>Locale</code> 257 * object for a well-formed BCP 47 language tag. 258 * 259 * <h5>Locale Constants</h5> 260 * 261 * <p>The <code>Locale</code> class provides a number of convenient constants 262 * that you can use to create <code>Locale</code> objects for commonly used 263 * locales. For example, the following creates a <code>Locale</code> object 264 * for the United States: 265 * <blockquote> 266 * <pre> 267 * Locale.US 268 * </pre> 269 * </blockquote> 270 * 271 * <h4>Use of Locale</h4> 272 * 273 * <p>Once you've created a <code>Locale</code> you can query it for information 274 * about itself. Use <code>getCountry</code> to get the country (or region) 275 * code and <code>getLanguage</code> to get the language code. 276 * You can use <code>getDisplayCountry</code> to get the 277 * name of the country suitable for displaying to the user. Similarly, 278 * you can use <code>getDisplayLanguage</code> to get the name of 279 * the language suitable for displaying to the user. Interestingly, 280 * the <code>getDisplayXXX</code> methods are themselves locale-sensitive 281 * and have two versions: one that uses the default locale and one 282 * that uses the locale specified as an argument. 283 * 284 * <p>The Java Platform provides a number of classes that perform locale-sensitive 285 * operations. For example, the <code>NumberFormat</code> class formats 286 * numbers, currency, and percentages in a locale-sensitive manner. Classes 287 * such as <code>NumberFormat</code> have several convenience methods 288 * for creating a default object of that type. For example, the 289 * <code>NumberFormat</code> class provides these three convenience methods 290 * for creating a default <code>NumberFormat</code> object: 291 * <blockquote> 292 * <pre> 293 * NumberFormat.getInstance() 294 * NumberFormat.getCurrencyInstance() 295 * NumberFormat.getPercentInstance() 296 * </pre> 297 * </blockquote> 298 * Each of these methods has two variants; one with an explicit locale 299 * and one without; the latter uses the default locale: 300 * <blockquote> 301 * <pre> 302 * NumberFormat.getInstance(myLocale) 303 * NumberFormat.getCurrencyInstance(myLocale) 304 * NumberFormat.getPercentInstance(myLocale) 305 * </pre> 306 * </blockquote> 307 * A <code>Locale</code> is the mechanism for identifying the kind of object 308 * (<code>NumberFormat</code>) that you would like to get. The locale is 309 * <STRONG>just</STRONG> a mechanism for identifying objects, 310 * <STRONG>not</STRONG> a container for the objects themselves. 311 * 312 * <h4>Compatibility</h4> 313 * 314 * <p>In order to maintain compatibility with existing usage, Locale's 315 * constructors retain their behavior prior to the Java Runtime 316 * Environment version 1.7. The same is largely true for the 317 * <code>toString</code> method. Thus Locale objects can continue to 318 * be used as they were. In particular, clients who parse the output 319 * of toString into language, country, and variant fields can continue 320 * to do so (although this is strongly discouraged), although the 321 * variant field will have additional information in it if script or 322 * extensions are present. 323 * 324 * <p>In addition, BCP 47 imposes syntax restrictions that are not 325 * imposed by Locale's constructors. This means that conversions 326 * between some Locales and BCP 47 language tags cannot be made without 327 * losing information. Thus <code>toLanguageTag</code> cannot 328 * represent the state of locales whose language, country, or variant 329 * do not conform to BCP 47. 330 * 331 * <p>Because of these issues, it is recommended that clients migrate 332 * away from constructing non-conforming locales and use the 333 * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead. 334 * Clients desiring a string representation of the complete locale can 335 * then always rely on <code>toLanguageTag</code> for this purpose. 336 * 337 * <h5><a name="special_cases_constructor"/>Special cases</h5> 338 * 339 * <p>For compatibility reasons, two 340 * non-conforming locales are treated as special cases. These are 341 * <b><tt>ja_JP_JP</tt></b> and <b><tt>th_TH_TH</tt></b>. These are ill-formed 342 * in BCP 47 since the variants are too short. To ease migration to BCP 47, 343 * these are treated specially during construction. These two cases (and only 344 * these) cause a constructor to generate an extension, all other values behave 345 * exactly as they did prior to Java 7. 346 * 347 * <p>Java has used <tt>ja_JP_JP</tt> to represent Japanese as used in 348 * Japan together with the Japanese Imperial calendar. This is now 349 * representable using a Unicode locale extension, by specifying the 350 * Unicode locale key <tt>ca</tt> (for "calendar") and type 351 * <tt>japanese</tt>. When the Locale constructor is called with the 352 * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is 353 * automatically added. 354 * 355 * <p>Java has used <tt>th_TH_TH</tt> to represent Thai as used in 356 * Thailand together with Thai digits. This is also now representable using 357 * a Unicode locale extension, by specifying the Unicode locale key 358 * <tt>nu</tt> (for "number") and value <tt>thai</tt>. When the Locale 359 * constructor is called with the arguments "th", "TH", "TH", the 360 * extension "u-nu-thai" is automatically added. 361 * 362 * <h5>Serialization</h5> 363 * 364 * <p>During serialization, writeObject writes all fields to the output 365 * stream, including extensions. 366 * 367 * <p>During deserialization, readResolve adds extensions as described 368 * in <a href="#special_cases_constructor">Special Cases</a>, only 369 * for the two cases th_TH_TH and ja_JP_JP. 370 * 371 * <h5>Legacy language codes</h5> 372 * 373 * <p>Locale's constructor has always converted three language codes to 374 * their earlier, obsoleted forms: <tt>he</tt> maps to <tt>iw</tt>, 375 * <tt>yi</tt> maps to <tt>ji</tt>, and <tt>id</tt> maps to 376 * <tt>in</tt>. This continues to be the case, in order to not break 377 * backwards compatibility. 378 * 379 * <p>The APIs added in 1.7 map between the old and new language codes, 380 * maintaining the old codes internal to Locale (so that 381 * <code>getLanguage</code> and <code>toString</code> reflect the old 382 * code), but using the new codes in the BCP 47 language tag APIs (so 383 * that <code>toLanguageTag</code> reflects the new one). This 384 * preserves the equivalence between Locales no matter which code or 385 * API is used to construct them. Java's default resource bundle 386 * lookup mechanism also implements this mapping, so that resources 387 * can be named using either convention, see {@link ResourceBundle.Control}. 388 * 389 * <h5>Three-letter language/country(region) codes</h5> 390 * 391 * <p>The Locale constructors have always specified that the language 392 * and the country param be two characters in length, although in 393 * practice they have accepted any length. The specification has now 394 * been relaxed to allow language codes of two to eight characters and 395 * country (region) codes of two to three characters, and in 396 * particular, three-letter language codes and three-digit region 397 * codes as specified in the IANA Language Subtag Registry. For 398 * compatibility, the implementation still does not impose a length 399 * constraint. 400 * 401 * @see Builder 402 * @see ResourceBundle 403 * @see java.text.Format 404 * @see java.text.NumberFormat 405 * @see java.text.Collator 406 * @author Mark Davis 407 * @since 1.1 408 */ 409public final class Locale implements Cloneable, Serializable { 410 411 static private final Cache LOCALECACHE = new Cache(); 412 413 /** Useful constant for language. 414 */ 415 static public final Locale ENGLISH = createConstant("en", ""); 416 417 /** Useful constant for language. 418 */ 419 static public final Locale FRENCH = createConstant("fr", ""); 420 421 /** Useful constant for language. 422 */ 423 static public final Locale GERMAN = createConstant("de", ""); 424 425 /** Useful constant for language. 426 */ 427 static public final Locale ITALIAN = createConstant("it", ""); 428 429 /** Useful constant for language. 430 */ 431 static public final Locale JAPANESE = createConstant("ja", ""); 432 433 /** Useful constant for language. 434 */ 435 static public final Locale KOREAN = createConstant("ko", ""); 436 437 /** Useful constant for language. 438 */ 439 static public final Locale CHINESE = createConstant("zh", ""); 440 441 /** Useful constant for language. 442 */ 443 static public final Locale SIMPLIFIED_CHINESE = createConstant("zh", "CN"); 444 445 /** Useful constant for language. 446 */ 447 static public final Locale TRADITIONAL_CHINESE = createConstant("zh", "TW"); 448 449 /** Useful constant for country. 450 */ 451 static public final Locale FRANCE = createConstant("fr", "FR"); 452 453 /** Useful constant for country. 454 */ 455 static public final Locale GERMANY = createConstant("de", "DE"); 456 457 /** Useful constant for country. 458 */ 459 static public final Locale ITALY = createConstant("it", "IT"); 460 461 /** Useful constant for country. 462 */ 463 static public final Locale JAPAN = createConstant("ja", "JP"); 464 465 /** Useful constant for country. 466 */ 467 static public final Locale KOREA = createConstant("ko", "KR"); 468 469 /** Useful constant for country. 470 */ 471 static public final Locale CHINA = SIMPLIFIED_CHINESE; 472 473 /** Useful constant for country. 474 */ 475 static public final Locale PRC = SIMPLIFIED_CHINESE; 476 477 /** Useful constant for country. 478 */ 479 static public final Locale TAIWAN = TRADITIONAL_CHINESE; 480 481 /** Useful constant for country. 482 */ 483 static public final Locale UK = createConstant("en", "GB"); 484 485 /** Useful constant for country. 486 */ 487 static public final Locale US = createConstant("en", "US"); 488 489 /** Useful constant for country. 490 */ 491 static public final Locale CANADA = createConstant("en", "CA"); 492 493 /** Useful constant for country. 494 */ 495 static public final Locale CANADA_FRENCH = createConstant("fr", "CA"); 496 497 /** 498 * ISO 639-3 generic code for undetermined languages. 499 */ 500 private static final String UNDETERMINED_LANGUAGE = "und"; 501 502 /** 503 * Useful constant for the root locale. The root locale is the locale whose 504 * language, country, and variant are empty ("") strings. This is regarded 505 * as the base locale of all locales, and is used as the language/country 506 * neutral locale for the locale sensitive operations. 507 * 508 * @since 1.6 509 */ 510 static public final Locale ROOT = createConstant("", ""); 511 512 /** 513 * The key for the private use extension ('x'). 514 * 515 * @see #getExtension(char) 516 * @see Builder#setExtension(char, String) 517 * @since 1.7 518 */ 519 static public final char PRIVATE_USE_EXTENSION = 'x'; 520 521 /** 522 * The key for Unicode locale extension ('u'). 523 * 524 * @see #getExtension(char) 525 * @see Builder#setExtension(char, String) 526 * @since 1.7 527 */ 528 static public final char UNICODE_LOCALE_EXTENSION = 'u'; 529 530 /** serialization ID 531 */ 532 static final long serialVersionUID = 9149081749638150636L; 533 534 /** 535 * Display types for retrieving localized names from the name providers. 536 */ 537 private static final int DISPLAY_LANGUAGE = 0; 538 private static final int DISPLAY_COUNTRY = 1; 539 private static final int DISPLAY_VARIANT = 2; 540 private static final int DISPLAY_SCRIPT = 3; 541 542 /** 543 * Private constructor used by getInstance method 544 */ 545 private Locale(BaseLocale baseLocale, LocaleExtensions extensions) { 546 this.baseLocale = baseLocale; 547 this.localeExtensions = extensions; 548 } 549 550 /** 551 * Construct a locale from language, country and variant. 552 * This constructor normalizes the language value to lowercase and 553 * the country value to uppercase. 554 * <p> 555 * <b>Note:</b> 556 * <ul> 557 * <li>ISO 639 is not a stable standard; some of the language codes it defines 558 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 559 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 560 * API on Locale will return only the OLD codes. 561 * <li>For backward compatibility reasons, this constructor does not make 562 * any syntactic checks on the input. 563 * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially, 564 * see <a href="#special_cases_constructor">Special Cases</a> for more information. 565 * </ul> 566 * 567 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 568 * up to 8 characters in length. See the <code>Locale</code> class description about 569 * valid language values. 570 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 571 * See the <code>Locale</code> class description about valid country values. 572 * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>. 573 * See the <code>Locale</code> class description for the details. 574 * @exception NullPointerException thrown if any argument is null. 575 */ 576 public Locale(String language, String country, String variant) { 577 if (language== null || country == null || variant == null) { 578 throw new NullPointerException(); 579 } 580 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant); 581 localeExtensions = getCompatibilityExtensions(language, "", country, variant); 582 } 583 584 /** 585 * Construct a locale from language and country. 586 * This constructor normalizes the language value to lowercase and 587 * the country value to uppercase. 588 * <p> 589 * <b>Note:</b> 590 * <ul> 591 * <li>ISO 639 is not a stable standard; some of the language codes it defines 592 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 593 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 594 * API on Locale will return only the OLD codes. 595 * <li>For backward compatibility reasons, this constructor does not make 596 * any syntactic checks on the input. 597 * </ul> 598 * 599 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 600 * up to 8 characters in length. See the <code>Locale</code> class description about 601 * valid language values. 602 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 603 * See the <code>Locale</code> class description about valid country values. 604 * @exception NullPointerException thrown if either argument is null. 605 */ 606 public Locale(String language, String country) { 607 this(language, country, ""); 608 } 609 610 /** 611 * Construct a locale from a language code. 612 * This constructor normalizes the language value to lowercase. 613 * <p> 614 * <b>Note:</b> 615 * <ul> 616 * <li>ISO 639 is not a stable standard; some of the language codes it defines 617 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 618 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 619 * API on Locale will return only the OLD codes. 620 * <li>For backward compatibility reasons, this constructor does not make 621 * any syntactic checks on the input. 622 * </ul> 623 * 624 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 625 * up to 8 characters in length. See the <code>Locale</code> class description about 626 * valid language values. 627 * @exception NullPointerException thrown if argument is null. 628 * @since 1.4 629 */ 630 public Locale(String language) { 631 this(language, "", ""); 632 } 633 634 /** 635 * This method must be called only for creating the Locale.* 636 * constants due to making shortcuts. 637 */ 638 private static Locale createConstant(String lang, String country) { 639 BaseLocale base = BaseLocale.createInstance(lang, country); 640 return getInstance(base, null); 641 } 642 643 /** 644 * Returns a <code>Locale</code> constructed from the given 645 * <code>language</code>, <code>country</code> and 646 * <code>variant</code>. If the same <code>Locale</code> instance 647 * is available in the cache, then that instance is 648 * returned. Otherwise, a new <code>Locale</code> instance is 649 * created and cached. 650 * 651 * @param language lowercase 2 to 8 language code. 652 * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code. 653 * @param variant vendor and browser specific code. See class description. 654 * @return the <code>Locale</code> instance requested 655 * @exception NullPointerException if any argument is null. 656 */ 657 static Locale getInstance(String language, String country, String variant) { 658 return getInstance(language, "", country, variant, null); 659 } 660 661 static Locale getInstance(String language, String script, String country, 662 String variant, LocaleExtensions extensions) { 663 if (language== null || script == null || country == null || variant == null) { 664 throw new NullPointerException(); 665 } 666 667 if (extensions == null) { 668 extensions = getCompatibilityExtensions(language, script, country, variant); 669 } 670 671 BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant); 672 return getInstance(baseloc, extensions); 673 } 674 675 static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) { 676 LocaleKey key = new LocaleKey(baseloc, extensions); 677 return LOCALECACHE.get(key); 678 } 679 680 private static class Cache extends LocaleObjectCache<LocaleKey, Locale> { 681 private Cache() { 682 } 683 684 @Override 685 protected Locale createObject(LocaleKey key) { 686 return new Locale(key.base, key.exts); 687 } 688 } 689 690 private static final class LocaleKey { 691 private final BaseLocale base; 692 private final LocaleExtensions exts; 693 private final int hash; 694 695 private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) { 696 base = baseLocale; 697 exts = extensions; 698 699 // Calculate the hash value here because it's always used. 700 int h = base.hashCode(); 701 if (exts != null) { 702 h ^= exts.hashCode(); 703 } 704 hash = h; 705 } 706 707 @Override 708 public boolean equals(Object obj) { 709 if (this == obj) { 710 return true; 711 } 712 if (!(obj instanceof LocaleKey)) { 713 return false; 714 } 715 LocaleKey other = (LocaleKey)obj; 716 if (hash != other.hash || !base.equals(other.base)) { 717 return false; 718 } 719 if (exts == null) { 720 return other.exts == null; 721 } 722 return exts.equals(other.exts); 723 } 724 725 @Override 726 public int hashCode() { 727 return hash; 728 } 729 } 730 731 /** 732 * Gets the current value of the default locale for this instance 733 * of the Java Virtual Machine. 734 * <p> 735 * The Java Virtual Machine sets the default locale during startup 736 * based on the host environment. It is used by many locale-sensitive 737 * methods if no locale is explicitly specified. 738 * It can be changed using the 739 * {@link #setDefault(java.util.Locale) setDefault} method. 740 * 741 * @return the default locale for this instance of the Java Virtual Machine 742 */ 743 public static Locale getDefault() { 744 // do not synchronize this method - see 4071298 745 // it's OK if more than one default locale happens to be created 746 if (defaultLocale == null) { 747 Locale locale = initDefault(); 748 } 749 return defaultLocale; 750 } 751 752 /** 753 * Gets the current value of the default locale for the specified Category 754 * for this instance of the Java Virtual Machine. 755 * <p> 756 * The Java Virtual Machine sets the default locale during startup based 757 * on the host environment. It is used by many locale-sensitive methods 758 * if no locale is explicitly specified. It can be changed using the 759 * setDefault(Locale.Category, Locale) method. 760 * 761 * @param category - the specified category to get the default locale 762 * @throws NullPointerException - if category is null 763 * @return the default locale for the specified Category for this instance 764 * of the Java Virtual Machine 765 * @see #setDefault(Locale.Category, Locale) 766 * @since 1.7 767 */ 768 public static Locale getDefault(Locale.Category category) { 769 // do not synchronize this method - see 4071298 770 // it's OK if more than one default locale happens to be created 771 switch (category) { 772 case DISPLAY: 773 if (defaultDisplayLocale == null) { 774 defaultDisplayLocale = initDefault(category); 775 } 776 return defaultDisplayLocale; 777 case FORMAT: 778 if (defaultFormatLocale == null) { 779 defaultFormatLocale = initDefault(category); 780 } 781 return defaultFormatLocale; 782 default: 783 assert false: "Unknown Category"; 784 } 785 return getDefault(); 786 } 787 788 /** 789 * @hide visible for testing. 790 */ 791 public static Locale initDefault() { 792 String language, region, script, country, variant; 793 language = System.getProperty("user.language", "en"); 794 // for compatibility, check for old user.region property 795 region = System.getProperty("user.region"); 796 if (region != null) { 797 // region can be of form country, country_variant, or _variant 798 int i = region.indexOf('_'); 799 if (i >= 0) { 800 country = region.substring(0, i); 801 variant = region.substring(i + 1); 802 } else { 803 country = region; 804 variant = ""; 805 } 806 script = ""; 807 } else { 808 script = System.getProperty("user.script", ""); 809 country = System.getProperty("user.country", ""); 810 variant = System.getProperty("user.variant", ""); 811 } 812 return getInstance(language, script, country, variant, null); 813 } 814 815 private static Locale initDefault(Locale.Category category) { 816 // make sure defaultLocale is initialized 817 final Locale defaultLocale = getDefault(); 818 819 return getInstance( 820 System.getProperty(category.languageKey, defaultLocale.getLanguage()), 821 System.getProperty(category.scriptKey, defaultLocale.getScript()), 822 System.getProperty(category.countryKey, defaultLocale.getCountry()), 823 System.getProperty(category.variantKey, defaultLocale.getVariant()), 824 null); 825 } 826 827 /** 828 * Sets the default locale for this instance of the Java Virtual Machine. 829 * This does not affect the host locale. 830 * <p> 831 * If there is a security manager, its <code>checkPermission</code> 832 * method is called with a <code>PropertyPermission("user.language", "write")</code> 833 * permission before the default locale is changed. 834 * <p> 835 * The Java Virtual Machine sets the default locale during startup 836 * based on the host environment. It is used by many locale-sensitive 837 * methods if no locale is explicitly specified. 838 * <p> 839 * Since changing the default locale may affect many different areas 840 * of functionality, this method should only be used if the caller 841 * is prepared to reinitialize locale-sensitive code running 842 * within the same Java Virtual Machine. 843 * <p> 844 * By setting the default locale with this method, all of the default 845 * locales for each Category are also set to the specified default locale. 846 * 847 * @throws SecurityException 848 * if a security manager exists and its 849 * <code>checkPermission</code> method doesn't allow the operation. 850 * @throws NullPointerException if <code>newLocale</code> is null 851 * @param newLocale the new default locale 852 * @see SecurityManager#checkPermission 853 * @see java.util.PropertyPermission 854 */ 855 public static synchronized void setDefault(Locale newLocale) { 856 setDefault(Category.DISPLAY, newLocale); 857 setDefault(Category.FORMAT, newLocale); 858 defaultLocale = newLocale; 859 ICU.setDefaultLocale(newLocale.toLanguageTag()); 860 } 861 862 /** 863 * Sets the default locale for the specified Category for this instance 864 * of the Java Virtual Machine. This does not affect the host locale. 865 * <p> 866 * If there is a security manager, its checkPermission method is called 867 * with a PropertyPermission("user.language", "write") permission before 868 * the default locale is changed. 869 * <p> 870 * The Java Virtual Machine sets the default locale during startup based 871 * on the host environment. It is used by many locale-sensitive methods 872 * if no locale is explicitly specified. 873 * <p> 874 * Since changing the default locale may affect many different areas of 875 * functionality, this method should only be used if the caller is 876 * prepared to reinitialize locale-sensitive code running within the 877 * same Java Virtual Machine. 878 * <p> 879 * 880 * @param category - the specified category to set the default locale 881 * @param newLocale - the new default locale 882 * @throws SecurityException - if a security manager exists and its 883 * checkPermission method doesn't allow the operation. 884 * @throws NullPointerException - if category and/or newLocale is null 885 * @see SecurityManager#checkPermission(java.security.Permission) 886 * @see PropertyPermission 887 * @see #getDefault(Locale.Category) 888 * @since 1.7 889 */ 890 public static synchronized void setDefault(Locale.Category category, 891 Locale newLocale) { 892 if (category == null) 893 throw new NullPointerException("Category cannot be NULL"); 894 if (newLocale == null) 895 throw new NullPointerException("Can't set default locale to NULL"); 896 897 SecurityManager sm = System.getSecurityManager(); 898 if (sm != null) sm.checkPermission(new PropertyPermission 899 ("user.language", "write")); 900 switch (category) { 901 case DISPLAY: 902 defaultDisplayLocale = newLocale; 903 break; 904 case FORMAT: 905 defaultFormatLocale = newLocale; 906 break; 907 default: 908 assert false: "Unknown Category"; 909 } 910 } 911 912 /** 913 * Returns an array of all installed locales. 914 * The returned array represents the union of locales supported 915 * by the Java runtime environment and by installed 916 * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider} 917 * implementations. It must contain at least a <code>Locale</code> 918 * instance equal to {@link java.util.Locale#US Locale.US}. 919 * 920 * @return An array of installed locales. 921 */ 922 public static Locale[] getAvailableLocales() { 923 return LocaleServiceProviderPool.getAllAvailableLocales(); 924 } 925 926 /** 927 * Returns a list of all 2-letter country codes defined in ISO 3166. 928 * Can be used to create Locales. 929 * <p> 930 * <b>Note:</b> The <code>Locale</code> class also supports other codes for 931 * country (region), such as 3-letter numeric UN M.49 area codes. 932 * Therefore, the list returned by this method does not contain ALL valid 933 * codes that can be used to create Locales. 934 */ 935 public static String[] getISOCountries() { 936 // Android-changed: Use ICU. 937 return ICU.getISOCountries(); 938 } 939 940 /** 941 * Returns a list of all 2-letter language codes defined in ISO 639. 942 * Can be used to create Locales. 943 * <p> 944 * <b>Note:</b> 945 * <ul> 946 * <li>ISO 639 is not a stable standard— some languages' codes have changed. 947 * The list this function returns includes both the new and the old codes for the 948 * languages whose codes have changed. 949 * <li>The <code>Locale</code> class also supports language codes up to 950 * 8 characters in length. Therefore, the list returned by this method does 951 * not contain ALL valid codes that can be used to create Locales. 952 * </ul> 953 */ 954 public static String[] getISOLanguages() { 955 // Android-changed: Use ICU. 956 return ICU.getISOLanguages(); 957 } 958 959 /** 960 * Returns the language code of this Locale. 961 * 962 * <p><b>Note:</b> ISO 639 is not a stable standard— some languages' codes have changed. 963 * Locale's constructor recognizes both the new and the old codes for the languages 964 * whose codes have changed, but this function always returns the old code. If you 965 * want to check for a specific language whose code has changed, don't do 966 * <pre> 967 * if (locale.getLanguage().equals("he")) // BAD! 968 * ... 969 * </pre> 970 * Instead, do 971 * <pre> 972 * if (locale.getLanguage().equals(new Locale("he").getLanguage())) 973 * ... 974 * </pre> 975 * @return The language code, or the empty string if none is defined. 976 * @see #getDisplayLanguage 977 */ 978 public String getLanguage() { 979 return baseLocale.getLanguage(); 980 } 981 982 /** 983 * Returns the script for this locale, which should 984 * either be the empty string or an ISO 15924 4-letter script 985 * code. The first letter is uppercase and the rest are 986 * lowercase, for example, 'Latn', 'Cyrl'. 987 * 988 * @return The script code, or the empty string if none is defined. 989 * @see #getDisplayScript 990 * @since 1.7 991 */ 992 public String getScript() { 993 return baseLocale.getScript(); 994 } 995 996 /** 997 * Returns the country/region code for this locale, which should 998 * either be the empty string, an uppercase ISO 3166 2-letter code, 999 * or a UN M.49 3-digit code. 1000 * 1001 * @return The country/region code, or the empty string if none is defined. 1002 * @see #getDisplayCountry 1003 */ 1004 public String getCountry() { 1005 return baseLocale.getRegion(); 1006 } 1007 1008 /** 1009 * Returns the variant code for this locale. 1010 * 1011 * @return The variant code, or the empty string if none is defined. 1012 * @see #getDisplayVariant 1013 */ 1014 public String getVariant() { 1015 return baseLocale.getVariant(); 1016 } 1017 1018 /** 1019 * Returns the extension (or private use) value associated with 1020 * the specified key, or null if there is no extension 1021 * associated with the key. To be well-formed, the key must be one 1022 * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so 1023 * for example 'z' and 'Z' represent the same extension. 1024 * 1025 * @param key the extension key 1026 * @return The extension, or null if this locale defines no 1027 * extension for the specified key. 1028 * @throws IllegalArgumentException if key is not well-formed 1029 * @see #PRIVATE_USE_EXTENSION 1030 * @see #UNICODE_LOCALE_EXTENSION 1031 * @since 1.7 1032 */ 1033 public String getExtension(char key) { 1034 if (!LocaleExtensions.isValidKey(key)) { 1035 throw new IllegalArgumentException("Ill-formed extension key: " + key); 1036 } 1037 return (localeExtensions == null) ? null : localeExtensions.getExtensionValue(key); 1038 } 1039 1040 /** 1041 * Returns the set of extension keys associated with this locale, or the 1042 * empty set if it has no extensions. The returned set is unmodifiable. 1043 * The keys will all be lower-case. 1044 * 1045 * @return The set of extension keys, or the empty set if this locale has 1046 * no extensions. 1047 * @since 1.7 1048 */ 1049 public Set<Character> getExtensionKeys() { 1050 if (localeExtensions == null) { 1051 return Collections.emptySet(); 1052 } 1053 return localeExtensions.getKeys(); 1054 } 1055 1056 /** 1057 * Returns the set of unicode locale attributes associated with 1058 * this locale, or the empty set if it has no attributes. The 1059 * returned set is unmodifiable. 1060 * 1061 * @return The set of attributes. 1062 * @since 1.7 1063 */ 1064 public Set<String> getUnicodeLocaleAttributes() { 1065 if (localeExtensions == null) { 1066 return Collections.emptySet(); 1067 } 1068 return localeExtensions.getUnicodeLocaleAttributes(); 1069 } 1070 1071 /** 1072 * Returns the Unicode locale type associated with the specified Unicode locale key 1073 * for this locale. Returns the empty string for keys that are defined with no type. 1074 * Returns null if the key is not defined. Keys are case-insensitive. The key must 1075 * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is 1076 * thrown. 1077 * 1078 * @param key the Unicode locale key 1079 * @return The Unicode locale type associated with the key, or null if the 1080 * locale does not define the key. 1081 * @throws IllegalArgumentException if the key is not well-formed 1082 * @throws NullPointerException if <code>key</code> is null 1083 * @since 1.7 1084 */ 1085 public String getUnicodeLocaleType(String key) { 1086 if (!UnicodeLocaleExtension.isKey(key)) { 1087 throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key); 1088 } 1089 return (localeExtensions == null) ? null : localeExtensions.getUnicodeLocaleType(key); 1090 } 1091 1092 /** 1093 * Returns the set of Unicode locale keys defined by this locale, or the empty set if 1094 * this locale has none. The returned set is immutable. Keys are all lower case. 1095 * 1096 * @return The set of Unicode locale keys, or the empty set if this locale has 1097 * no Unicode locale keywords. 1098 * @since 1.7 1099 */ 1100 public Set<String> getUnicodeLocaleKeys() { 1101 if (localeExtensions == null) { 1102 return Collections.emptySet(); 1103 } 1104 return localeExtensions.getUnicodeLocaleKeys(); 1105 } 1106 1107 /** 1108 * Package locale method returning the Locale's BaseLocale, 1109 * used by ResourceBundle 1110 * @return base locale of this Locale 1111 */ 1112 BaseLocale getBaseLocale() { 1113 return baseLocale; 1114 } 1115 1116 /** 1117 * Package private method returning the Locale's LocaleExtensions, 1118 * used by ResourceBundle. 1119 * @return locale exnteions of this Locale, 1120 * or {@code null} if no extensions are defined 1121 */ 1122 LocaleExtensions getLocaleExtensions() { 1123 return localeExtensions; 1124 } 1125 1126 /** 1127 * Returns a string representation of this <code>Locale</code> 1128 * object, consisting of language, country, variant, script, 1129 * and extensions as below: 1130 * <p><blockquote> 1131 * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions 1132 * </blockquote> 1133 * 1134 * Language is always lower case, country is always upper case, script is always title 1135 * case, and extensions are always lower case. Extensions and private use subtags 1136 * will be in canonical order as explained in {@link #toLanguageTag}. 1137 * 1138 * <p>When the locale has neither script nor extensions, the result is the same as in 1139 * Java 6 and prior. 1140 * 1141 * <p>If both the language and country fields are missing, this function will return 1142 * the empty string, even if the variant, script, or extensions field is present (you 1143 * can't have a locale with just a variant, the variant must accompany a well-formed 1144 * language or country code). 1145 * 1146 * <p>If script or extensions are present and variant is missing, no underscore is 1147 * added before the "#". 1148 * 1149 * <p>This behavior is designed to support debugging and to be compatible with 1150 * previous uses of <code>toString</code> that expected language, country, and variant 1151 * fields only. To represent a Locale as a String for interchange purposes, use 1152 * {@link #toLanguageTag}. 1153 * 1154 * <p>Examples: <ul><tt> 1155 * <li>en 1156 * <li>de_DE 1157 * <li>_GB 1158 * <li>en_US_WIN 1159 * <li>de__POSIX 1160 * <li>zh_CN_#Hans 1161 * <li>zh_TW_#Hant-x-java 1162 * <li>th_TH_TH_#u-nu-thai</tt></ul> 1163 * 1164 * @return A string representation of the Locale, for debugging. 1165 * @see #getDisplayName 1166 * @see #toLanguageTag 1167 */ 1168 @Override 1169 public final String toString() { 1170 boolean l = (baseLocale.getLanguage().length() != 0); 1171 boolean s = (baseLocale.getScript().length() != 0); 1172 boolean r = (baseLocale.getRegion().length() != 0); 1173 boolean v = (baseLocale.getVariant().length() != 0); 1174 boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0); 1175 1176 StringBuilder result = new StringBuilder(baseLocale.getLanguage()); 1177 if (r || (l && (v || s || e))) { 1178 result.append('_') 1179 .append(baseLocale.getRegion()); // This may just append '_' 1180 } 1181 if (v && (l || r)) { 1182 result.append('_') 1183 .append(baseLocale.getVariant()); 1184 } 1185 1186 if (s && (l || r)) { 1187 result.append("_#") 1188 .append(baseLocale.getScript()); 1189 } 1190 1191 if (e && (l || r)) { 1192 result.append('_'); 1193 if (!s) { 1194 result.append('#'); 1195 } 1196 result.append(localeExtensions.getID()); 1197 } 1198 1199 return result.toString(); 1200 } 1201 1202 /** 1203 * Returns a well-formed IETF BCP 47 language tag representing 1204 * this locale. 1205 * 1206 * <p>If this <code>Locale</code> has a language, country, or 1207 * variant that does not satisfy the IETF BCP 47 language tag 1208 * syntax requirements, this method handles these fields as 1209 * described below: 1210 * 1211 * <p><b>Language:</b> If language is empty, or not <a 1212 * href="#def_language" >well-formed</a> (for example "a" or 1213 * "e2"), it will be emitted as "und" (Undetermined). 1214 * 1215 * <p><b>Country:</b> If country is not <a 1216 * href="#def_region">well-formed</a> (for example "12" or "USA"), 1217 * it will be omitted. 1218 * 1219 * <p><b>Variant:</b> If variant <b>is</b> <a 1220 * href="#def_variant">well-formed</a>, each sub-segment 1221 * (delimited by '-' or '_') is emitted as a subtag. Otherwise: 1222 * <ul> 1223 * 1224 * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code> 1225 * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first 1226 * ill-formed sub-segment and all following will be appended to 1227 * the private use subtag. The first appended subtag will be 1228 * "lvariant", followed by the sub-segments in order, separated by 1229 * hyphen. For example, "x-lvariant-WIN", 1230 * "Oracle-x-lvariant-JDK-Standard-Edition". 1231 * 1232 * <li>if any sub-segment does not match 1233 * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated 1234 * and the problematic sub-segment and all following sub-segments 1235 * will be omitted. If the remainder is non-empty, it will be 1236 * emitted as a private use subtag as above (even if the remainder 1237 * turns out to be well-formed). For example, 1238 * "Solaris_isjustthecoolestthing" is emitted as 1239 * "x-lvariant-Solaris", not as "solaris".</li></ul> 1240 * 1241 * <p><b>Special Conversions:</b> Java supports some old locale 1242 * representations, including deprecated ISO language codes, 1243 * for compatibility. This method performs the following 1244 * conversions: 1245 * <ul> 1246 * 1247 * <li>Deprecated ISO language codes "iw", "ji", and "in" are 1248 * converted to "he", "yi", and "id", respectively. 1249 * 1250 * <li>A locale with language "no", country "NO", and variant 1251 * "NY", representing Norwegian Nynorsk (Norway), is converted 1252 * to a language tag "nn-NO".</li></ul> 1253 * 1254 * <p><b>Note:</b> Although the language tag created by this 1255 * method is well-formed (satisfies the syntax requirements 1256 * defined by the IETF BCP 47 specification), it is not 1257 * necessarily a valid BCP 47 language tag. For example, 1258 * <pre> 1259 * new Locale("xx", "YY").toLanguageTag();</pre> 1260 * 1261 * will return "xx-YY", but the language subtag "xx" and the 1262 * region subtag "YY" are invalid because they are not registered 1263 * in the IANA Language Subtag Registry. 1264 * 1265 * @return a BCP47 language tag representing the locale 1266 * @see #forLanguageTag(String) 1267 * @since 1.7 1268 */ 1269 public String toLanguageTag() { 1270 LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions); 1271 StringBuilder buf = new StringBuilder(); 1272 1273 String subtag = tag.getLanguage(); 1274 if (subtag.length() > 0) { 1275 buf.append(LanguageTag.canonicalizeLanguage(subtag)); 1276 } 1277 1278 subtag = tag.getScript(); 1279 if (subtag.length() > 0) { 1280 buf.append(LanguageTag.SEP); 1281 buf.append(LanguageTag.canonicalizeScript(subtag)); 1282 } 1283 1284 subtag = tag.getRegion(); 1285 if (subtag.length() > 0) { 1286 buf.append(LanguageTag.SEP); 1287 buf.append(LanguageTag.canonicalizeRegion(subtag)); 1288 } 1289 1290 List<String>subtags = tag.getVariants(); 1291 for (String s : subtags) { 1292 buf.append(LanguageTag.SEP); 1293 // preserve casing 1294 buf.append(s); 1295 } 1296 1297 subtags = tag.getExtensions(); 1298 for (String s : subtags) { 1299 buf.append(LanguageTag.SEP); 1300 buf.append(LanguageTag.canonicalizeExtension(s)); 1301 } 1302 1303 subtag = tag.getPrivateuse(); 1304 if (subtag.length() > 0) { 1305 if (buf.length() > 0) { 1306 buf.append(LanguageTag.SEP); 1307 } 1308 buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP); 1309 // preserve casing 1310 buf.append(subtag); 1311 } 1312 1313 return buf.toString(); 1314 } 1315 1316 /** 1317 * Returns a locale for the specified IETF BCP 47 language tag string. 1318 * 1319 * <p>If the specified language tag contains any ill-formed subtags, 1320 * the first such subtag and all following subtags are ignored. Compare 1321 * to {@link Locale.Builder#setLanguageTag} which throws an exception 1322 * in this case. 1323 * 1324 * <p>The following <b>conversions</b> are performed:<ul> 1325 * 1326 * <li>The language code "und" is mapped to language "". 1327 * 1328 * <li>The language codes "he", "yi", and "id" are mapped to "iw", 1329 * "ji", and "in" respectively. (This is the same canonicalization 1330 * that's done in Locale's constructors.) 1331 * 1332 * <li>The portion of a private use subtag prefixed by "lvariant", 1333 * if any, is removed and appended to the variant field in the 1334 * result locale (without case normalization). If it is then 1335 * empty, the private use subtag is discarded: 1336 * 1337 * <pre> 1338 * Locale loc; 1339 * loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX"); 1340 * loc.getVariant(); // returns "POSIX" 1341 * loc.getExtension('x'); // returns null 1342 * 1343 * loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def"); 1344 * loc.getVariant(); // returns "POSIX_Abc_Def" 1345 * loc.getExtension('x'); // returns "urp" 1346 * </pre> 1347 * 1348 * <li>When the languageTag argument contains an extlang subtag, 1349 * the first such subtag is used as the language, and the primary 1350 * language subtag and other extlang subtags are ignored: 1351 * 1352 * <pre> 1353 * Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao" 1354 * Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US" 1355 * </pre> 1356 * 1357 * <li>Case is normalized except for variant tags, which are left 1358 * unchanged. Language is normalized to lower case, script to 1359 * title case, country to upper case, and extensions to lower 1360 * case. 1361 * 1362 * <li>If, after processing, the locale would exactly match either 1363 * ja_JP_JP or th_TH_TH with no extensions, the appropriate 1364 * extensions are added as though the constructor had been called: 1365 * 1366 * <pre> 1367 * Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag(); 1368 * // returns "ja-JP-u-ca-japanese-x-lvariant-JP" 1369 * Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag(); 1370 * // returns "th-TH-u-nu-thai-x-lvariant-TH" 1371 * <pre></ul> 1372 * 1373 * <p>This implements the 'Language-Tag' production of BCP47, and 1374 * so supports grandfathered (regular and irregular) as well as 1375 * private use language tags. Stand alone private use tags are 1376 * represented as empty language and extension 'x-whatever', 1377 * and grandfathered tags are converted to their canonical replacements 1378 * where they exist. 1379 * 1380 * <p>Grandfathered tags with canonical replacements are as follows: 1381 * 1382 * <table> 1383 * <tbody align="center"> 1384 * <tr><th>grandfathered tag</th><th> </th><th>modern replacement</th></tr> 1385 * <tr><td>art-lojban</td><td> </td><td>jbo</td></tr> 1386 * <tr><td>i-ami</td><td> </td><td>ami</td></tr> 1387 * <tr><td>i-bnn</td><td> </td><td>bnn</td></tr> 1388 * <tr><td>i-hak</td><td> </td><td>hak</td></tr> 1389 * <tr><td>i-klingon</td><td> </td><td>tlh</td></tr> 1390 * <tr><td>i-lux</td><td> </td><td>lb</td></tr> 1391 * <tr><td>i-navajo</td><td> </td><td>nv</td></tr> 1392 * <tr><td>i-pwn</td><td> </td><td>pwn</td></tr> 1393 * <tr><td>i-tao</td><td> </td><td>tao</td></tr> 1394 * <tr><td>i-tay</td><td> </td><td>tay</td></tr> 1395 * <tr><td>i-tsu</td><td> </td><td>tsu</td></tr> 1396 * <tr><td>no-bok</td><td> </td><td>nb</td></tr> 1397 * <tr><td>no-nyn</td><td> </td><td>nn</td></tr> 1398 * <tr><td>sgn-BE-FR</td><td> </td><td>sfb</td></tr> 1399 * <tr><td>sgn-BE-NL</td><td> </td><td>vgt</td></tr> 1400 * <tr><td>sgn-CH-DE</td><td> </td><td>sgg</td></tr> 1401 * <tr><td>zh-guoyu</td><td> </td><td>cmn</td></tr> 1402 * <tr><td>zh-hakka</td><td> </td><td>hak</td></tr> 1403 * <tr><td>zh-min-nan</td><td> </td><td>nan</td></tr> 1404 * <tr><td>zh-xiang</td><td> </td><td>hsn</td></tr> 1405 * </tbody> 1406 * </table> 1407 * 1408 * <p>Grandfathered tags with no modern replacement will be 1409 * converted as follows: 1410 * 1411 * <table> 1412 * <tbody align="center"> 1413 * <tr><th>grandfathered tag</th><th> </th><th>converts to</th></tr> 1414 * <tr><td>cel-gaulish</td><td> </td><td>xtg-x-cel-gaulish</td></tr> 1415 * <tr><td>en-GB-oed</td><td> </td><td>en-GB-x-oed</td></tr> 1416 * <tr><td>i-default</td><td> </td><td>en-x-i-default</td></tr> 1417 * <tr><td>i-enochian</td><td> </td><td>und-x-i-enochian</td></tr> 1418 * <tr><td>i-mingo</td><td> </td><td>see-x-i-mingo</td></tr> 1419 * <tr><td>zh-min</td><td> </td><td>nan-x-zh-min</td></tr> 1420 * </tbody> 1421 * </table> 1422 * 1423 * <p>For a list of all grandfathered tags, see the 1424 * IANA Language Subtag Registry (search for "Type: grandfathered"). 1425 * 1426 * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code> 1427 * and <code>forLanguageTag</code> will round-trip. 1428 * 1429 * @param languageTag the language tag 1430 * @return The locale that best represents the language tag. 1431 * @throws NullPointerException if <code>languageTag</code> is <code>null</code> 1432 * @see #toLanguageTag() 1433 * @see java.util.Locale.Builder#setLanguageTag(String) 1434 * @since 1.7 1435 */ 1436 public static Locale forLanguageTag(String languageTag) { 1437 LanguageTag tag = LanguageTag.parse(languageTag, null); 1438 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 1439 bldr.setLanguageTag(tag); 1440 BaseLocale base = bldr.getBaseLocale(); 1441 LocaleExtensions exts = bldr.getLocaleExtensions(); 1442 if (exts == null && base.getVariant().length() > 0) { 1443 exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(), 1444 base.getRegion(), base.getVariant()); 1445 } 1446 return getInstance(base, exts); 1447 } 1448 1449 /** 1450 * Returns a three-letter abbreviation of this locale's language. 1451 * If the language matches an ISO 639-1 two-letter code, the 1452 * corresponding ISO 639-2/T three-letter lowercase code is 1453 * returned. The ISO 639-2 language codes can be found on-line, 1454 * see "Codes for the Representation of Names of Languages Part 2: 1455 * Alpha-3 Code". If the locale specifies a three-letter 1456 * language, the language is returned as is. If the locale does 1457 * not specify a language the empty string is returned. 1458 * 1459 * @return A three-letter abbreviation of this locale's language. 1460 * @exception MissingResourceException Throws MissingResourceException if 1461 * three-letter language abbreviation is not available for this locale. 1462 */ 1463 public String getISO3Language() throws MissingResourceException { 1464 // Android-changed: Use ICU.getIso3Language. Also return "" for empty languages 1465 // for the sake of backwards compatibility. 1466 String lang = baseLocale.getLanguage(); 1467 if (lang.length() == 3) { 1468 return lang; 1469 } else if (lang.isEmpty()) { 1470 return ""; 1471 } 1472 1473 String language3 = ICU.getISO3Language(lang); 1474 if (language3.isEmpty()) { 1475 throw new MissingResourceException("Couldn't find 3-letter language code for " 1476 + lang, "FormatData_" + toString(), "ShortLanguage"); 1477 } 1478 1479 return language3; 1480 } 1481 1482 /** 1483 * Returns a three-letter abbreviation for this locale's country. 1484 * If the country matches an ISO 3166-1 alpha-2 code, the 1485 * corresponding ISO 3166-1 alpha-3 uppercase code is returned. 1486 * If the locale doesn't specify a country, this will be the empty 1487 * string. 1488 * 1489 * <p>The ISO 3166-1 codes can be found on-line. 1490 * 1491 * @return A three-letter abbreviation of this locale's country. 1492 * @exception MissingResourceException Throws MissingResourceException if the 1493 * three-letter country abbreviation is not available for this locale. 1494 */ 1495 public String getISO3Country() throws MissingResourceException { 1496 // Android changed: Use.getIso3Country. Also return "" for missing regions. 1497 final String region = baseLocale.getRegion(); 1498 // Note that this will return an UN.M49 region code 1499 if (region.length() == 3) { 1500 return baseLocale.getRegion(); 1501 } else if (region.isEmpty()) { 1502 return ""; 1503 } 1504 1505 // Prefix "en-" because ICU doesn't really care about what the language is. 1506 String country3 = ICU.getISO3Country("en-" + region); 1507 if (country3 == null) { 1508 throw new MissingResourceException("Couldn't find 3-letter country code for " 1509 + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry"); 1510 } 1511 return country3; 1512 } 1513 1514 /** 1515 * Returns a name for the locale's language that is appropriate for display to the 1516 * user. 1517 * If possible, the name returned will be localized for the default locale. 1518 * For example, if the locale is fr_FR and the default locale 1519 * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and 1520 * the default locale is fr_FR, getDisplayLanguage() will return "anglais". 1521 * If the name returned cannot be localized for the default locale, 1522 * (say, we don't have a Japanese name for Croatian), 1523 * this function falls back on the English name, and uses the ISO code as a last-resort 1524 * value. If the locale doesn't specify a language, this function returns the empty string. 1525 */ 1526 public final String getDisplayLanguage() { 1527 return getDisplayLanguage(getDefault(Category.DISPLAY)); 1528 } 1529 1530 /** 1531 * Returns the name of this locale's language, localized to {@code locale}. 1532 * If the language name is unknown, the language code is returned. 1533 */ 1534 public String getDisplayLanguage(Locale locale) { 1535 String languageCode = baseLocale.getLanguage(); 1536 if (languageCode.isEmpty()) { 1537 return ""; 1538 } 1539 1540 // Hacks for backward compatibility. 1541 // 1542 // Our language tag will contain "und" if the languageCode is invalid 1543 // or missing. ICU will then return "langue indéterminée" or the equivalent 1544 // display language for the indeterminate language code. 1545 // 1546 // Sigh... ugh... and what not. 1547 final String normalizedLanguage = normalizeAndValidateLanguage( 1548 languageCode, false /* strict */); 1549 if (UNDETERMINED_LANGUAGE.equals(normalizedLanguage)) { 1550 return languageCode; 1551 } 1552 1553 // TODO: We need a new hack or a complete fix for http://b/8049507 --- We would 1554 // cover the frameworks' tracks when they were using "tl" instead of "fil". 1555 String result = ICU.getDisplayLanguage(this, locale); 1556 if (result == null) { // TODO: do we need to do this, or does ICU do it for us? 1557 result = ICU.getDisplayLanguage(this, Locale.getDefault()); 1558 } 1559 return result; 1560 } 1561 1562 private static String normalizeAndValidateLanguage(String language, boolean strict) { 1563 if (language == null || language.isEmpty()) { 1564 return ""; 1565 } 1566 1567 final String lowercaseLanguage = language.toLowerCase(Locale.ROOT); 1568 if (!isValidBcp47Alpha(lowercaseLanguage, 2, 3)) { 1569 if (strict) { 1570 throw new IllformedLocaleException("Invalid language: " + language); 1571 } else { 1572 return UNDETERMINED_LANGUAGE; 1573 } 1574 } 1575 1576 return lowercaseLanguage; 1577 } 1578 1579 /* 1580 * Checks whether a given string is an ASCII alphanumeric string. 1581 */ 1582 private static boolean isAsciiAlphaNum(String string) { 1583 for (int i = 0; i < string.length(); i++) { 1584 final char character = string.charAt(i); 1585 if (!(character >= 'a' && character <= 'z' || 1586 character >= 'A' && character <= 'Z' || 1587 character >= '0' && character <= '9')) { 1588 return false; 1589 } 1590 } 1591 1592 return true; 1593 } 1594 1595 /** 1596 * Returns a name for the the locale's script that is appropriate for display to 1597 * the user. If possible, the name will be localized for the default locale. Returns 1598 * the empty string if this locale doesn't specify a script code. 1599 * 1600 * @return the display name of the script code for the current default locale 1601 * @since 1.7 1602 */ 1603 public String getDisplayScript() { 1604 return getDisplayScript(getDefault()); 1605 } 1606 1607 /** 1608 * Returns the name of this locale's script code, localized to {@link Locale}. If the 1609 * script code is unknown, the return value of this method is the same as that of 1610 * {@link #getScript()}. 1611 * 1612 * @since 1.7 1613 */ 1614 public String getDisplayScript(Locale locale) { 1615 String scriptCode = baseLocale.getScript(); 1616 if (scriptCode.isEmpty()) { 1617 return ""; 1618 } 1619 1620 String result = ICU.getDisplayScript(this, locale); 1621 if (result == null) { // TODO: do we need to do this, or does ICU do it for us? 1622 result = ICU.getDisplayScript(this, Locale.getDefault()); 1623 } 1624 1625 return result; 1626 1627 } 1628 1629 /** 1630 * Returns a name for the locale's country that is appropriate for display to the 1631 * user. 1632 * If possible, the name returned will be localized for the default locale. 1633 * For example, if the locale is fr_FR and the default locale 1634 * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and 1635 * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis". 1636 * If the name returned cannot be localized for the default locale, 1637 * (say, we don't have a Japanese name for Croatia), 1638 * this function falls back on the English name, and uses the ISO code as a last-resort 1639 * value. If the locale doesn't specify a country, this function returns the empty string. 1640 */ 1641 public final String getDisplayCountry() { 1642 return getDisplayCountry(getDefault(Category.DISPLAY)); 1643 } 1644 /** 1645 * Returns the name of this locale's country, localized to {@code locale}. 1646 * Returns the empty string if this locale does not correspond to a specific 1647 * country. 1648 */ 1649 public String getDisplayCountry(Locale locale) { 1650 String countryCode = baseLocale.getRegion(); 1651 if (countryCode.isEmpty()) { 1652 return ""; 1653 } 1654 1655 final String normalizedRegion = normalizeAndValidateRegion( 1656 countryCode, false /* strict */); 1657 if (normalizedRegion.isEmpty()) { 1658 return countryCode; 1659 } 1660 1661 String result = ICU.getDisplayCountry(this, locale); 1662 if (result == null) { // TODO: do we need to do this, or does ICU do it for us? 1663 result = ICU.getDisplayCountry(this, Locale.getDefault()); 1664 } 1665 return result; 1666 } 1667 1668 private static String normalizeAndValidateRegion(String region, boolean strict) { 1669 if (region == null || region.isEmpty()) { 1670 return ""; 1671 } 1672 1673 final String uppercaseRegion = region.toUpperCase(Locale.ROOT); 1674 if (!isValidBcp47Alpha(uppercaseRegion, 2, 2) && 1675 !isUnM49AreaCode(uppercaseRegion)) { 1676 if (strict) { 1677 throw new IllformedLocaleException("Invalid region: " + region); 1678 } else { 1679 return ""; 1680 } 1681 } 1682 1683 return uppercaseRegion; 1684 } 1685 1686 private static boolean isValidBcp47Alpha(String string, int lowerBound, int upperBound) { 1687 final int length = string.length(); 1688 if (length < lowerBound || length > upperBound) { 1689 return false; 1690 } 1691 1692 for (int i = 0; i < length; ++i) { 1693 final char character = string.charAt(i); 1694 if (!(character >= 'a' && character <= 'z' || 1695 character >= 'A' && character <= 'Z')) { 1696 return false; 1697 } 1698 } 1699 1700 return true; 1701 } 1702 1703 /** 1704 * A UN M.49 is a 3 digit numeric code. 1705 */ 1706 private static boolean isUnM49AreaCode(String code) { 1707 if (code.length() != 3) { 1708 return false; 1709 } 1710 1711 for (int i = 0; i < 3; ++i) { 1712 final char character = code.charAt(i); 1713 if (!(character >= '0' && character <= '9')) { 1714 return false; 1715 } 1716 } 1717 1718 return true; 1719 } 1720 1721 /** 1722 * Returns a name for the locale's variant code that is appropriate for display to the 1723 * user. If possible, the name will be localized for the default locale. If the locale 1724 * doesn't specify a variant code, this function returns the empty string. 1725 */ 1726 public final String getDisplayVariant() { 1727 return getDisplayVariant(getDefault(Category.DISPLAY)); 1728 } 1729 1730 /** 1731 * Returns the full variant name in the specified {@code Locale} for the variant code 1732 * of this {@code Locale}. If there is no matching variant name, the variant code is 1733 * returned. 1734 * 1735 * @since 1.7 1736 */ 1737 public String getDisplayVariant(Locale locale) { 1738 String variantCode = baseLocale.getVariant(); 1739 if (variantCode.isEmpty()) { 1740 return ""; 1741 } 1742 1743 try { 1744 normalizeAndValidateVariant(variantCode); 1745 } catch (IllformedLocaleException ilfe) { 1746 return variantCode; 1747 } 1748 1749 String result = ICU.getDisplayVariant(this, locale); 1750 if (result == null) { // TODO: do we need to do this, or does ICU do it for us? 1751 result = ICU.getDisplayVariant(this, Locale.getDefault()); 1752 } 1753 1754 // The "old style" locale constructors allow us to pass in variants that aren't 1755 // valid BCP-47 variant subtags. When that happens, toLanguageTag will not emit 1756 // them. Note that we know variantCode.length() > 0 due to the isEmpty check at 1757 // the beginning of this function. 1758 if (result.isEmpty()) { 1759 return variantCode; 1760 } 1761 return result; 1762 } 1763 1764 private static String normalizeAndValidateVariant(String variant) { 1765 if (variant == null || variant.isEmpty()) { 1766 return ""; 1767 } 1768 1769 // Note that unlike extensions, we canonicalize to lower case alphabets 1770 // and underscores instead of hyphens. 1771 final String normalizedVariant = variant.replace('-', '_'); 1772 String[] subTags = normalizedVariant.split("_"); 1773 1774 for (String subTag : subTags) { 1775 if (!isValidVariantSubtag(subTag)) { 1776 throw new IllformedLocaleException("Invalid variant: " + variant); 1777 } 1778 } 1779 1780 return normalizedVariant; 1781 } 1782 1783 private static boolean isValidVariantSubtag(String subTag) { 1784 // The BCP-47 spec states that : 1785 // - Subtags can be between [5, 8] alphanumeric chars in length. 1786 // - Subtags that start with a number are allowed to be 4 chars in length. 1787 if (subTag.length() >= 5 && subTag.length() <= 8) { 1788 if (isAsciiAlphaNum(subTag)) { 1789 return true; 1790 } 1791 } else if (subTag.length() == 4) { 1792 final char firstChar = subTag.charAt(0); 1793 if ((firstChar >= '0' && firstChar <= '9') && isAsciiAlphaNum(subTag)) { 1794 return true; 1795 } 1796 } 1797 1798 return false; 1799 } 1800 1801 /** 1802 * Returns a name for the locale that is appropriate for display to the 1803 * user. This will be the values returned by getDisplayLanguage(), 1804 * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled 1805 * into a single string. The the non-empty values are used in order, 1806 * with the second and subsequent names in parentheses. For example: 1807 * <blockquote> 1808 * language (script, country, variant)<br> 1809 * language (country)<br> 1810 * language (variant)<br> 1811 * script (country)<br> 1812 * country<br> 1813 * </blockquote> 1814 * depending on which fields are specified in the locale. If the 1815 * language, sacript, country, and variant fields are all empty, 1816 * this function returns the empty string. 1817 */ 1818 public final String getDisplayName() { 1819 return getDisplayName(getDefault(Category.DISPLAY)); 1820 } 1821 1822 /** 1823 * Returns this locale's language name, country name, and variant, localized 1824 * to {@code locale}. The exact output form depends on whether this locale 1825 * corresponds to a specific language, script, country and variant. 1826 * 1827 * <p>For example: 1828 * <ul> 1829 * <li>{@code new Locale("en").getDisplayName(Locale.US)} -> {@code English} 1830 * <li>{@code new Locale("en", "US").getDisplayName(Locale.US)} -> {@code English (United States)} 1831 * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.US)} -> {@code English (United States,Computer)} 1832 * <li>{@code Locale.fromLanguageTag("zh-Hant-CN").getDisplayName(Locale.US)} -> {@code Chinese (Traditional Han,China)} 1833 * <li>{@code new Locale("en").getDisplayName(Locale.FRANCE)} -> {@code anglais} 1834 * <li>{@code new Locale("en", "US").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis)} 1835 * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis,informatique)}. 1836 * </ul> 1837 */ 1838 public String getDisplayName(Locale locale) { 1839 int count = 0; 1840 StringBuilder buffer = new StringBuilder(); 1841 String languageCode = baseLocale.getLanguage(); 1842 if (!languageCode.isEmpty()) { 1843 String displayLanguage = getDisplayLanguage(locale); 1844 buffer.append(displayLanguage.isEmpty() ? languageCode : displayLanguage); 1845 ++count; 1846 } 1847 String scriptCode = baseLocale.getScript(); 1848 if (!scriptCode.isEmpty()) { 1849 if (count == 1) { 1850 buffer.append(" ("); 1851 } 1852 String displayScript = getDisplayScript(locale); 1853 buffer.append(displayScript.isEmpty() ? scriptCode : displayScript); 1854 ++count; 1855 } 1856 String countryCode = baseLocale.getRegion(); 1857 if (!countryCode.isEmpty()) { 1858 if (count == 1) { 1859 buffer.append(" ("); 1860 } else if (count == 2) { 1861 buffer.append(","); 1862 } 1863 String displayCountry = getDisplayCountry(locale); 1864 buffer.append(displayCountry.isEmpty() ? countryCode : displayCountry); 1865 ++count; 1866 } 1867 String variantCode = baseLocale.getVariant(); 1868 if (!variantCode.isEmpty()) { 1869 if (count == 1) { 1870 buffer.append(" ("); 1871 } else if (count == 2 || count == 3) { 1872 buffer.append(","); 1873 } 1874 String displayVariant = getDisplayVariant(locale); 1875 buffer.append(displayVariant.isEmpty() ? variantCode : displayVariant); 1876 ++count; 1877 } 1878 if (count > 1) { 1879 buffer.append(")"); 1880 } 1881 return buffer.toString(); 1882 } 1883 1884 /** 1885 * Overrides Cloneable. 1886 */ 1887 public Object clone() 1888 { 1889 try { 1890 Locale that = (Locale)super.clone(); 1891 return that; 1892 } catch (CloneNotSupportedException e) { 1893 throw new InternalError(); 1894 } 1895 } 1896 1897 /** 1898 * Override hashCode. 1899 * Since Locales are often used in hashtables, caches the value 1900 * for speed. 1901 */ 1902 @Override 1903 public int hashCode() { 1904 int hc = hashCodeValue; 1905 if (hc == 0) { 1906 hc = baseLocale.hashCode(); 1907 if (localeExtensions != null) { 1908 hc ^= localeExtensions.hashCode(); 1909 } 1910 hashCodeValue = hc; 1911 } 1912 return hc; 1913 } 1914 1915 // Overrides 1916 1917 /** 1918 * Returns true if this Locale is equal to another object. A Locale is 1919 * deemed equal to another Locale with identical language, script, country, 1920 * variant and extensions, and unequal to all other objects. 1921 * 1922 * @return true if this Locale is equal to the specified object. 1923 */ 1924 @Override 1925 public boolean equals(Object obj) { 1926 if (this == obj) // quick check 1927 return true; 1928 if (!(obj instanceof Locale)) 1929 return false; 1930 BaseLocale otherBase = ((Locale)obj).baseLocale; 1931 if (!baseLocale.equals(otherBase)) { 1932 return false; 1933 } 1934 if (localeExtensions == null) { 1935 return ((Locale)obj).localeExtensions == null; 1936 } 1937 return localeExtensions.equals(((Locale)obj).localeExtensions); 1938 } 1939 1940 // ================= privates ===================================== 1941 1942 private transient BaseLocale baseLocale; 1943 private transient LocaleExtensions localeExtensions; 1944 1945 /** 1946 * Calculated hashcode 1947 */ 1948 private transient volatile int hashCodeValue = 0; 1949 1950 private static Locale defaultLocale = null; 1951 private static Locale defaultDisplayLocale = null; 1952 private static Locale defaultFormatLocale = null; 1953 1954 /** 1955 * Format a list using given pattern strings. 1956 * If either of the patterns is null, then a the list is 1957 * formatted by concatenation with the delimiter ','. 1958 * @param stringList the list of strings to be formatted. 1959 * @param listPattern should create a MessageFormat taking 0-3 arguments 1960 * and formatting them into a list. 1961 * @param listCompositionPattern should take 2 arguments 1962 * and is used by composeList. 1963 * @return a string representing the list. 1964 */ 1965 private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) { 1966 // If we have no list patterns, compose the list in a simple, 1967 // non-localized way. 1968 if (listPattern == null || listCompositionPattern == null) { 1969 StringBuffer result = new StringBuffer(); 1970 for (int i=0; i<stringList.length; ++i) { 1971 if (i>0) result.append(','); 1972 result.append(stringList[i]); 1973 } 1974 return result.toString(); 1975 } 1976 1977 // Compose the list down to three elements if necessary 1978 if (stringList.length > 3) { 1979 MessageFormat format = new MessageFormat(listCompositionPattern); 1980 stringList = composeList(format, stringList); 1981 } 1982 1983 // Rebuild the argument list with the list length as the first element 1984 Object[] args = new Object[stringList.length + 1]; 1985 System.arraycopy(stringList, 0, args, 1, stringList.length); 1986 args[0] = new Integer(stringList.length); 1987 1988 // Format it using the pattern in the resource 1989 MessageFormat format = new MessageFormat(listPattern); 1990 return format.format(args); 1991 } 1992 1993 /** 1994 * Given a list of strings, return a list shortened to three elements. 1995 * Shorten it by applying the given format to the first two elements 1996 * recursively. 1997 * @param format a format which takes two arguments 1998 * @param list a list of strings 1999 * @return if the list is three elements or shorter, the same list; 2000 * otherwise, a new list of three elements. 2001 */ 2002 private static String[] composeList(MessageFormat format, String[] list) { 2003 if (list.length <= 3) return list; 2004 2005 // Use the given format to compose the first two elements into one 2006 String[] listItems = { list[0], list[1] }; 2007 String newItem = format.format(listItems); 2008 2009 // Form a new list one element shorter 2010 String[] newList = new String[list.length-1]; 2011 System.arraycopy(list, 2, newList, 1, newList.length-1); 2012 newList[0] = newItem; 2013 2014 // Recurse 2015 return composeList(format, newList); 2016 } 2017 2018 /** 2019 * @serialField language String 2020 * language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>) 2021 * @serialField country String 2022 * country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>) 2023 * @serialField variant String 2024 * variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>) 2025 * @serialField hashcode int 2026 * deprecated, for forward compatibility only 2027 * @serialField script String 2028 * script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>) 2029 * @serialField extensions String 2030 * canonical representation of extensions, that is, 2031 * BCP47 extensions in alphabetical order followed by 2032 * BCP47 private use subtags, all in lower case letters 2033 * separated by HYPHEN-MINUS characters. 2034 * (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>, 2035 * <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>) 2036 */ 2037 private static final ObjectStreamField[] serialPersistentFields = { 2038 new ObjectStreamField("language", String.class), 2039 new ObjectStreamField("country", String.class), 2040 new ObjectStreamField("variant", String.class), 2041 new ObjectStreamField("hashcode", int.class), 2042 new ObjectStreamField("script", String.class), 2043 new ObjectStreamField("extensions", String.class), 2044 }; 2045 2046 /** 2047 * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>. 2048 * @param out the <code>ObjectOutputStream</code> to write 2049 * @throws IOException 2050 * @since 1.7 2051 */ 2052 private void writeObject(ObjectOutputStream out) throws IOException { 2053 ObjectOutputStream.PutField fields = out.putFields(); 2054 fields.put("language", baseLocale.getLanguage()); 2055 fields.put("script", baseLocale.getScript()); 2056 fields.put("country", baseLocale.getRegion()); 2057 fields.put("variant", baseLocale.getVariant()); 2058 fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID()); 2059 fields.put("hashcode", -1); // place holder just for backward support 2060 out.writeFields(); 2061 } 2062 2063 /** 2064 * Deserializes this <code>Locale</code>. 2065 * @param in the <code>ObjectInputStream</code> to read 2066 * @throws IOException 2067 * @throws ClassNotFoundException 2068 * @throws IllformedLocaleException 2069 * @since 1.7 2070 */ 2071 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 2072 ObjectInputStream.GetField fields = in.readFields(); 2073 String language = (String)fields.get("language", ""); 2074 String script = (String)fields.get("script", ""); 2075 String country = (String)fields.get("country", ""); 2076 String variant = (String)fields.get("variant", ""); 2077 String extStr = (String)fields.get("extensions", ""); 2078 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant); 2079 if (extStr.length() > 0) { 2080 try { 2081 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 2082 bldr.setExtensions(extStr); 2083 localeExtensions = bldr.getLocaleExtensions(); 2084 } catch (LocaleSyntaxException e) { 2085 throw new IllformedLocaleException(e.getMessage()); 2086 } 2087 } else { 2088 localeExtensions = null; 2089 } 2090 } 2091 2092 /** 2093 * Returns a cached <code>Locale</code> instance equivalent to 2094 * the deserialized <code>Locale</code>. When serialized 2095 * language, country and variant fields read from the object data stream 2096 * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions 2097 * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code> 2098 * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script 2099 * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a> 2100 * for more information. 2101 * 2102 * @return an instance of <code>Locale</code> equivalent to 2103 * the deserialized <code>Locale</code>. 2104 * @throws java.io.ObjectStreamException 2105 */ 2106 private Object readResolve() throws java.io.ObjectStreamException { 2107 return getInstance(baseLocale.getLanguage(), baseLocale.getScript(), 2108 baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions); 2109 } 2110 2111 private static volatile String[] isoLanguages = null; 2112 2113 private static volatile String[] isoCountries = null; 2114 2115 private static String convertOldISOCodes(String language) { 2116 // we accept both the old and the new ISO codes for the languages whose ISO 2117 // codes have changed, but we always store the OLD code, for backward compatibility 2118 language = LocaleUtils.toLowerString(language).intern(); 2119 if (language == "he") { 2120 return "iw"; 2121 } else if (language == "yi") { 2122 return "ji"; 2123 } else if (language == "id") { 2124 return "in"; 2125 } else { 2126 return language; 2127 } 2128 } 2129 2130 private static LocaleExtensions getCompatibilityExtensions(String language, 2131 String script, 2132 String country, 2133 String variant) { 2134 LocaleExtensions extensions = null; 2135 // Special cases for backward compatibility support 2136 if (LocaleUtils.caseIgnoreMatch(language, "ja") 2137 && script.length() == 0 2138 && LocaleUtils.caseIgnoreMatch(country, "jp") 2139 && "JP".equals(variant)) { 2140 // ja_JP_JP -> u-ca-japanese (calendar = japanese) 2141 extensions = LocaleExtensions.CALENDAR_JAPANESE; 2142 } else if (LocaleUtils.caseIgnoreMatch(language, "th") 2143 && script.length() == 0 2144 && LocaleUtils.caseIgnoreMatch(country, "th") 2145 && "TH".equals(variant)) { 2146 // th_TH_TH -> u-nu-thai (numbersystem = thai) 2147 extensions = LocaleExtensions.NUMBER_THAI; 2148 } 2149 return extensions; 2150 } 2151 2152 /** 2153 * @hide for internal use only. 2154 */ 2155 public static String adjustLanguageCode(String languageCode) { 2156 String adjusted = languageCode.toLowerCase(Locale.US); 2157 // Map new language codes to the obsolete language 2158 // codes so the correct resource bundles will be used. 2159 if (languageCode.equals("he")) { 2160 adjusted = "iw"; 2161 } else if (languageCode.equals("id")) { 2162 adjusted = "in"; 2163 } else if (languageCode.equals("yi")) { 2164 adjusted = "ji"; 2165 } 2166 2167 return adjusted; 2168 } 2169 2170 /** 2171 * Enum for locale categories. These locale categories are used to get/set 2172 * the default locale for the specific functionality represented by the 2173 * category. 2174 * 2175 * @see #getDefault(Locale.Category) 2176 * @see #setDefault(Locale.Category, Locale) 2177 * @since 1.7 2178 */ 2179 public enum Category { 2180 2181 /** 2182 * Category used to represent the default locale for 2183 * displaying user interfaces. 2184 */ 2185 DISPLAY("user.language.display", 2186 "user.script.display", 2187 "user.country.display", 2188 "user.variant.display"), 2189 2190 /** 2191 * Category used to represent the default locale for 2192 * formatting dates, numbers, and/or currencies. 2193 */ 2194 FORMAT("user.language.format", 2195 "user.script.format", 2196 "user.country.format", 2197 "user.variant.format"); 2198 2199 Category(String languageKey, String scriptKey, String countryKey, String variantKey) { 2200 this.languageKey = languageKey; 2201 this.scriptKey = scriptKey; 2202 this.countryKey = countryKey; 2203 this.variantKey = variantKey; 2204 } 2205 2206 final String languageKey; 2207 final String scriptKey; 2208 final String countryKey; 2209 final String variantKey; 2210 } 2211 2212 /** 2213 * <code>Builder</code> is used to build instances of <code>Locale</code> 2214 * from values configured by the setters. Unlike the <code>Locale</code> 2215 * constructors, the <code>Builder</code> checks if a value configured by a 2216 * setter satisfies the syntax requirements defined by the <code>Locale</code> 2217 * class. A <code>Locale</code> object created by a <code>Builder</code> is 2218 * well-formed and can be transformed to a well-formed IETF BCP 47 language tag 2219 * without losing information. 2220 * 2221 * <p><b>Note:</b> The <code>Locale</code> class does not provide any 2222 * syntactic restrictions on variant, while BCP 47 requires each variant 2223 * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3 2224 * alphanumerics. The method <code>setVariant</code> throws 2225 * <code>IllformedLocaleException</code> for a variant that does not satisfy 2226 * this restriction. If it is necessary to support such a variant, use a 2227 * Locale constructor. However, keep in mind that a <code>Locale</code> 2228 * object created this way might lose the variant information when 2229 * transformed to a BCP 47 language tag. 2230 * 2231 * <p>The following example shows how to create a <code>Locale</code> object 2232 * with the <code>Builder</code>. 2233 * <blockquote> 2234 * <pre> 2235 * Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build(); 2236 * </pre> 2237 * </blockquote> 2238 * 2239 * <p>Builders can be reused; <code>clear()</code> resets all 2240 * fields to their default values. 2241 * 2242 * @see Locale#forLanguageTag 2243 * @since 1.7 2244 */ 2245 public static final class Builder { 2246 private final InternalLocaleBuilder localeBuilder; 2247 2248 /** 2249 * Constructs an empty Builder. The default value of all 2250 * fields, extensions, and private use information is the 2251 * empty string. 2252 */ 2253 public Builder() { 2254 localeBuilder = new InternalLocaleBuilder(); 2255 } 2256 2257 /** 2258 * Resets the <code>Builder</code> to match the provided 2259 * <code>locale</code>. Existing state is discarded. 2260 * 2261 * <p>All fields of the locale must be well-formed, see {@link Locale}. 2262 * 2263 * <p>Locales with any ill-formed fields cause 2264 * <code>IllformedLocaleException</code> to be thrown, except for the 2265 * following three cases which are accepted for compatibility 2266 * reasons:<ul> 2267 * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese" 2268 * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai" 2269 * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul> 2270 * 2271 * @param locale the locale 2272 * @return This builder. 2273 * @throws IllformedLocaleException if <code>locale</code> has 2274 * any ill-formed fields. 2275 * @throws NullPointerException if <code>locale</code> is null. 2276 */ 2277 public Builder setLocale(Locale locale) { 2278 try { 2279 localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions); 2280 } catch (LocaleSyntaxException e) { 2281 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2282 } 2283 return this; 2284 } 2285 2286 /** 2287 * Resets the Builder to match the provided IETF BCP 47 2288 * language tag. Discards the existing state. Null and the 2289 * empty string cause the builder to be reset, like {@link 2290 * #clear}. Grandfathered tags (see {@link 2291 * Locale#forLanguageTag}) are converted to their canonical 2292 * form before being processed. Otherwise, the language tag 2293 * must be well-formed (see {@link Locale}) or an exception is 2294 * thrown (unlike <code>Locale.forLanguageTag</code>, which 2295 * just discards ill-formed and following portions of the 2296 * tag). 2297 * 2298 * @param languageTag the language tag 2299 * @return This builder. 2300 * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed 2301 * @see Locale#forLanguageTag(String) 2302 */ 2303 public Builder setLanguageTag(String languageTag) { 2304 ParseStatus sts = new ParseStatus(); 2305 LanguageTag tag = LanguageTag.parse(languageTag, sts); 2306 if (sts.isError()) { 2307 throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex()); 2308 } 2309 localeBuilder.setLanguageTag(tag); 2310 return this; 2311 } 2312 2313 /** 2314 * Sets the language. If <code>language</code> is the empty string or 2315 * null, the language in this <code>Builder</code> is removed. Otherwise, 2316 * the language must be <a href="./Locale.html#def_language">well-formed</a> 2317 * or an exception is thrown. 2318 * 2319 * <p>The typical language value is a two or three-letter language 2320 * code as defined in ISO639. 2321 * 2322 * @param language the language 2323 * @return This builder. 2324 * @throws IllformedLocaleException if <code>language</code> is ill-formed 2325 */ 2326 public Builder setLanguage(String language) { 2327 try { 2328 localeBuilder.setLanguage(language); 2329 } catch (LocaleSyntaxException e) { 2330 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2331 } 2332 return this; 2333 } 2334 2335 /** 2336 * Sets the script. If <code>script</code> is null or the empty string, 2337 * the script in this <code>Builder</code> is removed. 2338 * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an 2339 * exception is thrown. 2340 * 2341 * <p>The typical script value is a four-letter script code as defined by ISO 15924. 2342 * 2343 * @param script the script 2344 * @return This builder. 2345 * @throws IllformedLocaleException if <code>script</code> is ill-formed 2346 */ 2347 public Builder setScript(String script) { 2348 try { 2349 localeBuilder.setScript(script); 2350 } catch (LocaleSyntaxException e) { 2351 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2352 } 2353 return this; 2354 } 2355 2356 /** 2357 * Sets the region. If region is null or the empty string, the region 2358 * in this <code>Builder</code> is removed. Otherwise, 2359 * the region must be <a href="./Locale.html#def_region">well-formed</a> or an 2360 * exception is thrown. 2361 * 2362 * <p>The typical region value is a two-letter ISO 3166 code or a 2363 * three-digit UN M.49 area code. 2364 * 2365 * <p>The country value in the <code>Locale</code> created by the 2366 * <code>Builder</code> is always normalized to upper case. 2367 * 2368 * @param region the region 2369 * @return This builder. 2370 * @throws IllformedLocaleException if <code>region</code> is ill-formed 2371 */ 2372 public Builder setRegion(String region) { 2373 try { 2374 localeBuilder.setRegion(region); 2375 } catch (LocaleSyntaxException e) { 2376 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2377 } 2378 return this; 2379 } 2380 2381 /** 2382 * Sets the variant. If variant is null or the empty string, the 2383 * variant in this <code>Builder</code> is removed. Otherwise, it 2384 * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a> 2385 * subtags, or an exception is thrown. 2386 * 2387 * <p><b>Note:</b> This method checks if <code>variant</code> 2388 * satisfies the IETF BCP 47 variant subtag's syntax requirements, 2389 * and normalizes the value to lowercase letters. However, 2390 * the <code>Locale</code> class does not impose any syntactic 2391 * restriction on variant, and the variant value in 2392 * <code>Locale</code> is case sensitive. To set such a variant, 2393 * use a Locale constructor. 2394 * 2395 * @param variant the variant 2396 * @return This builder. 2397 * @throws IllformedLocaleException if <code>variant</code> is ill-formed 2398 */ 2399 public Builder setVariant(String variant) { 2400 try { 2401 localeBuilder.setVariant(variant); 2402 } catch (LocaleSyntaxException e) { 2403 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2404 } 2405 return this; 2406 } 2407 2408 /** 2409 * Sets the extension for the given key. If the value is null or the 2410 * empty string, the extension is removed. Otherwise, the extension 2411 * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception 2412 * is thrown. 2413 * 2414 * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION 2415 * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension. 2416 * Setting a value for this key replaces any existing Unicode locale key/type 2417 * pairs with those defined in the extension. 2418 * 2419 * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION 2420 * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be 2421 * well-formed, the value for this key needs only to have subtags of one to 2422 * eight alphanumeric characters, not two to eight as in the general case. 2423 * 2424 * @param key the extension key 2425 * @param value the extension value 2426 * @return This builder. 2427 * @throws IllformedLocaleException if <code>key</code> is illegal 2428 * or <code>value</code> is ill-formed 2429 * @see #setUnicodeLocaleKeyword(String, String) 2430 */ 2431 public Builder setExtension(char key, String value) { 2432 try { 2433 localeBuilder.setExtension(key, value); 2434 } catch (LocaleSyntaxException e) { 2435 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2436 } 2437 return this; 2438 } 2439 2440 /** 2441 * Sets the Unicode locale keyword type for the given key. If the type 2442 * is null, the Unicode keyword is removed. Otherwise, the key must be 2443 * non-null and both key and type must be <a 2444 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2445 * is thrown. 2446 * 2447 * <p>Keys and types are converted to lower case. 2448 * 2449 * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension} 2450 * replaces all Unicode locale keywords with those defined in the 2451 * extension. 2452 * 2453 * @param key the Unicode locale key 2454 * @param type the Unicode locale type 2455 * @return This builder. 2456 * @throws IllformedLocaleException if <code>key</code> or <code>type</code> 2457 * is ill-formed 2458 * @throws NullPointerException if <code>key</code> is null 2459 * @see #setExtension(char, String) 2460 */ 2461 public Builder setUnicodeLocaleKeyword(String key, String type) { 2462 try { 2463 localeBuilder.setUnicodeLocaleKeyword(key, type); 2464 } catch (LocaleSyntaxException e) { 2465 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2466 } 2467 return this; 2468 } 2469 2470 /** 2471 * Adds a unicode locale attribute, if not already present, otherwise 2472 * has no effect. The attribute must not be null and must be <a 2473 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2474 * is thrown. 2475 * 2476 * @param attribute the attribute 2477 * @return This builder. 2478 * @throws NullPointerException if <code>attribute</code> is null 2479 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2480 * @see #setExtension(char, String) 2481 */ 2482 public Builder addUnicodeLocaleAttribute(String attribute) { 2483 try { 2484 localeBuilder.addUnicodeLocaleAttribute(attribute); 2485 } catch (LocaleSyntaxException e) { 2486 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2487 } 2488 return this; 2489 } 2490 2491 /** 2492 * Removes a unicode locale attribute, if present, otherwise has no 2493 * effect. The attribute must not be null and must be <a 2494 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2495 * is thrown. 2496 * 2497 * <p>Attribute comparision for removal is case-insensitive. 2498 * 2499 * @param attribute the attribute 2500 * @return This builder. 2501 * @throws NullPointerException if <code>attribute</code> is null 2502 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2503 * @see #setExtension(char, String) 2504 */ 2505 public Builder removeUnicodeLocaleAttribute(String attribute) { 2506 try { 2507 localeBuilder.removeUnicodeLocaleAttribute(attribute); 2508 } catch (LocaleSyntaxException e) { 2509 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2510 } 2511 return this; 2512 } 2513 2514 /** 2515 * Resets the builder to its initial, empty state. 2516 * 2517 * @return This builder. 2518 */ 2519 public Builder clear() { 2520 localeBuilder.clear(); 2521 return this; 2522 } 2523 2524 /** 2525 * Resets the extensions to their initial, empty state. 2526 * Language, script, region and variant are unchanged. 2527 * 2528 * @return This builder. 2529 * @see #setExtension(char, String) 2530 */ 2531 public Builder clearExtensions() { 2532 localeBuilder.clearExtensions(); 2533 return this; 2534 } 2535 2536 /** 2537 * Returns an instance of <code>Locale</code> created from the fields set 2538 * on this builder. 2539 * 2540 * <p>This applies the conversions listed in {@link Locale#forLanguageTag} 2541 * when constructing a Locale. (Grandfathered tags are handled in 2542 * {@link #setLanguageTag}.) 2543 * 2544 * @return A Locale. 2545 */ 2546 public Locale build() { 2547 BaseLocale baseloc = localeBuilder.getBaseLocale(); 2548 LocaleExtensions extensions = localeBuilder.getLocaleExtensions(); 2549 if (extensions == null && baseloc.getVariant().length() > 0) { 2550 extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(), 2551 baseloc.getRegion(), baseloc.getVariant()); 2552 } 2553 return Locale.getInstance(baseloc, extensions); 2554 } 2555 } 2556} 2557