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