1 /* 2 * Copyright (c) 1996, 2012, 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 41 package java.util; 42 43 import java.io.IOException; 44 import java.io.ObjectInputStream; 45 import java.io.ObjectOutputStream; 46 import java.io.ObjectStreamField; 47 import java.io.Serializable; 48 import java.security.AccessController; 49 import java.text.MessageFormat; 50 import java.util.spi.LocaleNameProvider; 51 52 import sun.security.action.GetPropertyAction; 53 import sun.util.locale.provider.LocaleServiceProviderPool; 54 import sun.util.locale.BaseLocale; 55 import sun.util.locale.InternalLocaleBuilder; 56 import sun.util.locale.LanguageTag; 57 import sun.util.locale.LocaleExtensions; 58 import sun.util.locale.LocaleObjectCache; 59 import sun.util.locale.LocaleSyntaxException; 60 import sun.util.locale.LocaleUtils; 61 import sun.util.locale.ParseStatus; 62 import sun.util.locale.provider.LocaleProviderAdapter; 63 import sun.util.resources.OpenListResourceBundle; 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 */ 408 public 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 * Useful constant for the root locale. The root locale is the locale whose 498 * language, country, and variant are empty ("") strings. This is regarded 499 * as the base locale of all locales, and is used as the language/country 500 * neutral locale for the locale sensitive operations. 501 * 502 * @since 1.6 503 */ 504 static public final Locale ROOT = createConstant("", ""); 505 506 /** 507 * The key for the private use extension ('x'). 508 * 509 * @see #getExtension(char) 510 * @see Builder#setExtension(char, String) 511 * @since 1.7 512 */ 513 static public final char PRIVATE_USE_EXTENSION = 'x'; 514 515 /** 516 * The key for Unicode locale extension ('u'). 517 * 518 * @see #getExtension(char) 519 * @see Builder#setExtension(char, String) 520 * @since 1.7 521 */ 522 static public final char UNICODE_LOCALE_EXTENSION = 'u'; 523 524 /** serialization ID 525 */ 526 static final long serialVersionUID = 9149081749638150636L; 527 528 /** 529 * Display types for retrieving localized names from the name providers. 530 */ 531 private static final int DISPLAY_LANGUAGE = 0; 532 private static final int DISPLAY_COUNTRY = 1; 533 private static final int DISPLAY_VARIANT = 2; 534 private static final int DISPLAY_SCRIPT = 3; 535 536 /** 537 * Private constructor used by getInstance method 538 */ 539 private Locale(BaseLocale baseLocale, LocaleExtensions extensions) { 540 this.baseLocale = baseLocale; 541 this.localeExtensions = extensions; 542 } 543 544 /** 545 * Construct a locale from language, country and variant. 546 * This constructor normalizes the language value to lowercase and 547 * the country value to uppercase. 548 * <p> 549 * <b>Note:</b> 550 * <ul> 551 * <li>ISO 639 is not a stable standard; some of the language codes it defines 552 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 553 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 554 * API on Locale will return only the OLD codes. 555 * <li>For backward compatibility reasons, this constructor does not make 556 * any syntactic checks on the input. 557 * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially, 558 * see <a href="#special_cases_constructor">Special Cases</a> for more information. 559 * </ul> 560 * 561 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 562 * up to 8 characters in length. See the <code>Locale</code> class description about 563 * valid language values. 564 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 565 * See the <code>Locale</code> class description about valid country values. 566 * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>. 567 * See the <code>Locale</code> class description for the details. 568 * @exception NullPointerException thrown if any argument is null. 569 */ 570 public Locale(String language, String country, String variant) { 571 if (language== null || country == null || variant == null) { 572 throw new NullPointerException(); 573 } 574 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant); 575 localeExtensions = getCompatibilityExtensions(language, "", country, variant); 576 } 577 578 /** 579 * Construct a locale from language and country. 580 * This constructor normalizes the language value to lowercase and 581 * the country value to uppercase. 582 * <p> 583 * <b>Note:</b> 584 * <ul> 585 * <li>ISO 639 is not a stable standard; some of the language codes it defines 586 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 587 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 588 * API on Locale will return only the OLD codes. 589 * <li>For backward compatibility reasons, this constructor does not make 590 * any syntactic checks on the input. 591 * </ul> 592 * 593 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 594 * up to 8 characters in length. See the <code>Locale</code> class description about 595 * valid language values. 596 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 597 * See the <code>Locale</code> class description about valid country values. 598 * @exception NullPointerException thrown if either argument is null. 599 */ 600 public Locale(String language, String country) { 601 this(language, country, ""); 602 } 603 604 /** 605 * Construct a locale from a language code. 606 * This constructor normalizes the language value to lowercase. 607 * <p> 608 * <b>Note:</b> 609 * <ul> 610 * <li>ISO 639 is not a stable standard; some of the language codes it defines 611 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 612 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 613 * API on Locale will return only the OLD codes. 614 * <li>For backward compatibility reasons, this constructor does not make 615 * any syntactic checks on the input. 616 * </ul> 617 * 618 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 619 * up to 8 characters in length. See the <code>Locale</code> class description about 620 * valid language values. 621 * @exception NullPointerException thrown if argument is null. 622 * @since 1.4 623 */ 624 public Locale(String language) { 625 this(language, "", ""); 626 } 627 628 /** 629 * This method must be called only for creating the Locale.* 630 * constants due to making shortcuts. 631 */ 632 private static Locale createConstant(String lang, String country) { 633 BaseLocale base = BaseLocale.createInstance(lang, country); 634 return getInstance(base, null); 635 } 636 637 /** 638 * Returns a <code>Locale</code> constructed from the given 639 * <code>language</code>, <code>country</code> and 640 * <code>variant</code>. If the same <code>Locale</code> instance 641 * is available in the cache, then that instance is 642 * returned. Otherwise, a new <code>Locale</code> instance is 643 * created and cached. 644 * 645 * @param language lowercase 2 to 8 language code. 646 * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code. 647 * @param variant vendor and browser specific code. See class description. 648 * @return the <code>Locale</code> instance requested 649 * @exception NullPointerException if any argument is null. 650 */ 651 static Locale getInstance(String language, String country, String variant) { 652 return getInstance(language, "", country, variant, null); 653 } 654 655 static Locale getInstance(String language, String script, String country, 656 String variant, LocaleExtensions extensions) { 657 if (language== null || script == null || country == null || variant == null) { 658 throw new NullPointerException(); 659 } 660 661 if (extensions == null) { 662 extensions = getCompatibilityExtensions(language, script, country, variant); 663 } 664 665 BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant); 666 return getInstance(baseloc, extensions); 667 } 668 669 static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) { 670 LocaleKey key = new LocaleKey(baseloc, extensions); 671 return LOCALECACHE.get(key); 672 } 673 674 private static class Cache extends LocaleObjectCache<LocaleKey, Locale> { 675 private Cache() { 676 } 677 678 @Override 679 protected Locale createObject(LocaleKey key) { 680 return new Locale(key.base, key.exts); 681 } 682 } 683 684 private static final class LocaleKey { 685 private final BaseLocale base; 686 private final LocaleExtensions exts; 687 private final int hash; 688 689 private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) { 690 base = baseLocale; 691 exts = extensions; 692 693 // Calculate the hash value here because it's always used. 694 int h = base.hashCode(); 695 if (exts != null) { 696 h ^= exts.hashCode(); 697 } 698 hash = h; 699 } 700 701 @Override 702 public boolean equals(Object obj) { 703 if (this == obj) { 704 return true; 705 } 706 if (!(obj instanceof LocaleKey)) { 707 return false; 708 } 709 LocaleKey other = (LocaleKey)obj; 710 if (hash != other.hash || !base.equals(other.base)) { 711 return false; 712 } 713 if (exts == null) { 714 return other.exts == null; 715 } 716 return exts.equals(other.exts); 717 } 718 719 @Override 720 public int hashCode() { 721 return hash; 722 } 723 } 724 725 /** 726 * Gets the current value of the default locale for this instance 727 * of the Java Virtual Machine. 728 * <p> 729 * The Java Virtual Machine sets the default locale during startup 730 * based on the host environment. It is used by many locale-sensitive 731 * methods if no locale is explicitly specified. 732 * It can be changed using the 733 * {@link #setDefault(java.util.Locale) setDefault} method. 734 * 735 * @return the default locale for this instance of the Java Virtual Machine 736 */ 737 public static Locale getDefault() { 738 // do not synchronize this method - see 4071298 739 return defaultLocale; 740 } 741 742 /** 743 * Gets the current value of the default locale for the specified Category 744 * for this instance of the Java Virtual Machine. 745 * <p> 746 * The Java Virtual Machine sets the default locale during startup based 747 * on the host environment. It is used by many locale-sensitive methods 748 * if no locale is explicitly specified. It can be changed using the 749 * setDefault(Locale.Category, Locale) method. 750 * 751 * @param category - the specified category to get the default locale 752 * @throws NullPointerException - if category is null 753 * @return the default locale for the specified Category for this instance 754 * of the Java Virtual Machine 755 * @see #setDefault(Locale.Category, Locale) 756 * @since 1.7 757 */ 758 public static Locale getDefault(Locale.Category category) { 759 // do not synchronize this method - see 4071298 760 switch (category) { 761 case DISPLAY: 762 if (defaultDisplayLocale == null) { 763 synchronized(Locale.class) { 764 if (defaultDisplayLocale == null) { 765 defaultDisplayLocale = initDefault(category); 766 } 767 } 768 } 769 return defaultDisplayLocale; 770 case FORMAT: 771 if (defaultFormatLocale == null) { 772 synchronized(Locale.class) { 773 if (defaultFormatLocale == null) { 774 defaultFormatLocale = initDefault(category); 775 } 776 } 777 } 778 return defaultFormatLocale; 779 default: 780 assert false: "Unknown Category"; 781 } 782 return getDefault(); 783 } 784 785 private static Locale initDefault() { 786 String language, region, script, country, variant; 787 language = AccessController.doPrivileged( 788 new GetPropertyAction("user.language", "en")); 789 // for compatibility, check for old user.region property 790 region = AccessController.doPrivileged( 791 new GetPropertyAction("user.region")); 792 if (region != null) { 793 // region can be of form country, country_variant, or _variant 794 int i = region.indexOf('_'); 795 if (i >= 0) { 796 country = region.substring(0, i); 797 variant = region.substring(i + 1); 798 } else { 799 country = region; 800 variant = ""; 801 } 802 script = ""; 803 } else { 804 script = AccessController.doPrivileged( 805 new GetPropertyAction("user.script", "")); 806 country = AccessController.doPrivileged( 807 new GetPropertyAction("user.country", "")); 808 variant = AccessController.doPrivileged( 809 new GetPropertyAction("user.variant", "")); 810 } 811 812 return getInstance(language, script, country, variant, null); 813 } 814 815 private static Locale initDefault(Locale.Category category) { 816 return getInstance( 817 AccessController.doPrivileged( 818 new GetPropertyAction(category.languageKey, defaultLocale.getLanguage())), 819 AccessController.doPrivileged( 820 new GetPropertyAction(category.scriptKey, defaultLocale.getScript())), 821 AccessController.doPrivileged( 822 new GetPropertyAction(category.countryKey, defaultLocale.getCountry())), 823 AccessController.doPrivileged( 824 new GetPropertyAction(category.variantKey, defaultLocale.getVariant())), 825 null); 826 } 827 828 /** 829 * Sets the default locale for this instance of the Java Virtual Machine. 830 * This does not affect the host locale. 831 * <p> 832 * If there is a security manager, its <code>checkPermission</code> 833 * method is called with a <code>PropertyPermission("user.language", "write")</code> 834 * permission before the default locale is changed. 835 * <p> 836 * The Java Virtual Machine sets the default locale during startup 837 * based on the host environment. It is used by many locale-sensitive 838 * methods if no locale is explicitly specified. 839 * <p> 840 * Since changing the default locale may affect many different areas 841 * of functionality, this method should only be used if the caller 842 * is prepared to reinitialize locale-sensitive code running 843 * within the same Java Virtual Machine. 844 * <p> 845 * By setting the default locale with this method, all of the default 846 * locales for each Category are also set to the specified default locale. 847 * 848 * @throws SecurityException 849 * if a security manager exists and its 850 * <code>checkPermission</code> method doesn't allow the operation. 851 * @throws NullPointerException if <code>newLocale</code> is null 852 * @param newLocale the new default locale 853 * @see SecurityManager#checkPermission 854 * @see java.util.PropertyPermission 855 */ 856 public static synchronized void setDefault(Locale newLocale) { 857 setDefault(Category.DISPLAY, newLocale); 858 setDefault(Category.FORMAT, newLocale); 859 defaultLocale = newLocale; 860 } 861 862 /** 863 * Sets the default locale for the specified Category for this instance 864 * of the Java Virtual Machine. This does not affect the host locale. 865 * <p> 866 * If there is a security manager, its checkPermission method is called 867 * with a PropertyPermission("user.language", "write") permission before 868 * the default locale is changed. 869 * <p> 870 * The Java Virtual Machine sets the default locale during startup based 871 * on the host environment. It is used by many locale-sensitive methods 872 * if no locale is explicitly specified. 873 * <p> 874 * Since changing the default locale may affect many different areas of 875 * functionality, this method should only be used if the caller is 876 * prepared to reinitialize locale-sensitive code running within the 877 * same Java Virtual Machine. 878 * <p> 879 * 880 * @param category - the specified category to set the default locale 881 * @param newLocale - the new default locale 882 * @throws SecurityException - if a security manager exists and its 883 * checkPermission method doesn't allow the operation. 884 * @throws NullPointerException - if category and/or newLocale is null 885 * @see SecurityManager#checkPermission(java.security.Permission) 886 * @see PropertyPermission 887 * @see #getDefault(Locale.Category) 888 * @since 1.7 889 */ 890 public static synchronized void setDefault(Locale.Category category, 891 Locale newLocale) { 892 if (category == null) 893 throw new NullPointerException("Category cannot be NULL"); 894 if (newLocale == null) 895 throw new NullPointerException("Can't set default locale to NULL"); 896 897 SecurityManager sm = System.getSecurityManager(); 898 if (sm != null) sm.checkPermission(new PropertyPermission 899 ("user.language", "write")); 900 switch (category) { 901 case DISPLAY: 902 defaultDisplayLocale = newLocale; 903 break; 904 case FORMAT: 905 defaultFormatLocale = newLocale; 906 break; 907 default: 908 assert false: "Unknown Category"; 909 } 910 } 911 912 /** 913 * Returns an array of all installed locales. 914 * The returned array represents the union of locales supported 915 * by the Java runtime environment and by installed 916 * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider} 917 * implementations. It must contain at least a <code>Locale</code> 918 * instance equal to {@link java.util.Locale#US Locale.US}. 919 * 920 * @return An array of installed locales. 921 */ 922 public static Locale[] getAvailableLocales() { 923 return LocaleServiceProviderPool.getAllAvailableLocales(); 924 } 925 926 /** 927 * Returns a list of all 2-letter country codes defined in ISO 3166. 928 * Can be used to create Locales. 929 * <p> 930 * <b>Note:</b> The <code>Locale</code> class also supports other codes for 931 * country (region), such as 3-letter numeric UN M.49 area codes. 932 * Therefore, the list returned by this method does not contain ALL valid 933 * codes that can be used to create Locales. 934 */ 935 public static String[] getISOCountries() { 936 if (isoCountries == null) { 937 isoCountries = getISO2Table(LocaleISOData.isoCountryTable); 938 } 939 String[] result = new String[isoCountries.length]; 940 System.arraycopy(isoCountries, 0, result, 0, isoCountries.length); 941 return result; 942 } 943 944 /** 945 * Returns a list of all 2-letter language codes defined in ISO 639. 946 * Can be used to create Locales. 947 * <p> 948 * <b>Note:</b> 949 * <ul> 950 * <li>ISO 639 is not a stable standard— some languages' codes have changed. 951 * The list this function returns includes both the new and the old codes for the 952 * languages whose codes have changed. 953 * <li>The <code>Locale</code> class also supports language codes up to 954 * 8 characters in length. Therefore, the list returned by this method does 955 * not contain ALL valid codes that can be used to create Locales. 956 * </ul> 957 */ 958 public static String[] getISOLanguages() { 959 if (isoLanguages == null) { 960 isoLanguages = getISO2Table(LocaleISOData.isoLanguageTable); 961 } 962 String[] result = new String[isoLanguages.length]; 963 System.arraycopy(isoLanguages, 0, result, 0, isoLanguages.length); 964 return result; 965 } 966 967 private static String[] getISO2Table(String table) { 968 int len = table.length() / 5; 969 String[] isoTable = new String[len]; 970 for (int i = 0, j = 0; i < len; i++, j += 5) { 971 isoTable[i] = table.substring(j, j + 2); 972 } 973 return isoTable; 974 } 975 976 /** 977 * Returns the language code of this Locale. 978 * 979 * <p><b>Note:</b> ISO 639 is not a stable standard— some languages' codes have changed. 980 * Locale's constructor recognizes both the new and the old codes for the languages 981 * whose codes have changed, but this function always returns the old code. If you 982 * want to check for a specific language whose code has changed, don't do 983 * <pre> 984 * if (locale.getLanguage().equals("he")) // BAD! 985 * ... 986 * </pre> 987 * Instead, do 988 * <pre> 989 * if (locale.getLanguage().equals(new Locale("he").getLanguage())) 990 * ... 991 * </pre> 992 * @return The language code, or the empty string if none is defined. 993 * @see #getDisplayLanguage 994 */ 995 public String getLanguage() { 996 return baseLocale.getLanguage(); 997 } 998 999 /** 1000 * Returns the script for this locale, which should 1001 * either be the empty string or an ISO 15924 4-letter script 1002 * code. The first letter is uppercase and the rest are 1003 * lowercase, for example, 'Latn', 'Cyrl'. 1004 * 1005 * @return The script code, or the empty string if none is defined. 1006 * @see #getDisplayScript 1007 * @since 1.7 1008 */ 1009 public String getScript() { 1010 return baseLocale.getScript(); 1011 } 1012 1013 /** 1014 * Returns the country/region code for this locale, which should 1015 * either be the empty string, an uppercase ISO 3166 2-letter code, 1016 * or a UN M.49 3-digit code. 1017 * 1018 * @return The country/region code, or the empty string if none is defined. 1019 * @see #getDisplayCountry 1020 */ 1021 public String getCountry() { 1022 return baseLocale.getRegion(); 1023 } 1024 1025 /** 1026 * Returns the variant code for this locale. 1027 * 1028 * @return The variant code, or the empty string if none is defined. 1029 * @see #getDisplayVariant 1030 */ 1031 public String getVariant() { 1032 return baseLocale.getVariant(); 1033 } 1034 1035 /** 1036 * Returns {@code true} if this {@code Locale} has any <a href="#def_extensions"> 1037 * extensions</a>. 1038 * 1039 * @return {@code true} if this {@code Locale} has any extensions 1040 * @since 1.8 1041 */ 1042 public boolean hasExtensions() { 1043 return localeExtensions != null; 1044 } 1045 1046 /** 1047 * Returns a copy of this {@code Locale} with no <a href="#def_extensions"> 1048 * extensions</a>. If this {@code Locale} has no extensions, this {@code Locale} 1049 * is returned. 1050 * 1051 * @return a copy of this {@code Locale} with no extensions, or {@code this} 1052 * if {@code this} has no extensions 1053 * @since 1.8 1054 */ 1055 public Locale stripExtensions() { 1056 return hasExtensions() ? Locale.getInstance(baseLocale, null) : this; 1057 } 1058 1059 /** 1060 * Returns the extension (or private use) value associated with 1061 * the specified key, or null if there is no extension 1062 * associated with the key. To be well-formed, the key must be one 1063 * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so 1064 * for example 'z' and 'Z' represent the same extension. 1065 * 1066 * @param key the extension key 1067 * @return The extension, or null if this locale defines no 1068 * extension for the specified key. 1069 * @throws IllegalArgumentException if key is not well-formed 1070 * @see #PRIVATE_USE_EXTENSION 1071 * @see #UNICODE_LOCALE_EXTENSION 1072 * @since 1.7 1073 */ 1074 public String getExtension(char key) { 1075 if (!LocaleExtensions.isValidKey(key)) { 1076 throw new IllegalArgumentException("Ill-formed extension key: " + key); 1077 } 1078 return hasExtensions() ? localeExtensions.getExtensionValue(key) : null; 1079 } 1080 1081 /** 1082 * Returns the set of extension keys associated with this locale, or the 1083 * empty set if it has no extensions. The returned set is unmodifiable. 1084 * The keys will all be lower-case. 1085 * 1086 * @return The set of extension keys, or the empty set if this locale has 1087 * no extensions. 1088 * @since 1.7 1089 */ 1090 public Set<Character> getExtensionKeys() { 1091 if (!hasExtensions()) { 1092 return Collections.emptySet(); 1093 } 1094 return localeExtensions.getKeys(); 1095 } 1096 1097 /** 1098 * Returns the set of unicode locale attributes associated with 1099 * this locale, or the empty set if it has no attributes. The 1100 * returned set is unmodifiable. 1101 * 1102 * @return The set of attributes. 1103 * @since 1.7 1104 */ 1105 public Set<String> getUnicodeLocaleAttributes() { 1106 if (!hasExtensions()) { 1107 return Collections.emptySet(); 1108 } 1109 return localeExtensions.getUnicodeLocaleAttributes(); 1110 } 1111 1112 /** 1113 * Returns the Unicode locale type associated with the specified Unicode locale key 1114 * for this locale. Returns the empty string for keys that are defined with no type. 1115 * Returns null if the key is not defined. Keys are case-insensitive. The key must 1116 * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is 1117 * thrown. 1118 * 1119 * @param key the Unicode locale key 1120 * @return The Unicode locale type associated with the key, or null if the 1121 * locale does not define the key. 1122 * @throws IllegalArgumentException if the key is not well-formed 1123 * @throws NullPointerException if <code>key</code> is null 1124 * @since 1.7 1125 */ 1126 public String getUnicodeLocaleType(String key) { 1127 if (!isUnicodeExtensionKey(key)) { 1128 throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key); 1129 } 1130 return hasExtensions() ? localeExtensions.getUnicodeLocaleType(key) : null; 1131 } 1132 1133 /** 1134 * Returns the set of Unicode locale keys defined by this locale, or the empty set if 1135 * this locale has none. The returned set is immutable. Keys are all lower case. 1136 * 1137 * @return The set of Unicode locale keys, or the empty set if this locale has 1138 * no Unicode locale keywords. 1139 * @since 1.7 1140 */ 1141 public Set<String> getUnicodeLocaleKeys() { 1142 if (localeExtensions == null) { 1143 return Collections.emptySet(); 1144 } 1145 return localeExtensions.getUnicodeLocaleKeys(); 1146 } 1147 1148 /** 1149 * Package locale method returning the Locale's BaseLocale, 1150 * used by ResourceBundle 1151 * @return base locale of this Locale 1152 */ 1153 BaseLocale getBaseLocale() { 1154 return baseLocale; 1155 } 1156 1157 /** 1158 * Package private method returning the Locale's LocaleExtensions, 1159 * used by ResourceBundle. 1160 * @return locale exnteions of this Locale, 1161 * or {@code null} if no extensions are defined 1162 */ 1163 LocaleExtensions getLocaleExtensions() { 1164 return localeExtensions; 1165 } 1166 1167 /** 1168 * Returns a string representation of this <code>Locale</code> 1169 * object, consisting of language, country, variant, script, 1170 * and extensions as below: 1171 * <p><blockquote> 1172 * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions 1173 * </blockquote> 1174 * 1175 * Language is always lower case, country is always upper case, script is always title 1176 * case, and extensions are always lower case. Extensions and private use subtags 1177 * will be in canonical order as explained in {@link #toLanguageTag}. 1178 * 1179 * <p>When the locale has neither script nor extensions, the result is the same as in 1180 * Java 6 and prior. 1181 * 1182 * <p>If both the language and country fields are missing, this function will return 1183 * the empty string, even if the variant, script, or extensions field is present (you 1184 * can't have a locale with just a variant, the variant must accompany a well-formed 1185 * language or country code). 1186 * 1187 * <p>If script or extensions are present and variant is missing, no underscore is 1188 * added before the "#". 1189 * 1190 * <p>This behavior is designed to support debugging and to be compatible with 1191 * previous uses of <code>toString</code> that expected language, country, and variant 1192 * fields only. To represent a Locale as a String for interchange purposes, use 1193 * {@link #toLanguageTag}. 1194 * 1195 * <p>Examples: <ul><tt> 1196 * <li>en 1197 * <li>de_DE 1198 * <li>_GB 1199 * <li>en_US_WIN 1200 * <li>de__POSIX 1201 * <li>zh_CN_#Hans 1202 * <li>zh_TW_#Hant-x-java 1203 * <li>th_TH_TH_#u-nu-thai</tt></ul> 1204 * 1205 * @return A string representation of the Locale, for debugging. 1206 * @see #getDisplayName 1207 * @see #toLanguageTag 1208 */ 1209 @Override 1210 public final String toString() { 1211 boolean l = (baseLocale.getLanguage().length() != 0); 1212 boolean s = (baseLocale.getScript().length() != 0); 1213 boolean r = (baseLocale.getRegion().length() != 0); 1214 boolean v = (baseLocale.getVariant().length() != 0); 1215 boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0); 1216 1217 StringBuilder result = new StringBuilder(baseLocale.getLanguage()); 1218 if (r || (l && (v || s || e))) { 1219 result.append('_') 1220 .append(baseLocale.getRegion()); // This may just append '_' 1221 } 1222 if (v && (l || r)) { 1223 result.append('_') 1224 .append(baseLocale.getVariant()); 1225 } 1226 1227 if (s && (l || r)) { 1228 result.append("_#") 1229 .append(baseLocale.getScript()); 1230 } 1231 1232 if (e && (l || r)) { 1233 result.append('_'); 1234 if (!s) { 1235 result.append('#'); 1236 } 1237 result.append(localeExtensions.getID()); 1238 } 1239 1240 return result.toString(); 1241 } 1242 1243 /** 1244 * Returns a well-formed IETF BCP 47 language tag representing 1245 * this locale. 1246 * 1247 * <p>If this <code>Locale</code> has a language, country, or 1248 * variant that does not satisfy the IETF BCP 47 language tag 1249 * syntax requirements, this method handles these fields as 1250 * described below: 1251 * 1252 * <p><b>Language:</b> If language is empty, or not <a 1253 * href="#def_language" >well-formed</a> (for example "a" or 1254 * "e2"), it will be emitted as "und" (Undetermined). 1255 * 1256 * <p><b>Country:</b> If country is not <a 1257 * href="#def_region">well-formed</a> (for example "12" or "USA"), 1258 * it will be omitted. 1259 * 1260 * <p><b>Variant:</b> If variant <b>is</b> <a 1261 * href="#def_variant">well-formed</a>, each sub-segment 1262 * (delimited by '-' or '_') is emitted as a subtag. Otherwise: 1263 * <ul> 1264 * 1265 * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code> 1266 * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first 1267 * ill-formed sub-segment and all following will be appended to 1268 * the private use subtag. The first appended subtag will be 1269 * "lvariant", followed by the sub-segments in order, separated by 1270 * hyphen. For example, "x-lvariant-WIN", 1271 * "Oracle-x-lvariant-JDK-Standard-Edition". 1272 * 1273 * <li>if any sub-segment does not match 1274 * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated 1275 * and the problematic sub-segment and all following sub-segments 1276 * will be omitted. If the remainder is non-empty, it will be 1277 * emitted as a private use subtag as above (even if the remainder 1278 * turns out to be well-formed). For example, 1279 * "Solaris_isjustthecoolestthing" is emitted as 1280 * "x-lvariant-Solaris", not as "solaris".</li></ul> 1281 * 1282 * <p><b>Special Conversions:</b> Java supports some old locale 1283 * representations, including deprecated ISO language codes, 1284 * for compatibility. This method performs the following 1285 * conversions: 1286 * <ul> 1287 * 1288 * <li>Deprecated ISO language codes "iw", "ji", and "in" are 1289 * converted to "he", "yi", and "id", respectively. 1290 * 1291 * <li>A locale with language "no", country "NO", and variant 1292 * "NY", representing Norwegian Nynorsk (Norway), is converted 1293 * to a language tag "nn-NO".</li></ul> 1294 * 1295 * <p><b>Note:</b> Although the language tag created by this 1296 * method is well-formed (satisfies the syntax requirements 1297 * defined by the IETF BCP 47 specification), it is not 1298 * necessarily a valid BCP 47 language tag. For example, 1299 * <pre> 1300 * new Locale("xx", "YY").toLanguageTag();</pre> 1301 * 1302 * will return "xx-YY", but the language subtag "xx" and the 1303 * region subtag "YY" are invalid because they are not registered 1304 * in the IANA Language Subtag Registry. 1305 * 1306 * @return a BCP47 language tag representing the locale 1307 * @see #forLanguageTag(String) 1308 * @since 1.7 1309 */ 1310 public String toLanguageTag() { 1311 if (languageTag != null) { 1312 return languageTag; 1313 } 1314 1315 LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions); 1316 StringBuilder buf = new StringBuilder(); 1317 1318 String subtag = tag.getLanguage(); 1319 if (subtag.length() > 0) { 1320 buf.append(LanguageTag.canonicalizeLanguage(subtag)); 1321 } 1322 1323 subtag = tag.getScript(); 1324 if (subtag.length() > 0) { 1325 buf.append(LanguageTag.SEP); 1326 buf.append(LanguageTag.canonicalizeScript(subtag)); 1327 } 1328 1329 subtag = tag.getRegion(); 1330 if (subtag.length() > 0) { 1331 buf.append(LanguageTag.SEP); 1332 buf.append(LanguageTag.canonicalizeRegion(subtag)); 1333 } 1334 1335 List<String>subtags = tag.getVariants(); 1336 for (String s : subtags) { 1337 buf.append(LanguageTag.SEP); 1338 // preserve casing 1339 buf.append(s); 1340 } 1341 1342 subtags = tag.getExtensions(); 1343 for (String s : subtags) { 1344 buf.append(LanguageTag.SEP); 1345 buf.append(LanguageTag.canonicalizeExtension(s)); 1346 } 1347 1348 subtag = tag.getPrivateuse(); 1349 if (subtag.length() > 0) { 1350 if (buf.length() > 0) { 1351 buf.append(LanguageTag.SEP); 1352 } 1353 buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP); 1354 // preserve casing 1355 buf.append(subtag); 1356 } 1357 1358 String langTag = buf.toString(); 1359 synchronized (this) { 1360 if (languageTag == null) { 1361 languageTag = langTag; 1362 } 1363 } 1364 return languageTag; 1365 } 1366 1367 /** 1368 * Returns a locale for the specified IETF BCP 47 language tag string. 1369 * 1370 * <p>If the specified language tag contains any ill-formed subtags, 1371 * the first such subtag and all following subtags are ignored. Compare 1372 * to {@link Locale.Builder#setLanguageTag} which throws an exception 1373 * in this case. 1374 * 1375 * <p>The following <b>conversions</b> are performed:<ul> 1376 * 1377 * <li>The language code "und" is mapped to language "". 1378 * 1379 * <li>The language codes "he", "yi", and "id" are mapped to "iw", 1380 * "ji", and "in" respectively. (This is the same canonicalization 1381 * that's done in Locale's constructors.) 1382 * 1383 * <li>The portion of a private use subtag prefixed by "lvariant", 1384 * if any, is removed and appended to the variant field in the 1385 * result locale (without case normalization). If it is then 1386 * empty, the private use subtag is discarded: 1387 * 1388 * <pre> 1389 * Locale loc; 1390 * loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX"); 1391 * loc.getVariant(); // returns "POSIX" 1392 * loc.getExtension('x'); // returns null 1393 * 1394 * loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def"); 1395 * loc.getVariant(); // returns "POSIX_Abc_Def" 1396 * loc.getExtension('x'); // returns "urp" 1397 * </pre> 1398 * 1399 * <li>When the languageTag argument contains an extlang subtag, 1400 * the first such subtag is used as the language, and the primary 1401 * language subtag and other extlang subtags are ignored: 1402 * 1403 * <pre> 1404 * Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao" 1405 * Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US" 1406 * </pre> 1407 * 1408 * <li>Case is normalized except for variant tags, which are left 1409 * unchanged. Language is normalized to lower case, script to 1410 * title case, country to upper case, and extensions to lower 1411 * case. 1412 * 1413 * <li>If, after processing, the locale would exactly match either 1414 * ja_JP_JP or th_TH_TH with no extensions, the appropriate 1415 * extensions are added as though the constructor had been called: 1416 * 1417 * <pre> 1418 * Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag(); 1419 * // returns "ja-JP-u-ca-japanese-x-lvariant-JP" 1420 * Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag(); 1421 * // returns "th-TH-u-nu-thai-x-lvariant-TH" 1422 * <pre></ul> 1423 * 1424 * <p>This implements the 'Language-Tag' production of BCP47, and 1425 * so supports grandfathered (regular and irregular) as well as 1426 * private use language tags. Stand alone private use tags are 1427 * represented as empty language and extension 'x-whatever', 1428 * and grandfathered tags are converted to their canonical replacements 1429 * where they exist. 1430 * 1431 * <p>Grandfathered tags with canonical replacements are as follows: 1432 * 1433 * <table> 1434 * <tbody align="center"> 1435 * <tr><th>grandfathered tag</th><th> </th><th>modern replacement</th></tr> 1436 * <tr><td>art-lojban</td><td> </td><td>jbo</td></tr> 1437 * <tr><td>i-ami</td><td> </td><td>ami</td></tr> 1438 * <tr><td>i-bnn</td><td> </td><td>bnn</td></tr> 1439 * <tr><td>i-hak</td><td> </td><td>hak</td></tr> 1440 * <tr><td>i-klingon</td><td> </td><td>tlh</td></tr> 1441 * <tr><td>i-lux</td><td> </td><td>lb</td></tr> 1442 * <tr><td>i-navajo</td><td> </td><td>nv</td></tr> 1443 * <tr><td>i-pwn</td><td> </td><td>pwn</td></tr> 1444 * <tr><td>i-tao</td><td> </td><td>tao</td></tr> 1445 * <tr><td>i-tay</td><td> </td><td>tay</td></tr> 1446 * <tr><td>i-tsu</td><td> </td><td>tsu</td></tr> 1447 * <tr><td>no-bok</td><td> </td><td>nb</td></tr> 1448 * <tr><td>no-nyn</td><td> </td><td>nn</td></tr> 1449 * <tr><td>sgn-BE-FR</td><td> </td><td>sfb</td></tr> 1450 * <tr><td>sgn-BE-NL</td><td> </td><td>vgt</td></tr> 1451 * <tr><td>sgn-CH-DE</td><td> </td><td>sgg</td></tr> 1452 * <tr><td>zh-guoyu</td><td> </td><td>cmn</td></tr> 1453 * <tr><td>zh-hakka</td><td> </td><td>hak</td></tr> 1454 * <tr><td>zh-min-nan</td><td> </td><td>nan</td></tr> 1455 * <tr><td>zh-xiang</td><td> </td><td>hsn</td></tr> 1456 * </tbody> 1457 * </table> 1458 * 1459 * <p>Grandfathered tags with no modern replacement will be 1460 * converted as follows: 1461 * 1462 * <table> 1463 * <tbody align="center"> 1464 * <tr><th>grandfathered tag</th><th> </th><th>converts to</th></tr> 1465 * <tr><td>cel-gaulish</td><td> </td><td>xtg-x-cel-gaulish</td></tr> 1466 * <tr><td>en-GB-oed</td><td> </td><td>en-GB-x-oed</td></tr> 1467 * <tr><td>i-default</td><td> </td><td>en-x-i-default</td></tr> 1468 * <tr><td>i-enochian</td><td> </td><td>und-x-i-enochian</td></tr> 1469 * <tr><td>i-mingo</td><td> </td><td>see-x-i-mingo</td></tr> 1470 * <tr><td>zh-min</td><td> </td><td>nan-x-zh-min</td></tr> 1471 * </tbody> 1472 * </table> 1473 * 1474 * <p>For a list of all grandfathered tags, see the 1475 * IANA Language Subtag Registry (search for "Type: grandfathered"). 1476 * 1477 * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code> 1478 * and <code>forLanguageTag</code> will round-trip. 1479 * 1480 * @param languageTag the language tag 1481 * @return The locale that best represents the language tag. 1482 * @throws NullPointerException if <code>languageTag</code> is <code>null</code> 1483 * @see #toLanguageTag() 1484 * @see java.util.Locale.Builder#setLanguageTag(String) 1485 * @since 1.7 1486 */ 1487 public static Locale forLanguageTag(String languageTag) { 1488 LanguageTag tag = LanguageTag.parse(languageTag, null); 1489 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 1490 bldr.setLanguageTag(tag); 1491 BaseLocale base = bldr.getBaseLocale(); 1492 LocaleExtensions exts = bldr.getLocaleExtensions(); 1493 if (exts == null && base.getVariant().length() > 0) { 1494 exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(), 1495 base.getRegion(), base.getVariant()); 1496 } 1497 return getInstance(base, exts); 1498 } 1499 1500 /** 1501 * Returns a three-letter abbreviation of this locale's language. 1502 * If the language matches an ISO 639-1 two-letter code, the 1503 * corresponding ISO 639-2/T three-letter lowercase code is 1504 * returned. The ISO 639-2 language codes can be found on-line, 1505 * see "Codes for the Representation of Names of Languages Part 2: 1506 * Alpha-3 Code". If the locale specifies a three-letter 1507 * language, the language is returned as is. If the locale does 1508 * not specify a language the empty string is returned. 1509 * 1510 * @return A three-letter abbreviation of this locale's language. 1511 * @exception MissingResourceException Throws MissingResourceException if 1512 * three-letter language abbreviation is not available for this locale. 1513 */ 1514 public String getISO3Language() throws MissingResourceException { 1515 String lang = baseLocale.getLanguage(); 1516 if (lang.length() == 3) { 1517 return lang; 1518 } 1519 1520 String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable); 1521 if (language3 == null) { 1522 throw new MissingResourceException("Couldn't find 3-letter language code for " 1523 + lang, "FormatData_" + toString(), "ShortLanguage"); 1524 } 1525 return language3; 1526 } 1527 1528 /** 1529 * Returns a three-letter abbreviation for this locale's country. 1530 * If the country matches an ISO 3166-1 alpha-2 code, the 1531 * corresponding ISO 3166-1 alpha-3 uppercase code is returned. 1532 * If the locale doesn't specify a country, this will be the empty 1533 * string. 1534 * 1535 * <p>The ISO 3166-1 codes can be found on-line. 1536 * 1537 * @return A three-letter abbreviation of this locale's country. 1538 * @exception MissingResourceException Throws MissingResourceException if the 1539 * three-letter country abbreviation is not available for this locale. 1540 */ 1541 public String getISO3Country() throws MissingResourceException { 1542 String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable); 1543 if (country3 == null) { 1544 throw new MissingResourceException("Couldn't find 3-letter country code for " 1545 + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry"); 1546 } 1547 return country3; 1548 } 1549 1550 private static String getISO3Code(String iso2Code, String table) { 1551 int codeLength = iso2Code.length(); 1552 if (codeLength == 0) { 1553 return ""; 1554 } 1555 1556 int tableLength = table.length(); 1557 int index = tableLength; 1558 if (codeLength == 2) { 1559 char c1 = iso2Code.charAt(0); 1560 char c2 = iso2Code.charAt(1); 1561 for (index = 0; index < tableLength; index += 5) { 1562 if (table.charAt(index) == c1 1563 && table.charAt(index + 1) == c2) { 1564 break; 1565 } 1566 } 1567 } 1568 return index < tableLength ? table.substring(index + 2, index + 5) : null; 1569 } 1570 1571 /** 1572 * Returns a name for the locale's language that is appropriate for display to the 1573 * user. 1574 * If possible, the name returned will be localized for the default locale. 1575 * For example, if the locale is fr_FR and the default locale 1576 * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and 1577 * the default locale is fr_FR, getDisplayLanguage() will return "anglais". 1578 * If the name returned cannot be localized for the default locale, 1579 * (say, we don't have a Japanese name for Croatian), 1580 * this function falls back on the English name, and uses the ISO code as a last-resort 1581 * value. If the locale doesn't specify a language, this function returns the empty string. 1582 */ 1583 public final String getDisplayLanguage() { 1584 return getDisplayLanguage(getDefault(Category.DISPLAY)); 1585 } 1586 1587 /** 1588 * Returns a name for the locale's language that is appropriate for display to the 1589 * user. 1590 * If possible, the name returned will be localized according to inLocale. 1591 * For example, if the locale is fr_FR and inLocale 1592 * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and 1593 * inLocale is fr_FR, getDisplayLanguage() will return "anglais". 1594 * If the name returned cannot be localized according to inLocale, 1595 * (say, we don't have a Japanese name for Croatian), 1596 * this function falls back on the English name, and finally 1597 * on the ISO code as a last-resort value. If the locale doesn't specify a language, 1598 * this function returns the empty string. 1599 * 1600 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1601 */ 1602 public String getDisplayLanguage(Locale inLocale) { 1603 return getDisplayString(baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE); 1604 } 1605 1606 /** 1607 * Returns a name for the the locale's script that is appropriate for display to 1608 * the user. If possible, the name will be localized for the default locale. Returns 1609 * the empty string if this locale doesn't specify a script code. 1610 * 1611 * @return the display name of the script code for the current default locale 1612 * @since 1.7 1613 */ 1614 public String getDisplayScript() { 1615 return getDisplayScript(getDefault(Category.DISPLAY)); 1616 } 1617 1618 /** 1619 * Returns a name for the locale's script that is appropriate 1620 * for display to the user. If possible, the name will be 1621 * localized for the given locale. Returns the empty string if 1622 * this locale doesn't specify a script code. 1623 * 1624 * @return the display name of the script code for the current default locale 1625 * @throws NullPointerException if <code>inLocale</code> is <code>null</code> 1626 * @since 1.7 1627 */ 1628 public String getDisplayScript(Locale inLocale) { 1629 return getDisplayString(baseLocale.getScript(), inLocale, DISPLAY_SCRIPT); 1630 } 1631 1632 /** 1633 * Returns a name for the locale's country that is appropriate for display to the 1634 * user. 1635 * If possible, the name returned will be localized for the default locale. 1636 * For example, if the locale is fr_FR and the default locale 1637 * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and 1638 * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis". 1639 * If the name returned cannot be localized for the default locale, 1640 * (say, we don't have a Japanese name for Croatia), 1641 * this function falls back on the English name, and uses the ISO code as a last-resort 1642 * value. If the locale doesn't specify a country, this function returns the empty string. 1643 */ 1644 public final String getDisplayCountry() { 1645 return getDisplayCountry(getDefault(Category.DISPLAY)); 1646 } 1647 1648 /** 1649 * Returns a name for the locale's country that is appropriate for display to the 1650 * user. 1651 * If possible, the name returned will be localized according to inLocale. 1652 * For example, if the locale is fr_FR and inLocale 1653 * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and 1654 * inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis". 1655 * If the name returned cannot be localized according to inLocale. 1656 * (say, we don't have a Japanese name for Croatia), 1657 * this function falls back on the English name, and finally 1658 * on the ISO code as a last-resort value. If the locale doesn't specify a country, 1659 * this function returns the empty string. 1660 * 1661 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1662 */ 1663 public String getDisplayCountry(Locale inLocale) { 1664 return getDisplayString(baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY); 1665 } 1666 1667 private String getDisplayString(String code, Locale inLocale, int type) { 1668 if (code.length() == 0) { 1669 return ""; 1670 } 1671 1672 if (inLocale == null) { 1673 throw new NullPointerException(); 1674 } 1675 1676 LocaleServiceProviderPool pool = 1677 LocaleServiceProviderPool.getPool(LocaleNameProvider.class); 1678 String key = (type == DISPLAY_VARIANT ? "%%"+code : code); 1679 String result = pool.getLocalizedObject( 1680 LocaleNameGetter.INSTANCE, 1681 inLocale, key, type, code); 1682 if (result != null) { 1683 return result; 1684 } 1685 1686 return code; 1687 } 1688 1689 /** 1690 * Returns a name for the locale's variant code that is appropriate for display to the 1691 * user. If possible, the name will be localized for the default locale. If the locale 1692 * doesn't specify a variant code, this function returns the empty string. 1693 */ 1694 public final String getDisplayVariant() { 1695 return getDisplayVariant(getDefault(Category.DISPLAY)); 1696 } 1697 1698 /** 1699 * Returns a name for the locale's variant code that is appropriate for display to the 1700 * user. If possible, the name will be localized for inLocale. If the locale 1701 * doesn't specify a variant code, this function returns the empty string. 1702 * 1703 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1704 */ 1705 public String getDisplayVariant(Locale inLocale) { 1706 if (baseLocale.getVariant().length() == 0) 1707 return ""; 1708 1709 OpenListResourceBundle bundle = LocaleProviderAdapter.forJRE().getLocaleData().getLocaleNames(inLocale); 1710 1711 String names[] = getDisplayVariantArray(bundle, inLocale); 1712 1713 // Get the localized patterns for formatting a list, and use 1714 // them to format the list. 1715 String listPattern = null; 1716 String listCompositionPattern = null; 1717 try { 1718 listPattern = bundle.getString("ListPattern"); 1719 listCompositionPattern = bundle.getString("ListCompositionPattern"); 1720 } catch (MissingResourceException e) { 1721 } 1722 return formatList(names, listPattern, listCompositionPattern); 1723 } 1724 1725 /** 1726 * Returns a name for the locale that is appropriate for display to the 1727 * user. This will be the values returned by getDisplayLanguage(), 1728 * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled 1729 * into a single string. The the non-empty values are used in order, 1730 * with the second and subsequent names in parentheses. For example: 1731 * <blockquote> 1732 * language (script, country, variant)<br> 1733 * language (country)<br> 1734 * language (variant)<br> 1735 * script (country)<br> 1736 * country<br> 1737 * </blockquote> 1738 * depending on which fields are specified in the locale. If the 1739 * language, sacript, country, and variant fields are all empty, 1740 * this function returns the empty string. 1741 */ 1742 public final String getDisplayName() { 1743 return getDisplayName(getDefault(Category.DISPLAY)); 1744 } 1745 1746 /** 1747 * Returns a name for the locale that is appropriate for display 1748 * to the user. This will be the values returned by 1749 * getDisplayLanguage(), getDisplayScript(),getDisplayCountry(), 1750 * and getDisplayVariant() assembled into a single string. 1751 * The non-empty values are used in order, 1752 * with the second and subsequent names in parentheses. For example: 1753 * <blockquote> 1754 * language (script, country, variant)<br> 1755 * language (country)<br> 1756 * language (variant)<br> 1757 * script (country)<br> 1758 * country<br> 1759 * </blockquote> 1760 * depending on which fields are specified in the locale. If the 1761 * language, script, country, and variant fields are all empty, 1762 * this function returns the empty string. 1763 * 1764 * @throws NullPointerException if <code>inLocale</code> is <code>null</code> 1765 */ 1766 public String getDisplayName(Locale inLocale) { 1767 OpenListResourceBundle bundle = LocaleProviderAdapter.forJRE().getLocaleData().getLocaleNames(inLocale); 1768 1769 String languageName = getDisplayLanguage(inLocale); 1770 String scriptName = getDisplayScript(inLocale); 1771 String countryName = getDisplayCountry(inLocale); 1772 String[] variantNames = getDisplayVariantArray(bundle, inLocale); 1773 1774 // Get the localized patterns for formatting a display name. 1775 String displayNamePattern = null; 1776 String listPattern = null; 1777 String listCompositionPattern = null; 1778 try { 1779 displayNamePattern = bundle.getString("DisplayNamePattern"); 1780 listPattern = bundle.getString("ListPattern"); 1781 listCompositionPattern = bundle.getString("ListCompositionPattern"); 1782 } catch (MissingResourceException e) { 1783 } 1784 1785 // The display name consists of a main name, followed by qualifiers. 1786 // Typically, the format is "MainName (Qualifier, Qualifier)" but this 1787 // depends on what pattern is stored in the display locale. 1788 String mainName = null; 1789 String[] qualifierNames = null; 1790 1791 // The main name is the language, or if there is no language, the script, 1792 // then if no script, the country. If there is no language/script/country 1793 // (an anomalous situation) then the display name is simply the variant's 1794 // display name. 1795 if (languageName.length() == 0 && scriptName.length() == 0 && countryName.length() == 0) { 1796 if (variantNames.length == 0) { 1797 return ""; 1798 } else { 1799 return formatList(variantNames, listPattern, listCompositionPattern); 1800 } 1801 } 1802 ArrayList<String> names = new ArrayList<>(4); 1803 if (languageName.length() != 0) { 1804 names.add(languageName); 1805 } 1806 if (scriptName.length() != 0) { 1807 names.add(scriptName); 1808 } 1809 if (countryName.length() != 0) { 1810 names.add(countryName); 1811 } 1812 if (variantNames.length != 0) { 1813 names.addAll(Arrays.asList(variantNames)); 1814 } 1815 1816 // The first one in the main name 1817 mainName = names.get(0); 1818 1819 // Others are qualifiers 1820 int numNames = names.size(); 1821 qualifierNames = (numNames > 1) ? 1822 names.subList(1, numNames).toArray(new String[numNames - 1]) : new String[0]; 1823 1824 // Create an array whose first element is the number of remaining 1825 // elements. This serves as a selector into a ChoiceFormat pattern from 1826 // the resource. The second and third elements are the main name and 1827 // the qualifier; if there are no qualifiers, the third element is 1828 // unused by the format pattern. 1829 Object[] displayNames = { 1830 new Integer(qualifierNames.length != 0 ? 2 : 1), 1831 mainName, 1832 // We could also just call formatList() and have it handle the empty 1833 // list case, but this is more efficient, and we want it to be 1834 // efficient since all the language-only locales will not have any 1835 // qualifiers. 1836 qualifierNames.length != 0 ? formatList(qualifierNames, listPattern, listCompositionPattern) : null 1837 }; 1838 1839 if (displayNamePattern != null) { 1840 return new MessageFormat(displayNamePattern).format(displayNames); 1841 } 1842 else { 1843 // If we cannot get the message format pattern, then we use a simple 1844 // hard-coded pattern. This should not occur in practice unless the 1845 // installation is missing some core files (FormatData etc.). 1846 StringBuilder result = new StringBuilder(); 1847 result.append((String)displayNames[1]); 1848 if (displayNames.length > 2) { 1849 result.append(" ("); 1850 result.append((String)displayNames[2]); 1851 result.append(')'); 1852 } 1853 return result.toString(); 1854 } 1855 } 1856 1857 /** 1858 * Overrides Cloneable. 1859 */ 1860 @Override 1861 public Object clone() 1862 { 1863 try { 1864 Locale that = (Locale)super.clone(); 1865 return that; 1866 } catch (CloneNotSupportedException e) { 1867 throw new InternalError(e); 1868 } 1869 } 1870 1871 /** 1872 * Override hashCode. 1873 * Since Locales are often used in hashtables, caches the value 1874 * for speed. 1875 */ 1876 @Override 1877 public int hashCode() { 1878 int hc = hashCodeValue; 1879 if (hc == 0) { 1880 hc = baseLocale.hashCode(); 1881 if (localeExtensions != null) { 1882 hc ^= localeExtensions.hashCode(); 1883 } 1884 hashCodeValue = hc; 1885 } 1886 return hc; 1887 } 1888 1889 // Overrides 1890 1891 /** 1892 * Returns true if this Locale is equal to another object. A Locale is 1893 * deemed equal to another Locale with identical language, script, country, 1894 * variant and extensions, and unequal to all other objects. 1895 * 1896 * @return true if this Locale is equal to the specified object. 1897 */ 1898 @Override 1899 public boolean equals(Object obj) { 1900 if (this == obj) // quick check 1901 return true; 1902 if (!(obj instanceof Locale)) 1903 return false; 1904 BaseLocale otherBase = ((Locale)obj).baseLocale; 1905 if (!baseLocale.equals(otherBase)) { 1906 return false; 1907 } 1908 if (localeExtensions == null) { 1909 return ((Locale)obj).localeExtensions == null; 1910 } 1911 return localeExtensions.equals(((Locale)obj).localeExtensions); 1912 } 1913 1914 // ================= privates ===================================== 1915 1916 private transient BaseLocale baseLocale; 1917 private transient LocaleExtensions localeExtensions; 1918 1919 /** 1920 * Calculated hashcode 1921 */ 1922 private transient volatile int hashCodeValue = 0; 1923 1924 private volatile static Locale defaultLocale = initDefault(); 1925 private volatile static Locale defaultDisplayLocale = null; 1926 private volatile static Locale defaultFormatLocale = null; 1927 1928 private transient volatile String languageTag; 1929 1930 /** 1931 * Return an array of the display names of the variant. 1932 * @param bundle the ResourceBundle to use to get the display names 1933 * @return an array of display names, possible of zero length. 1934 */ 1935 private String[] getDisplayVariantArray(OpenListResourceBundle bundle, Locale inLocale) { 1936 // Split the variant name into tokens separated by '_'. 1937 StringTokenizer tokenizer = new StringTokenizer(baseLocale.getVariant(), "_"); 1938 String[] names = new String[tokenizer.countTokens()]; 1939 1940 // For each variant token, lookup the display name. If 1941 // not found, use the variant name itself. 1942 for (int i=0; i<names.length; ++i) { 1943 names[i] = getDisplayString(tokenizer.nextToken(), 1944 inLocale, DISPLAY_VARIANT); 1945 } 1946 1947 return names; 1948 } 1949 1950 /** 1951 * Format a list using given pattern strings. 1952 * If either of the patterns is null, then a the list is 1953 * formatted by concatenation with the delimiter ','. 1954 * @param stringList the list of strings to be formatted. 1955 * @param listPattern should create a MessageFormat taking 0-3 arguments 1956 * and formatting them into a list. 1957 * @param listCompositionPattern should take 2 arguments 1958 * and is used by composeList. 1959 * @return a string representing the list. 1960 */ 1961 private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) { 1962 // If we have no list patterns, compose the list in a simple, 1963 // non-localized way. 1964 if (listPattern == null || listCompositionPattern == null) { 1965 StringBuilder result = new StringBuilder(); 1966 for (int i = 0; i < stringList.length; ++i) { 1967 if (i > 0) { 1968 result.append(','); 1969 } 1970 result.append(stringList[i]); 1971 } 1972 return result.toString(); 1973 } 1974 1975 // Compose the list down to three elements if necessary 1976 if (stringList.length > 3) { 1977 MessageFormat format = new MessageFormat(listCompositionPattern); 1978 stringList = composeList(format, stringList); 1979 } 1980 1981 // Rebuild the argument list with the list length as the first element 1982 Object[] args = new Object[stringList.length + 1]; 1983 System.arraycopy(stringList, 0, args, 1, stringList.length); 1984 args[0] = new Integer(stringList.length); 1985 1986 // Format it using the pattern in the resource 1987 MessageFormat format = new MessageFormat(listPattern); 1988 return format.format(args); 1989 } 1990 1991 /** 1992 * Given a list of strings, return a list shortened to three elements. 1993 * Shorten it by applying the given format to the first two elements 1994 * recursively. 1995 * @param format a format which takes two arguments 1996 * @param list a list of strings 1997 * @return if the list is three elements or shorter, the same list; 1998 * otherwise, a new list of three elements. 1999 */ 2000 private static String[] composeList(MessageFormat format, String[] list) { 2001 if (list.length <= 3) return list; 2002 2003 // Use the given format to compose the first two elements into one 2004 String[] listItems = { list[0], list[1] }; 2005 String newItem = format.format(listItems); 2006 2007 // Form a new list one element shorter 2008 String[] newList = new String[list.length-1]; 2009 System.arraycopy(list, 2, newList, 1, newList.length-1); 2010 newList[0] = newItem; 2011 2012 // Recurse 2013 return composeList(format, newList); 2014 } 2015 2016 // Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to 2017 // avoid its class loading. 2018 private static boolean isUnicodeExtensionKey(String s) { 2019 // 2alphanum 2020 return (s.length() == 2) && LocaleUtils.isAlphaNumericString(s); 2021 } 2022 2023 /** 2024 * @serialField language String 2025 * language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>) 2026 * @serialField country String 2027 * country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>) 2028 * @serialField variant String 2029 * variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>) 2030 * @serialField hashcode int 2031 * deprecated, for forward compatibility only 2032 * @serialField script String 2033 * script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>) 2034 * @serialField extensions String 2035 * canonical representation of extensions, that is, 2036 * BCP47 extensions in alphabetical order followed by 2037 * BCP47 private use subtags, all in lower case letters 2038 * separated by HYPHEN-MINUS characters. 2039 * (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>, 2040 * <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>) 2041 */ 2042 private static final ObjectStreamField[] serialPersistentFields = { 2043 new ObjectStreamField("language", String.class), 2044 new ObjectStreamField("country", String.class), 2045 new ObjectStreamField("variant", String.class), 2046 new ObjectStreamField("hashcode", int.class), 2047 new ObjectStreamField("script", String.class), 2048 new ObjectStreamField("extensions", String.class), 2049 }; 2050 2051 /** 2052 * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>. 2053 * @param out the <code>ObjectOutputStream</code> to write 2054 * @throws IOException 2055 * @since 1.7 2056 */ 2057 private void writeObject(ObjectOutputStream out) throws IOException { 2058 ObjectOutputStream.PutField fields = out.putFields(); 2059 fields.put("language", baseLocale.getLanguage()); 2060 fields.put("script", baseLocale.getScript()); 2061 fields.put("country", baseLocale.getRegion()); 2062 fields.put("variant", baseLocale.getVariant()); 2063 fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID()); 2064 fields.put("hashcode", -1); // place holder just for backward support 2065 out.writeFields(); 2066 } 2067 2068 /** 2069 * Deserializes this <code>Locale</code>. 2070 * @param in the <code>ObjectInputStream</code> to read 2071 * @throws IOException 2072 * @throws ClassNotFoundException 2073 * @throws IllformdLocaleException 2074 * @since 1.7 2075 */ 2076 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 2077 ObjectInputStream.GetField fields = in.readFields(); 2078 String language = (String)fields.get("language", ""); 2079 String script = (String)fields.get("script", ""); 2080 String country = (String)fields.get("country", ""); 2081 String variant = (String)fields.get("variant", ""); 2082 String extStr = (String)fields.get("extensions", ""); 2083 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant); 2084 if (extStr.length() > 0) { 2085 try { 2086 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 2087 bldr.setExtensions(extStr); 2088 localeExtensions = bldr.getLocaleExtensions(); 2089 } catch (LocaleSyntaxException e) { 2090 throw new IllformedLocaleException(e.getMessage()); 2091 } 2092 } else { 2093 localeExtensions = null; 2094 } 2095 } 2096 2097 /** 2098 * Returns a cached <code>Locale</code> instance equivalent to 2099 * the deserialized <code>Locale</code>. When serialized 2100 * language, country and variant fields read from the object data stream 2101 * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions 2102 * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code> 2103 * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script 2104 * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a> 2105 * for more information. 2106 * 2107 * @return an instance of <code>Locale</code> equivalent to 2108 * the deserialized <code>Locale</code>. 2109 * @throws java.io.ObjectStreamException 2110 */ 2111 private Object readResolve() throws java.io.ObjectStreamException { 2112 return getInstance(baseLocale.getLanguage(), baseLocale.getScript(), 2113 baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions); 2114 } 2115 2116 private static volatile String[] isoLanguages = null; 2117 2118 private static volatile String[] isoCountries = null; 2119 2120 private static String convertOldISOCodes(String language) { 2121 // we accept both the old and the new ISO codes for the languages whose ISO 2122 // codes have changed, but we always store the OLD code, for backward compatibility 2123 language = LocaleUtils.toLowerString(language).intern(); 2124 if (language == "he") { 2125 return "iw"; 2126 } else if (language == "yi") { 2127 return "ji"; 2128 } else if (language == "id") { 2129 return "in"; 2130 } else { 2131 return language; 2132 } 2133 } 2134 2135 private static LocaleExtensions getCompatibilityExtensions(String language, 2136 String script, 2137 String country, 2138 String variant) { 2139 LocaleExtensions extensions = null; 2140 // Special cases for backward compatibility support 2141 if (LocaleUtils.caseIgnoreMatch(language, "ja") 2142 && script.length() == 0 2143 && LocaleUtils.caseIgnoreMatch(country, "jp") 2144 && "JP".equals(variant)) { 2145 // ja_JP_JP -> u-ca-japanese (calendar = japanese) 2146 extensions = LocaleExtensions.CALENDAR_JAPANESE; 2147 } else if (LocaleUtils.caseIgnoreMatch(language, "th") 2148 && script.length() == 0 2149 && LocaleUtils.caseIgnoreMatch(country, "th") 2150 && "TH".equals(variant)) { 2151 // th_TH_TH -> u-nu-thai (numbersystem = thai) 2152 extensions = LocaleExtensions.NUMBER_THAI; 2153 } 2154 return extensions; 2155 } 2156 2157 /** 2158 * Obtains a localized locale names from a LocaleNameProvider 2159 * implementation. 2160 */ 2161 private static class LocaleNameGetter 2162 implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> { 2163 private static final LocaleNameGetter INSTANCE = new LocaleNameGetter(); 2164 2165 @Override 2166 public String getObject(LocaleNameProvider localeNameProvider, 2167 Locale locale, 2168 String key, 2169 Object... params) { 2170 assert params.length == 2; 2171 int type = (Integer)params[0]; 2172 String code = (String)params[1]; 2173 2174 switch(type) { 2175 case DISPLAY_LANGUAGE: 2176 return localeNameProvider.getDisplayLanguage(code, locale); 2177 case DISPLAY_COUNTRY: 2178 return localeNameProvider.getDisplayCountry(code, locale); 2179 case DISPLAY_VARIANT: 2180 return localeNameProvider.getDisplayVariant(code, locale); 2181 case DISPLAY_SCRIPT: 2182 return localeNameProvider.getDisplayScript(code, locale); 2183 default: 2184 assert false; // shouldn't happen 2185 } 2186 2187 return null; 2188 } 2189 } 2190 2191 /** 2192 * Enum for locale categories. These locale categories are used to get/set 2193 * the default locale for the specific functionality represented by the 2194 * category. 2195 * 2196 * @see #getDefault(Locale.Category) 2197 * @see #setDefault(Locale.Category, Locale) 2198 * @since 1.7 2199 */ 2200 public enum Category { 2201 2202 /** 2203 * Category used to represent the default locale for 2204 * displaying user interfaces. 2205 */ 2206 DISPLAY("user.language.display", 2207 "user.script.display", 2208 "user.country.display", 2209 "user.variant.display"), 2210 2211 /** 2212 * Category used to represent the default locale for 2213 * formatting dates, numbers, and/or currencies. 2214 */ 2215 FORMAT("user.language.format", 2216 "user.script.format", 2217 "user.country.format", 2218 "user.variant.format"); 2219 2220 Category(String languageKey, String scriptKey, String countryKey, String variantKey) { 2221 this.languageKey = languageKey; 2222 this.scriptKey = scriptKey; 2223 this.countryKey = countryKey; 2224 this.variantKey = variantKey; 2225 } 2226 2227 final String languageKey; 2228 final String scriptKey; 2229 final String countryKey; 2230 final String variantKey; 2231 } 2232 2233 /** 2234 * <code>Builder</code> is used to build instances of <code>Locale</code> 2235 * from values configured by the setters. Unlike the <code>Locale</code> 2236 * constructors, the <code>Builder</code> checks if a value configured by a 2237 * setter satisfies the syntax requirements defined by the <code>Locale</code> 2238 * class. A <code>Locale</code> object created by a <code>Builder</code> is 2239 * well-formed and can be transformed to a well-formed IETF BCP 47 language tag 2240 * without losing information. 2241 * 2242 * <p><b>Note:</b> The <code>Locale</code> class does not provide any 2243 * syntactic restrictions on variant, while BCP 47 requires each variant 2244 * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3 2245 * alphanumerics. The method <code>setVariant</code> throws 2246 * <code>IllformedLocaleException</code> for a variant that does not satisfy 2247 * this restriction. If it is necessary to support such a variant, use a 2248 * Locale constructor. However, keep in mind that a <code>Locale</code> 2249 * object created this way might lose the variant information when 2250 * transformed to a BCP 47 language tag. 2251 * 2252 * <p>The following example shows how to create a <code>Locale</code> object 2253 * with the <code>Builder</code>. 2254 * <blockquote> 2255 * <pre> 2256 * Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build(); 2257 * </pre> 2258 * </blockquote> 2259 * 2260 * <p>Builders can be reused; <code>clear()</code> resets all 2261 * fields to their default values. 2262 * 2263 * @see Locale#forLanguageTag 2264 * @since 1.7 2265 */ 2266 public static final class Builder { 2267 private final InternalLocaleBuilder localeBuilder; 2268 2269 /** 2270 * Constructs an empty Builder. The default value of all 2271 * fields, extensions, and private use information is the 2272 * empty string. 2273 */ 2274 public Builder() { 2275 localeBuilder = new InternalLocaleBuilder(); 2276 } 2277 2278 /** 2279 * Resets the <code>Builder</code> to match the provided 2280 * <code>locale</code>. Existing state is discarded. 2281 * 2282 * <p>All fields of the locale must be well-formed, see {@link Locale}. 2283 * 2284 * <p>Locales with any ill-formed fields cause 2285 * <code>IllformedLocaleException</code> to be thrown, except for the 2286 * following three cases which are accepted for compatibility 2287 * reasons:<ul> 2288 * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese" 2289 * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai" 2290 * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul> 2291 * 2292 * @param locale the locale 2293 * @return This builder. 2294 * @throws IllformedLocaleException if <code>locale</code> has 2295 * any ill-formed fields. 2296 * @throws NullPointerException if <code>locale</code> is null. 2297 */ 2298 public Builder setLocale(Locale locale) { 2299 try { 2300 localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions); 2301 } catch (LocaleSyntaxException e) { 2302 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2303 } 2304 return this; 2305 } 2306 2307 /** 2308 * Resets the Builder to match the provided IETF BCP 47 2309 * language tag. Discards the existing state. Null and the 2310 * empty string cause the builder to be reset, like {@link 2311 * #clear}. Grandfathered tags (see {@link 2312 * Locale#forLanguageTag}) are converted to their canonical 2313 * form before being processed. Otherwise, the language tag 2314 * must be well-formed (see {@link Locale}) or an exception is 2315 * thrown (unlike <code>Locale.forLanguageTag</code>, which 2316 * just discards ill-formed and following portions of the 2317 * tag). 2318 * 2319 * @param languageTag the language tag 2320 * @return This builder. 2321 * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed 2322 * @see Locale#forLanguageTag(String) 2323 */ 2324 public Builder setLanguageTag(String languageTag) { 2325 ParseStatus sts = new ParseStatus(); 2326 LanguageTag tag = LanguageTag.parse(languageTag, sts); 2327 if (sts.isError()) { 2328 throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex()); 2329 } 2330 localeBuilder.setLanguageTag(tag); 2331 return this; 2332 } 2333 2334 /** 2335 * Sets the language. If <code>language</code> is the empty string or 2336 * null, the language in this <code>Builder</code> is removed. Otherwise, 2337 * the language must be <a href="./Locale.html#def_language">well-formed</a> 2338 * or an exception is thrown. 2339 * 2340 * <p>The typical language value is a two or three-letter language 2341 * code as defined in ISO639. 2342 * 2343 * @param language the language 2344 * @return This builder. 2345 * @throws IllformedLocaleException if <code>language</code> is ill-formed 2346 */ 2347 public Builder setLanguage(String language) { 2348 try { 2349 localeBuilder.setLanguage(language); 2350 } catch (LocaleSyntaxException e) { 2351 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2352 } 2353 return this; 2354 } 2355 2356 /** 2357 * Sets the script. If <code>script</code> is null or the empty string, 2358 * the script in this <code>Builder</code> is removed. 2359 * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an 2360 * exception is thrown. 2361 * 2362 * <p>The typical script value is a four-letter script code as defined by ISO 15924. 2363 * 2364 * @param script the script 2365 * @return This builder. 2366 * @throws IllformedLocaleException if <code>script</code> is ill-formed 2367 */ 2368 public Builder setScript(String script) { 2369 try { 2370 localeBuilder.setScript(script); 2371 } catch (LocaleSyntaxException e) { 2372 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2373 } 2374 return this; 2375 } 2376 2377 /** 2378 * Sets the region. If region is null or the empty string, the region 2379 * in this <code>Builder</code> is removed. Otherwise, 2380 * the region must be <a href="./Locale.html#def_region">well-formed</a> or an 2381 * exception is thrown. 2382 * 2383 * <p>The typical region value is a two-letter ISO 3166 code or a 2384 * three-digit UN M.49 area code. 2385 * 2386 * <p>The country value in the <code>Locale</code> created by the 2387 * <code>Builder</code> is always normalized to upper case. 2388 * 2389 * @param region the region 2390 * @return This builder. 2391 * @throws IllformedLocaleException if <code>region</code> is ill-formed 2392 */ 2393 public Builder setRegion(String region) { 2394 try { 2395 localeBuilder.setRegion(region); 2396 } catch (LocaleSyntaxException e) { 2397 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2398 } 2399 return this; 2400 } 2401 2402 /** 2403 * Sets the variant. If variant is null or the empty string, the 2404 * variant in this <code>Builder</code> is removed. Otherwise, it 2405 * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a> 2406 * subtags, or an exception is thrown. 2407 * 2408 * <p><b>Note:</b> This method checks if <code>variant</code> 2409 * satisfies the IETF BCP 47 variant subtag's syntax requirements, 2410 * and normalizes the value to lowercase letters. However, 2411 * the <code>Locale</code> class does not impose any syntactic 2412 * restriction on variant, and the variant value in 2413 * <code>Locale</code> is case sensitive. To set such a variant, 2414 * use a Locale constructor. 2415 * 2416 * @param variant the variant 2417 * @return This builder. 2418 * @throws IllformedLocaleException if <code>variant</code> is ill-formed 2419 */ 2420 public Builder setVariant(String variant) { 2421 try { 2422 localeBuilder.setVariant(variant); 2423 } catch (LocaleSyntaxException e) { 2424 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2425 } 2426 return this; 2427 } 2428 2429 /** 2430 * Sets the extension for the given key. If the value is null or the 2431 * empty string, the extension is removed. Otherwise, the extension 2432 * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception 2433 * is thrown. 2434 * 2435 * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION 2436 * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension. 2437 * Setting a value for this key replaces any existing Unicode locale key/type 2438 * pairs with those defined in the extension. 2439 * 2440 * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION 2441 * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be 2442 * well-formed, the value for this key needs only to have subtags of one to 2443 * eight alphanumeric characters, not two to eight as in the general case. 2444 * 2445 * @param key the extension key 2446 * @param value the extension value 2447 * @return This builder. 2448 * @throws IllformedLocaleException if <code>key</code> is illegal 2449 * or <code>value</code> is ill-formed 2450 * @see #setUnicodeLocaleKeyword(String, String) 2451 */ 2452 public Builder setExtension(char key, String value) { 2453 try { 2454 localeBuilder.setExtension(key, value); 2455 } catch (LocaleSyntaxException e) { 2456 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2457 } 2458 return this; 2459 } 2460 2461 /** 2462 * Sets the Unicode locale keyword type for the given key. If the type 2463 * is null, the Unicode keyword is removed. Otherwise, the key must be 2464 * non-null and both key and type must be <a 2465 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2466 * is thrown. 2467 * 2468 * <p>Keys and types are converted to lower case. 2469 * 2470 * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension} 2471 * replaces all Unicode locale keywords with those defined in the 2472 * extension. 2473 * 2474 * @param key the Unicode locale key 2475 * @param type the Unicode locale type 2476 * @return This builder. 2477 * @throws IllformedLocaleException if <code>key</code> or <code>type</code> 2478 * is ill-formed 2479 * @throws NullPointerException if <code>key</code> is null 2480 * @see #setExtension(char, String) 2481 */ 2482 public Builder setUnicodeLocaleKeyword(String key, String type) { 2483 try { 2484 localeBuilder.setUnicodeLocaleKeyword(key, type); 2485 } catch (LocaleSyntaxException e) { 2486 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2487 } 2488 return this; 2489 } 2490 2491 /** 2492 * Adds a unicode locale attribute, if not already present, otherwise 2493 * has no effect. The attribute must not be null and must be <a 2494 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2495 * is thrown. 2496 * 2497 * @param attribute the attribute 2498 * @return This builder. 2499 * @throws NullPointerException if <code>attribute</code> is null 2500 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2501 * @see #setExtension(char, String) 2502 */ 2503 public Builder addUnicodeLocaleAttribute(String attribute) { 2504 try { 2505 localeBuilder.addUnicodeLocaleAttribute(attribute); 2506 } catch (LocaleSyntaxException e) { 2507 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2508 } 2509 return this; 2510 } 2511 2512 /** 2513 * Removes a unicode locale attribute, if present, otherwise has no 2514 * effect. The attribute must not be null and must be <a 2515 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2516 * is thrown. 2517 * 2518 * <p>Attribute comparision for removal is case-insensitive. 2519 * 2520 * @param attribute the attribute 2521 * @return This builder. 2522 * @throws NullPointerException if <code>attribute</code> is null 2523 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2524 * @see #setExtension(char, String) 2525 */ 2526 public Builder removeUnicodeLocaleAttribute(String attribute) { 2527 try { 2528 localeBuilder.removeUnicodeLocaleAttribute(attribute); 2529 } catch (LocaleSyntaxException e) { 2530 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2531 } 2532 return this; 2533 } 2534 2535 /** 2536 * Resets the builder to its initial, empty state. 2537 * 2538 * @return This builder. 2539 */ 2540 public Builder clear() { 2541 localeBuilder.clear(); 2542 return this; 2543 } 2544 2545 /** 2546 * Resets the extensions to their initial, empty state. 2547 * Language, script, region and variant are unchanged. 2548 * 2549 * @return This builder. 2550 * @see #setExtension(char, String) 2551 */ 2552 public Builder clearExtensions() { 2553 localeBuilder.clearExtensions(); 2554 return this; 2555 } 2556 2557 /** 2558 * Returns an instance of <code>Locale</code> created from the fields set 2559 * on this builder. 2560 * 2561 * <p>This applies the conversions listed in {@link Locale#forLanguageTag} 2562 * when constructing a Locale. (Grandfathered tags are handled in 2563 * {@link #setLanguageTag}.) 2564 * 2565 * @return A Locale. 2566 */ 2567 public Locale build() { 2568 BaseLocale baseloc = localeBuilder.getBaseLocale(); 2569 LocaleExtensions extensions = localeBuilder.getLocaleExtensions(); 2570 if (extensions == null && baseloc.getVariant().length() > 0) { 2571 extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(), 2572 baseloc.getRegion(), baseloc.getVariant()); 2573 } 2574 return Locale.getInstance(baseloc, extensions); 2575 } 2576 } 2577 }