1 /* 2 * Copyright (c) 1996, 2019, 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.text.MessageFormat; 49 import java.util.concurrent.ConcurrentHashMap; 50 import java.util.spi.LocaleNameProvider; 51 import java.util.stream.Collectors; 52 53 import sun.security.action.GetPropertyAction; 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.LocaleMatcher; 59 import sun.util.locale.LocaleObjectCache; 60 import sun.util.locale.LocaleSyntaxException; 61 import sun.util.locale.LocaleUtils; 62 import sun.util.locale.ParseStatus; 63 import sun.util.locale.provider.LocaleProviderAdapter; 64 import sun.util.locale.provider.LocaleResources; 65 import sun.util.locale.provider.LocaleServiceProviderPool; 66 import sun.util.locale.provider.TimeZoneNameUtility; 67 68 /** 69 * A <code>Locale</code> object represents a specific geographical, political, 70 * or cultural region. An operation that requires a <code>Locale</code> to perform 71 * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code> 72 * to tailor information for the user. For example, displaying a number 73 * is a locale-sensitive operation— the number should be formatted 74 * according to the customs and conventions of the user's native country, 75 * region, or culture. 76 * 77 * <p> The {@code Locale} class implements IETF BCP 47 which is composed of 78 * <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 "Matching of Language 79 * Tags"</a> and <a href="http://tools.ietf.org/html/rfc5646">RFC 5646 "Tags 80 * for Identifying Languages"</a> with support for the LDML (UTS#35, "Unicode 81 * Locale Data Markup Language") BCP 47-compatible extensions for locale data 82 * exchange. 83 * 84 * <p> A <code>Locale</code> object logically consists of the fields 85 * described below. 86 * 87 * <dl> 88 * <dt><a id="def_language"><b>language</b></a></dt> 89 * 90 * <dd>ISO 639 alpha-2 or alpha-3 language code, or registered 91 * language subtags up to 8 alpha letters (for future enhancements). 92 * When a language has both an alpha-2 code and an alpha-3 code, the 93 * alpha-2 code must be used. You can find a full list of valid 94 * language codes in the IANA Language Subtag Registry (search for 95 * "Type: language"). The language field is case insensitive, but 96 * <code>Locale</code> always canonicalizes to lower case.</dd> 97 * 98 * <dd>Well-formed language values have the form 99 * <code>[a-zA-Z]{2,8}</code>. Note that this is not the full 100 * BCP47 language production, since it excludes extlang. They are 101 * not needed since modern three-letter language codes replace 102 * them.</dd> 103 * 104 * <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd> 105 * 106 * <dt><a id="def_script"><b>script</b></a></dt> 107 * 108 * <dd>ISO 15924 alpha-4 script code. You can find a full list of 109 * valid script codes in the IANA Language Subtag Registry (search 110 * for "Type: script"). The script field is case insensitive, but 111 * <code>Locale</code> always canonicalizes to title case (the first 112 * letter is upper case and the rest of the letters are lower 113 * case).</dd> 114 * 115 * <dd>Well-formed script values have the form 116 * <code>[a-zA-Z]{4}</code></dd> 117 * 118 * <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd> 119 * 120 * <dt><a id="def_region"><b>country (region)</b></a></dt> 121 * 122 * <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. 123 * You can find a full list of valid country and region codes in the 124 * IANA Language Subtag Registry (search for "Type: region"). The 125 * country (region) field is case insensitive, but 126 * <code>Locale</code> always canonicalizes to upper case.</dd> 127 * 128 * <dd>Well-formed country/region values have 129 * the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd> 130 * 131 * <dd>Example: "US" (United States), "FR" (France), "029" 132 * (Caribbean)</dd> 133 * 134 * <dt><a id="def_variant"><b>variant</b></a></dt> 135 * 136 * <dd>Any arbitrary value used to indicate a variation of a 137 * <code>Locale</code>. Where there are two or more variant values 138 * each indicating its own semantics, these values should be ordered 139 * by importance, with most important first, separated by 140 * underscore('_'). The variant field is case sensitive.</dd> 141 * 142 * <dd>Note: IETF BCP 47 places syntactic restrictions on variant 143 * subtags. Also BCP 47 subtags are strictly used to indicate 144 * additional variations that define a language or its dialects that 145 * are not covered by any combinations of language, script and 146 * region subtags. You can find a full list of valid variant codes 147 * in the IANA Language Subtag Registry (search for "Type: variant"). 148 * 149 * <p>However, the variant field in <code>Locale</code> has 150 * historically been used for any kind of variation, not just 151 * language variations. For example, some supported variants 152 * available in Java SE Runtime Environments indicate alternative 153 * cultural behaviors such as calendar type or number script. In 154 * BCP 47 this kind of information, which does not identify the 155 * language, is supported by extension subtags or private use 156 * subtags.</dd> 157 * 158 * <dd>Well-formed variant values have the form <code>SUBTAG 159 * (('_'|'-') SUBTAG)*</code> where <code>SUBTAG = 160 * [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only 161 * uses hyphen ('-') as a delimiter, this is more lenient).</dd> 162 * 163 * <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd> 164 * 165 * <dt><a id="def_extensions"><b>extensions</b></a></dt> 166 * 167 * <dd>A map from single character keys to string values, indicating 168 * extensions apart from language identification. The extensions in 169 * <code>Locale</code> implement the semantics and syntax of BCP 47 170 * extension subtags and private use subtags. The extensions are 171 * case insensitive, but <code>Locale</code> canonicalizes all 172 * extension keys and values to lower case. Note that extensions 173 * cannot have empty values.</dd> 174 * 175 * <dd>Well-formed keys are single characters from the set 176 * <code>[0-9a-zA-Z]</code>. Well-formed values have the form 177 * <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x' 178 * <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys 179 * <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows 180 * single-character subtags).</dd> 181 * 182 * <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar), 183 * key="x"/value="java-1-7"</dd> 184 * </dl> 185 * 186 * <b>Note:</b> Although BCP 47 requires field values to be registered 187 * in the IANA Language Subtag Registry, the <code>Locale</code> class 188 * does not provide any validation features. The <code>Builder</code> 189 * only checks if an individual field satisfies the syntactic 190 * requirement (is well-formed), but does not validate the value 191 * itself. See {@link Builder} for details. 192 * 193 * <h2><a id="def_locale_extension">Unicode locale/language extension</a></h2> 194 * 195 * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional 196 * attributes and keywords to override or refine the default behavior 197 * associated with a locale. A keyword is represented by a pair of 198 * key and type. For example, "nu-thai" indicates that Thai local 199 * digits (value:"thai") should be used for formatting numbers 200 * (key:"nu"). 201 * 202 * <p>The keywords are mapped to a BCP 47 extension value using the 203 * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}). The above 204 * example, "nu-thai", becomes the extension "u-nu-thai". 205 * 206 * <p>Thus, when a <code>Locale</code> object contains Unicode locale 207 * attributes and keywords, 208 * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a 209 * String representing this information, for example, "nu-thai". The 210 * <code>Locale</code> class also provides {@link 211 * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and 212 * {@link #getUnicodeLocaleType} which allow you to access Unicode 213 * locale attributes and key/type pairs directly. When represented as 214 * a string, the Unicode Locale Extension lists attributes 215 * alphabetically, followed by key/type sequences with keys listed 216 * alphabetically (the order of subtags comprising a key's type is 217 * fixed when the type is defined) 218 * 219 * <p>A well-formed locale key has the form 220 * <code>[0-9a-zA-Z]{2}</code>. A well-formed locale type has the 221 * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it 222 * can be empty, or a series of subtags 3-8 alphanums in length). A 223 * well-formed locale attribute has the form 224 * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same 225 * form as a locale type subtag). 226 * 227 * <p>The Unicode locale extension specifies optional behavior in 228 * locale-sensitive services. Although the LDML specification defines 229 * various keys and values, actual locale-sensitive service 230 * implementations in a Java Runtime Environment might not support any 231 * particular Unicode locale attributes or key/type pairs. 232 * 233 * <h3>Creating a Locale</h3> 234 * 235 * <p>There are several different ways to create a <code>Locale</code> 236 * object. 237 * 238 * <h4>Builder</h4> 239 * 240 * <p>Using {@link Builder} you can construct a <code>Locale</code> object 241 * that conforms to BCP 47 syntax. 242 * 243 * <h4>Constructors</h4> 244 * 245 * <p>The <code>Locale</code> class provides three constructors: 246 * <blockquote> 247 * <pre> 248 * {@link #Locale(String language)} 249 * {@link #Locale(String language, String country)} 250 * {@link #Locale(String language, String country, String variant)} 251 * </pre> 252 * </blockquote> 253 * These constructors allow you to create a <code>Locale</code> object 254 * with language, country and variant, but you cannot specify 255 * script or extensions. 256 * 257 * <h4>Factory Methods</h4> 258 * 259 * <p>The method {@link #forLanguageTag} creates a <code>Locale</code> 260 * object for a well-formed BCP 47 language tag. 261 * 262 * <h4>Locale Constants</h4> 263 * 264 * <p>The <code>Locale</code> class provides a number of convenient constants 265 * that you can use to create <code>Locale</code> objects for commonly used 266 * locales. For example, the following creates a <code>Locale</code> object 267 * for the United States: 268 * <blockquote> 269 * <pre> 270 * Locale.US 271 * </pre> 272 * </blockquote> 273 * 274 * <h3><a id="LocaleMatching">Locale Matching</a></h3> 275 * 276 * <p>If an application or a system is internationalized and provides localized 277 * resources for multiple locales, it sometimes needs to find one or more 278 * locales (or language tags) which meet each user's specific preferences. Note 279 * that a term "language tag" is used interchangeably with "locale" in this 280 * locale matching documentation. 281 * 282 * <p>In order to do matching a user's preferred locales to a set of language 283 * tags, <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 Matching of 284 * Language Tags</a> defines two mechanisms: filtering and lookup. 285 * <em>Filtering</em> is used to get all matching locales, whereas 286 * <em>lookup</em> is to choose the best matching locale. 287 * Matching is done case-insensitively. These matching mechanisms are described 288 * in the following sections. 289 * 290 * <p>A user's preference is called a <em>Language Priority List</em> and is 291 * expressed as a list of language ranges. There are syntactically two types of 292 * language ranges: basic and extended. See 293 * {@link Locale.LanguageRange Locale.LanguageRange} for details. 294 * 295 * <h4>Filtering</h4> 296 * 297 * <p>The filtering operation returns all matching language tags. It is defined 298 * in RFC 4647 as follows: 299 * "In filtering, each language range represents the least specific language 300 * tag (that is, the language tag with fewest number of subtags) that is an 301 * acceptable match. All of the language tags in the matching set of tags will 302 * have an equal or greater number of subtags than the language range. Every 303 * non-wildcard subtag in the language range will appear in every one of the 304 * matching language tags." 305 * 306 * <p>There are two types of filtering: filtering for basic language ranges 307 * (called "basic filtering") and filtering for extended language ranges 308 * (called "extended filtering"). They may return different results by what 309 * kind of language ranges are included in the given Language Priority List. 310 * {@link Locale.FilteringMode} is a parameter to specify how filtering should 311 * be done. 312 * 313 * <h4>Lookup</h4> 314 * 315 * <p>The lookup operation returns the best matching language tags. It is 316 * defined in RFC 4647 as follows: 317 * "By contrast with filtering, each language range represents the most 318 * specific tag that is an acceptable match. The first matching tag found, 319 * according to the user's priority, is considered the closest match and is the 320 * item returned." 321 * 322 * <p>For example, if a Language Priority List consists of two language ranges, 323 * {@code "zh-Hant-TW"} and {@code "en-US"}, in prioritized order, lookup 324 * method progressively searches the language tags below in order to find the 325 * best matching language tag. 326 * <blockquote> 327 * <pre> 328 * 1. zh-Hant-TW 329 * 2. zh-Hant 330 * 3. zh 331 * 4. en-US 332 * 5. en 333 * </pre> 334 * </blockquote> 335 * If there is a language tag which matches completely to a language range 336 * above, the language tag is returned. 337 * 338 * <p>{@code "*"} is the special language range, and it is ignored in lookup. 339 * 340 * <p>If multiple language tags match as a result of the subtag {@code '*'} 341 * included in a language range, the first matching language tag returned by 342 * an {@link Iterator} over a {@link Collection} of language tags is treated as 343 * the best matching one. 344 * 345 * <h3>Use of Locale</h3> 346 * 347 * <p>Once you've created a <code>Locale</code> you can query it for information 348 * about itself. Use <code>getCountry</code> to get the country (or region) 349 * code and <code>getLanguage</code> to get the language code. 350 * You can use <code>getDisplayCountry</code> to get the 351 * name of the country suitable for displaying to the user. Similarly, 352 * you can use <code>getDisplayLanguage</code> to get the name of 353 * the language suitable for displaying to the user. Interestingly, 354 * the <code>getDisplayXXX</code> methods are themselves locale-sensitive 355 * and have two versions: one that uses the default 356 * {@link Locale.Category#DISPLAY DISPLAY} locale and one 357 * that uses the locale specified as an argument. 358 * 359 * <p>The Java Platform provides a number of classes that perform locale-sensitive 360 * operations. For example, the <code>NumberFormat</code> class formats 361 * numbers, currency, and percentages in a locale-sensitive manner. Classes 362 * such as <code>NumberFormat</code> have several convenience methods 363 * for creating a default object of that type. For example, the 364 * <code>NumberFormat</code> class provides these three convenience methods 365 * for creating a default <code>NumberFormat</code> object: 366 * <blockquote> 367 * <pre> 368 * NumberFormat.getInstance() 369 * NumberFormat.getCurrencyInstance() 370 * NumberFormat.getPercentInstance() 371 * </pre> 372 * </blockquote> 373 * Each of these methods has two variants; one with an explicit locale 374 * and one without; the latter uses the default 375 * {@link Locale.Category#FORMAT FORMAT} locale: 376 * <blockquote> 377 * <pre> 378 * NumberFormat.getInstance(myLocale) 379 * NumberFormat.getCurrencyInstance(myLocale) 380 * NumberFormat.getPercentInstance(myLocale) 381 * </pre> 382 * </blockquote> 383 * A <code>Locale</code> is the mechanism for identifying the kind of object 384 * (<code>NumberFormat</code>) that you would like to get. The locale is 385 * <STRONG>just</STRONG> a mechanism for identifying objects, 386 * <STRONG>not</STRONG> a container for the objects themselves. 387 * 388 * <h3>Compatibility</h3> 389 * 390 * <p>In order to maintain compatibility with existing usage, Locale's 391 * constructors retain their behavior prior to the Java Runtime 392 * Environment version 1.7. The same is largely true for the 393 * <code>toString</code> method. Thus Locale objects can continue to 394 * be used as they were. In particular, clients who parse the output 395 * of toString into language, country, and variant fields can continue 396 * to do so (although this is strongly discouraged), although the 397 * variant field will have additional information in it if script or 398 * extensions are present. 399 * 400 * <p>In addition, BCP 47 imposes syntax restrictions that are not 401 * imposed by Locale's constructors. This means that conversions 402 * between some Locales and BCP 47 language tags cannot be made without 403 * losing information. Thus <code>toLanguageTag</code> cannot 404 * represent the state of locales whose language, country, or variant 405 * do not conform to BCP 47. 406 * 407 * <p>Because of these issues, it is recommended that clients migrate 408 * away from constructing non-conforming locales and use the 409 * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead. 410 * Clients desiring a string representation of the complete locale can 411 * then always rely on <code>toLanguageTag</code> for this purpose. 412 * 413 * <h4><a id="special_cases_constructor">Special cases</a></h4> 414 * 415 * <p>For compatibility reasons, two 416 * non-conforming locales are treated as special cases. These are 417 * <b>{@code ja_JP_JP}</b> and <b>{@code th_TH_TH}</b>. These are ill-formed 418 * in BCP 47 since the variants are too short. To ease migration to BCP 47, 419 * these are treated specially during construction. These two cases (and only 420 * these) cause a constructor to generate an extension, all other values behave 421 * exactly as they did prior to Java 7. 422 * 423 * <p>Java has used {@code ja_JP_JP} to represent Japanese as used in 424 * Japan together with the Japanese Imperial calendar. This is now 425 * representable using a Unicode locale extension, by specifying the 426 * Unicode locale key {@code ca} (for "calendar") and type 427 * {@code japanese}. When the Locale constructor is called with the 428 * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is 429 * automatically added. 430 * 431 * <p>Java has used {@code th_TH_TH} to represent Thai as used in 432 * Thailand together with Thai digits. This is also now representable using 433 * a Unicode locale extension, by specifying the Unicode locale key 434 * {@code nu} (for "number") and value {@code thai}. When the Locale 435 * constructor is called with the arguments "th", "TH", "TH", the 436 * extension "u-nu-thai" is automatically added. 437 * 438 * <h4>Serialization</h4> 439 * 440 * <p>During serialization, writeObject writes all fields to the output 441 * stream, including extensions. 442 * 443 * <p>During deserialization, readResolve adds extensions as described 444 * in <a href="#special_cases_constructor">Special Cases</a>, only 445 * for the two cases th_TH_TH and ja_JP_JP. 446 * 447 * <h4>Legacy language codes</h4> 448 * 449 * <p>Locale's constructor has always converted three language codes to 450 * their earlier, obsoleted forms: {@code he} maps to {@code iw}, 451 * {@code yi} maps to {@code ji}, and {@code id} maps to 452 * {@code in}. This continues to be the case, in order to not break 453 * backwards compatibility. 454 * 455 * <p>The APIs added in 1.7 map between the old and new language codes, 456 * maintaining the old codes internal to Locale (so that 457 * <code>getLanguage</code> and <code>toString</code> reflect the old 458 * code), but using the new codes in the BCP 47 language tag APIs (so 459 * that <code>toLanguageTag</code> reflects the new one). This 460 * preserves the equivalence between Locales no matter which code or 461 * API is used to construct them. Java's default resource bundle 462 * lookup mechanism also implements this mapping, so that resources 463 * can be named using either convention, see {@link ResourceBundle.Control}. 464 * 465 * <h4>Three-letter language/country(region) codes</h4> 466 * 467 * <p>The Locale constructors have always specified that the language 468 * and the country param be two characters in length, although in 469 * practice they have accepted any length. The specification has now 470 * been relaxed to allow language codes of two to eight characters and 471 * country (region) codes of two to three characters, and in 472 * particular, three-letter language codes and three-digit region 473 * codes as specified in the IANA Language Subtag Registry. For 474 * compatibility, the implementation still does not impose a length 475 * constraint. 476 * 477 * @see Builder 478 * @see ResourceBundle 479 * @see java.text.Format 480 * @see java.text.NumberFormat 481 * @see java.text.Collator 482 * @author Mark Davis 483 * @since 1.1 484 */ 485 public final class Locale implements Cloneable, Serializable { 486 487 /** Useful constant for language. 488 */ 489 public static final Locale ENGLISH; 490 491 /** Useful constant for language. 492 */ 493 public static final Locale FRENCH; 494 495 /** Useful constant for language. 496 */ 497 public static final Locale GERMAN; 498 499 /** Useful constant for language. 500 */ 501 public static final Locale ITALIAN; 502 503 /** Useful constant for language. 504 */ 505 public static final Locale JAPANESE; 506 507 /** Useful constant for language. 508 */ 509 public static final Locale KOREAN; 510 511 /** Useful constant for language. 512 */ 513 public static final Locale CHINESE; 514 515 /** Useful constant for language. 516 */ 517 public static final Locale SIMPLIFIED_CHINESE; 518 519 /** Useful constant for language. 520 */ 521 public static final Locale TRADITIONAL_CHINESE; 522 523 /** Useful constant for country. 524 */ 525 public static final Locale FRANCE; 526 527 /** Useful constant for country. 528 */ 529 public static final Locale GERMANY; 530 531 /** Useful constant for country. 532 */ 533 public static final Locale ITALY; 534 535 /** Useful constant for country. 536 */ 537 public static final Locale JAPAN; 538 539 /** Useful constant for country. 540 */ 541 public static final Locale KOREA; 542 543 /** Useful constant for country. 544 */ 545 public static final Locale UK; 546 547 /** Useful constant for country. 548 */ 549 public static final Locale US; 550 551 /** Useful constant for country. 552 */ 553 public static final Locale CANADA; 554 555 /** Useful constant for country. 556 */ 557 public static final Locale CANADA_FRENCH; 558 559 /** 560 * Useful constant for the root locale. The root locale is the locale whose 561 * language, country, and variant are empty ("") strings. This is regarded 562 * as the base locale of all locales, and is used as the language/country 563 * neutral locale for the locale sensitive operations. 564 * 565 * @since 1.6 566 */ 567 public static final Locale ROOT; 568 569 private static final Map<BaseLocale, Locale> CONSTANT_LOCALES = new HashMap<>(); 570 571 static { 572 ENGLISH = createConstant(BaseLocale.ENGLISH); 573 FRENCH = createConstant(BaseLocale.FRENCH); 574 GERMAN = createConstant(BaseLocale.GERMAN); 575 ITALIAN = createConstant(BaseLocale.ITALIAN); 576 JAPANESE = createConstant(BaseLocale.JAPANESE); 577 KOREAN = createConstant(BaseLocale.KOREAN); 578 CHINESE = createConstant(BaseLocale.CHINESE); 579 SIMPLIFIED_CHINESE = createConstant(BaseLocale.SIMPLIFIED_CHINESE); 580 TRADITIONAL_CHINESE = createConstant(BaseLocale.TRADITIONAL_CHINESE); 581 FRANCE = createConstant(BaseLocale.FRANCE); 582 GERMANY = createConstant(BaseLocale.GERMANY); 583 ITALY = createConstant(BaseLocale.ITALY); 584 JAPAN = createConstant(BaseLocale.JAPAN); 585 KOREA = createConstant(BaseLocale.KOREA); 586 UK = createConstant(BaseLocale.UK); 587 US = createConstant(BaseLocale.US); 588 CANADA = createConstant(BaseLocale.CANADA); 589 CANADA_FRENCH = createConstant(BaseLocale.CANADA_FRENCH); 590 ROOT = createConstant(BaseLocale.ROOT); 591 } 592 593 /** Useful constant for country. 594 */ 595 public static final Locale CHINA = SIMPLIFIED_CHINESE; 596 597 /** Useful constant for country. 598 */ 599 public static final Locale PRC = SIMPLIFIED_CHINESE; 600 601 /** Useful constant for country. 602 */ 603 public static final Locale TAIWAN = TRADITIONAL_CHINESE; 604 605 /** 606 * This method must be called only for creating the Locale.* 607 * constants due to making shortcuts. 608 */ 609 private static Locale createConstant(byte baseType) { 610 BaseLocale base = BaseLocale.constantBaseLocales[baseType]; 611 Locale locale = new Locale(base, null); 612 CONSTANT_LOCALES.put(base, locale); 613 return locale; 614 } 615 616 /** 617 * The key for the private use extension ('x'). 618 * 619 * @see #getExtension(char) 620 * @see Builder#setExtension(char, String) 621 * @since 1.7 622 */ 623 public static final char PRIVATE_USE_EXTENSION = 'x'; 624 625 /** 626 * The key for Unicode locale extension ('u'). 627 * 628 * @see #getExtension(char) 629 * @see Builder#setExtension(char, String) 630 * @since 1.7 631 */ 632 public static final char UNICODE_LOCALE_EXTENSION = 'u'; 633 634 /** serialization ID 635 */ 636 static final long serialVersionUID = 9149081749638150636L; 637 638 /** 639 * Enum for specifying the type defined in ISO 3166. This enum is used to 640 * retrieve the two-letter ISO3166-1 alpha-2, three-letter ISO3166-1 641 * alpha-3, four-letter ISO3166-3 country codes. 642 * 643 * @see #getISOCountries(Locale.IsoCountryCode) 644 * @since 9 645 */ 646 public static enum IsoCountryCode { 647 /** 648 * PART1_ALPHA2 is used to represent the ISO3166-1 alpha-2 two letter 649 * country codes. 650 */ 651 PART1_ALPHA2 { 652 @Override 653 Set<String> createCountryCodeSet() { 654 return Set.of(Locale.getISOCountries()); 655 } 656 }, 657 658 /** 659 * 660 * PART1_ALPHA3 is used to represent the ISO3166-1 alpha-3 three letter 661 * country codes. 662 */ 663 PART1_ALPHA3 { 664 @Override 665 Set<String> createCountryCodeSet() { 666 return LocaleISOData.computeISO3166_1Alpha3Countries(); 667 } 668 }, 669 670 /** 671 * PART3 is used to represent the ISO3166-3 four letter country codes. 672 */ 673 PART3 { 674 @Override 675 Set<String> createCountryCodeSet() { 676 return Set.of(LocaleISOData.ISO3166_3); 677 } 678 }; 679 680 /** 681 * Concrete implementation of this method attempts to compute value 682 * for iso3166CodesMap for each IsoCountryCode type key. 683 */ 684 abstract Set<String> createCountryCodeSet(); 685 686 /** 687 * Map to hold country codes for each ISO3166 part. 688 */ 689 private static Map<IsoCountryCode, Set<String>> iso3166CodesMap = new ConcurrentHashMap<>(); 690 691 /** 692 * This method is called from Locale class to retrieve country code set 693 * for getISOCountries(type) 694 */ 695 static Set<String> retrieveISOCountryCodes(IsoCountryCode type) { 696 return iso3166CodesMap.computeIfAbsent(type, IsoCountryCode::createCountryCodeSet); 697 } 698 } 699 700 /** 701 * Display types for retrieving localized names from the name providers. 702 */ 703 private static final int DISPLAY_LANGUAGE = 0; 704 private static final int DISPLAY_COUNTRY = 1; 705 private static final int DISPLAY_VARIANT = 2; 706 private static final int DISPLAY_SCRIPT = 3; 707 private static final int DISPLAY_UEXT_KEY = 4; 708 private static final int DISPLAY_UEXT_TYPE = 5; 709 710 /** 711 * Private constructor used by getInstance method 712 */ 713 private Locale(BaseLocale baseLocale, LocaleExtensions extensions) { 714 this.baseLocale = baseLocale; 715 this.localeExtensions = extensions; 716 } 717 718 /** 719 * Construct a locale from language, country and variant. 720 * This constructor normalizes the language value to lowercase and 721 * the country value to uppercase. 722 * <p> 723 * <b>Note:</b> 724 * <ul> 725 * <li>ISO 639 is not a stable standard; some of the language codes it defines 726 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 727 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 728 * API on Locale will return only the OLD codes. 729 * <li>For backward compatibility reasons, this constructor does not make 730 * any syntactic checks on the input. 731 * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially, 732 * see <a href="#special_cases_constructor">Special Cases</a> for more information. 733 * </ul> 734 * 735 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 736 * up to 8 characters in length. See the <code>Locale</code> class description about 737 * valid language values. 738 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 739 * See the <code>Locale</code> class description about valid country values. 740 * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>. 741 * See the <code>Locale</code> class description for the details. 742 * @exception NullPointerException thrown if any argument is null. 743 */ 744 public Locale(String language, String country, String variant) { 745 if (language == null || country == null || variant == null) { 746 throw new NullPointerException(); 747 } 748 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant); 749 localeExtensions = getCompatibilityExtensions(language, "", country, variant); 750 } 751 752 /** 753 * Construct a locale from language and country. 754 * This constructor normalizes the language value to lowercase and 755 * the country value to uppercase. 756 * <p> 757 * <b>Note:</b> 758 * <ul> 759 * <li>ISO 639 is not a stable standard; some of the language codes it defines 760 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 761 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 762 * API on Locale will return only the OLD codes. 763 * <li>For backward compatibility reasons, this constructor does not make 764 * any syntactic checks on the input. 765 * </ul> 766 * 767 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 768 * up to 8 characters in length. See the <code>Locale</code> class description about 769 * valid language values. 770 * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. 771 * See the <code>Locale</code> class description about valid country values. 772 * @exception NullPointerException thrown if either argument is null. 773 */ 774 public Locale(String language, String country) { 775 this(language, country, ""); 776 } 777 778 /** 779 * Construct a locale from a language code. 780 * This constructor normalizes the language value to lowercase. 781 * <p> 782 * <b>Note:</b> 783 * <ul> 784 * <li>ISO 639 is not a stable standard; some of the language codes it defines 785 * (specifically "iw", "ji", and "in") have changed. This constructor accepts both the 786 * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other 787 * API on Locale will return only the OLD codes. 788 * <li>For backward compatibility reasons, this constructor does not make 789 * any syntactic checks on the input. 790 * </ul> 791 * 792 * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag 793 * up to 8 characters in length. See the <code>Locale</code> class description about 794 * valid language values. 795 * @exception NullPointerException thrown if argument is null. 796 * @since 1.4 797 */ 798 public Locale(String language) { 799 this(language, "", ""); 800 } 801 802 /** 803 * Returns a <code>Locale</code> constructed from the given 804 * <code>language</code>, <code>country</code> and 805 * <code>variant</code>. If the same <code>Locale</code> instance 806 * is available in the cache, then that instance is 807 * returned. Otherwise, a new <code>Locale</code> instance is 808 * created and cached. 809 * 810 * @param language lowercase 2 to 8 language code. 811 * @param country uppercase two-letter ISO-3166 code and numeric-3 UN M.49 area code. 812 * @param variant vendor and browser specific code. See class description. 813 * @return the <code>Locale</code> instance requested 814 * @exception NullPointerException if any argument is null. 815 */ 816 static Locale getInstance(String language, String country, String variant) { 817 return getInstance(language, "", country, variant, null); 818 } 819 820 static Locale getInstance(String language, String script, String country, 821 String variant, LocaleExtensions extensions) { 822 if (language== null || script == null || country == null || variant == null) { 823 throw new NullPointerException(); 824 } 825 826 if (extensions == null) { 827 extensions = getCompatibilityExtensions(language, script, country, variant); 828 } 829 830 BaseLocale baseloc = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant); 831 return getInstance(baseloc, extensions); 832 } 833 834 static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) { 835 if (extensions == null) { 836 Locale locale = CONSTANT_LOCALES.get(baseloc); 837 if (locale != null) { 838 return locale; 839 } 840 return Cache.LOCALECACHE.get(baseloc); 841 } else { 842 LocaleKey key = new LocaleKey(baseloc, extensions); 843 return Cache.LOCALECACHE.get(key); 844 } 845 } 846 847 private static class Cache extends LocaleObjectCache<Object, Locale> { 848 849 private static final Cache LOCALECACHE = new Cache(); 850 851 private Cache() { 852 } 853 854 @Override 855 protected Locale createObject(Object key) { 856 if (key instanceof BaseLocale) { 857 return new Locale((BaseLocale)key, null); 858 } else { 859 LocaleKey lk = (LocaleKey)key; 860 return new Locale(lk.base, lk.exts); 861 } 862 } 863 } 864 865 private static final class LocaleKey { 866 private final BaseLocale base; 867 private final LocaleExtensions exts; 868 private final int hash; 869 870 private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) { 871 base = baseLocale; 872 exts = extensions; 873 874 // Calculate the hash value here because it's always used. 875 int h = base.hashCode(); 876 if (exts != null) { 877 h ^= exts.hashCode(); 878 } 879 hash = h; 880 } 881 882 @Override 883 public boolean equals(Object obj) { 884 if (this == obj) { 885 return true; 886 } 887 if (!(obj instanceof LocaleKey)) { 888 return false; 889 } 890 LocaleKey other = (LocaleKey)obj; 891 if (hash != other.hash || !base.equals(other.base)) { 892 return false; 893 } 894 if (exts == null) { 895 return other.exts == null; 896 } 897 return exts.equals(other.exts); 898 } 899 900 @Override 901 public int hashCode() { 902 return hash; 903 } 904 } 905 906 /** 907 * Gets the current value of the default locale for this instance 908 * of the Java Virtual Machine. 909 * <p> 910 * The Java Virtual Machine sets the default locale during startup 911 * based on the host environment. It is used by many locale-sensitive 912 * methods if no locale is explicitly specified. 913 * It can be changed using the 914 * {@link #setDefault(java.util.Locale) setDefault} method. 915 * 916 * @return the default locale for this instance of the Java Virtual Machine 917 */ 918 public static Locale getDefault() { 919 // do not synchronize this method - see 4071298 920 return defaultLocale; 921 } 922 923 /** 924 * Gets the current value of the default locale for the specified Category 925 * for this instance of the Java Virtual Machine. 926 * <p> 927 * The Java Virtual Machine sets the default locale during startup based 928 * on the host environment. It is used by many locale-sensitive methods 929 * if no locale is explicitly specified. It can be changed using the 930 * setDefault(Locale.Category, Locale) method. 931 * 932 * @param category the specified category to get the default locale 933 * @throws NullPointerException if category is null 934 * @return the default locale for the specified Category for this instance 935 * of the Java Virtual Machine 936 * @see #setDefault(Locale.Category, Locale) 937 * @since 1.7 938 */ 939 public static Locale getDefault(Locale.Category category) { 940 // do not synchronize this method - see 4071298 941 switch (category) { 942 case DISPLAY: 943 if (defaultDisplayLocale == null) { 944 synchronized(Locale.class) { 945 if (defaultDisplayLocale == null) { 946 defaultDisplayLocale = initDefault(category); 947 } 948 } 949 } 950 return defaultDisplayLocale; 951 case FORMAT: 952 if (defaultFormatLocale == null) { 953 synchronized(Locale.class) { 954 if (defaultFormatLocale == null) { 955 defaultFormatLocale = initDefault(category); 956 } 957 } 958 } 959 return defaultFormatLocale; 960 default: 961 assert false: "Unknown Category"; 962 } 963 return getDefault(); 964 } 965 966 private static Locale initDefault() { 967 String language, region, script, country, variant; 968 Properties props = GetPropertyAction.privilegedGetProperties(); 969 language = props.getProperty("user.language", "en"); 970 // for compatibility, check for old user.region property 971 region = props.getProperty("user.region"); 972 if (region != null) { 973 // region can be of form country, country_variant, or _variant 974 int i = region.indexOf('_'); 975 if (i >= 0) { 976 country = region.substring(0, i); 977 variant = region.substring(i + 1); 978 } else { 979 country = region; 980 variant = ""; 981 } 982 script = ""; 983 } else { 984 script = props.getProperty("user.script", ""); 985 country = props.getProperty("user.country", ""); 986 variant = props.getProperty("user.variant", ""); 987 } 988 989 return getInstance(language, script, country, variant, 990 getDefaultExtensions(props.getProperty("user.extensions", "")) 991 .orElse(null)); 992 } 993 994 private static Locale initDefault(Locale.Category category) { 995 Properties props = GetPropertyAction.privilegedGetProperties(); 996 997 return getInstance( 998 props.getProperty(category.languageKey, 999 defaultLocale.getLanguage()), 1000 props.getProperty(category.scriptKey, 1001 defaultLocale.getScript()), 1002 props.getProperty(category.countryKey, 1003 defaultLocale.getCountry()), 1004 props.getProperty(category.variantKey, 1005 defaultLocale.getVariant()), 1006 getDefaultExtensions(props.getProperty(category.extensionsKey, "")) 1007 .orElse(defaultLocale.getLocaleExtensions())); 1008 } 1009 1010 private static Optional<LocaleExtensions> getDefaultExtensions(String extensionsProp) { 1011 if (LocaleUtils.isEmpty(extensionsProp)) { 1012 return Optional.empty(); 1013 } 1014 1015 LocaleExtensions exts = null; 1016 try { 1017 exts = new InternalLocaleBuilder() 1018 .setExtensions(extensionsProp) 1019 .getLocaleExtensions(); 1020 } catch (LocaleSyntaxException e) { 1021 // just ignore this incorrect property 1022 } 1023 1024 return Optional.ofNullable(exts); 1025 } 1026 1027 /** 1028 * Sets the default locale for this instance of the Java Virtual Machine. 1029 * This does not affect the host locale. 1030 * <p> 1031 * If there is a security manager, its <code>checkPermission</code> 1032 * method is called with a <code>PropertyPermission("user.language", "write")</code> 1033 * permission before the default locale is changed. 1034 * <p> 1035 * The Java Virtual Machine sets the default locale during startup 1036 * based on the host environment. It is used by many locale-sensitive 1037 * methods if no locale is explicitly specified. 1038 * <p> 1039 * Since changing the default locale may affect many different areas 1040 * of functionality, this method should only be used if the caller 1041 * is prepared to reinitialize locale-sensitive code running 1042 * within the same Java Virtual Machine. 1043 * <p> 1044 * By setting the default locale with this method, all of the default 1045 * locales for each Category are also set to the specified default locale. 1046 * 1047 * @throws SecurityException 1048 * if a security manager exists and its 1049 * <code>checkPermission</code> method doesn't allow the operation. 1050 * @throws NullPointerException if <code>newLocale</code> is null 1051 * @param newLocale the new default locale 1052 * @see SecurityManager#checkPermission 1053 * @see java.util.PropertyPermission 1054 */ 1055 public static synchronized void setDefault(Locale newLocale) { 1056 setDefault(Category.DISPLAY, newLocale); 1057 setDefault(Category.FORMAT, newLocale); 1058 defaultLocale = newLocale; 1059 } 1060 1061 /** 1062 * Sets the default locale for the specified Category for this instance 1063 * of the Java Virtual Machine. This does not affect the host locale. 1064 * <p> 1065 * If there is a security manager, its checkPermission method is called 1066 * with a PropertyPermission("user.language", "write") permission before 1067 * the default locale is changed. 1068 * <p> 1069 * The Java Virtual Machine sets the default locale during startup based 1070 * on the host environment. It is used by many locale-sensitive methods 1071 * if no locale is explicitly specified. 1072 * <p> 1073 * Since changing the default locale may affect many different areas of 1074 * functionality, this method should only be used if the caller is 1075 * prepared to reinitialize locale-sensitive code running within the 1076 * same Java Virtual Machine. 1077 * 1078 * @param category the specified category to set the default locale 1079 * @param newLocale the new default locale 1080 * @throws SecurityException if a security manager exists and its 1081 * checkPermission method doesn't allow the operation. 1082 * @throws NullPointerException if category and/or newLocale is null 1083 * @see SecurityManager#checkPermission(java.security.Permission) 1084 * @see PropertyPermission 1085 * @see #getDefault(Locale.Category) 1086 * @since 1.7 1087 */ 1088 public static synchronized void setDefault(Locale.Category category, 1089 Locale newLocale) { 1090 if (category == null) 1091 throw new NullPointerException("Category cannot be NULL"); 1092 if (newLocale == null) 1093 throw new NullPointerException("Can't set default locale to NULL"); 1094 1095 SecurityManager sm = System.getSecurityManager(); 1096 if (sm != null) sm.checkPermission(new PropertyPermission 1097 ("user.language", "write")); 1098 switch (category) { 1099 case DISPLAY: 1100 defaultDisplayLocale = newLocale; 1101 break; 1102 case FORMAT: 1103 defaultFormatLocale = newLocale; 1104 break; 1105 default: 1106 assert false: "Unknown Category"; 1107 } 1108 } 1109 1110 /** 1111 * Returns an array of all installed locales. 1112 * The returned array represents the union of locales supported 1113 * by the Java runtime environment and by installed 1114 * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider} 1115 * implementations. It must contain at least a <code>Locale</code> 1116 * instance equal to {@link java.util.Locale#US Locale.US}. 1117 * 1118 * @return An array of installed locales. 1119 */ 1120 public static Locale[] getAvailableLocales() { 1121 return LocaleServiceProviderPool.getAllAvailableLocales(); 1122 } 1123 1124 /** 1125 * Returns a list of all 2-letter country codes defined in ISO 3166. 1126 * Can be used to create Locales. 1127 * This method is equivalent to {@link #getISOCountries(Locale.IsoCountryCode type)} 1128 * with {@code type} {@link IsoCountryCode#PART1_ALPHA2}. 1129 * <p> 1130 * <b>Note:</b> The <code>Locale</code> class also supports other codes for 1131 * country (region), such as 3-letter numeric UN M.49 area codes. 1132 * Therefore, the list returned by this method does not contain ALL valid 1133 * codes that can be used to create Locales. 1134 * <p> 1135 * Note that this method does not return obsolete 2-letter country codes. 1136 * ISO3166-3 codes which designate country codes for those obsolete codes, 1137 * can be retrieved from {@link #getISOCountries(Locale.IsoCountryCode type)} with 1138 * {@code type} {@link IsoCountryCode#PART3}. 1139 * @return An array of ISO 3166 two-letter country codes. 1140 */ 1141 public static String[] getISOCountries() { 1142 if (isoCountries == null) { 1143 isoCountries = getISO2Table(LocaleISOData.isoCountryTable); 1144 } 1145 String[] result = new String[isoCountries.length]; 1146 System.arraycopy(isoCountries, 0, result, 0, isoCountries.length); 1147 return result; 1148 } 1149 1150 /** 1151 * Returns a {@code Set} of ISO3166 country codes for the specified type. 1152 * 1153 * @param type {@link Locale.IsoCountryCode} specified ISO code type. 1154 * @see java.util.Locale.IsoCountryCode 1155 * @throws NullPointerException if type is null 1156 * @return a {@code Set} of ISO country codes for the specified type. 1157 * @since 9 1158 */ 1159 public static Set<String> getISOCountries(IsoCountryCode type) { 1160 Objects.requireNonNull(type); 1161 return IsoCountryCode.retrieveISOCountryCodes(type); 1162 } 1163 1164 /** 1165 * Returns a list of all 2-letter language codes defined in ISO 639. 1166 * Can be used to create Locales. 1167 * <p> 1168 * <b>Note:</b> 1169 * <ul> 1170 * <li>ISO 639 is not a stable standard— some languages' codes have changed. 1171 * The list this function returns includes both the new and the old codes for the 1172 * languages whose codes have changed. 1173 * <li>The <code>Locale</code> class also supports language codes up to 1174 * 8 characters in length. Therefore, the list returned by this method does 1175 * not contain ALL valid codes that can be used to create Locales. 1176 * </ul> 1177 * 1178 * @return An array of ISO 639 two-letter language codes. 1179 */ 1180 public static String[] getISOLanguages() { 1181 if (isoLanguages == null) { 1182 isoLanguages = getISO2Table(LocaleISOData.isoLanguageTable); 1183 } 1184 String[] result = new String[isoLanguages.length]; 1185 System.arraycopy(isoLanguages, 0, result, 0, isoLanguages.length); 1186 return result; 1187 } 1188 1189 private static String[] getISO2Table(String table) { 1190 int len = table.length() / 5; 1191 String[] isoTable = new String[len]; 1192 for (int i = 0, j = 0; i < len; i++, j += 5) { 1193 isoTable[i] = table.substring(j, j + 2); 1194 } 1195 return isoTable; 1196 } 1197 1198 /** 1199 * Returns the language code of this Locale. 1200 * 1201 * <p><b>Note:</b> ISO 639 is not a stable standard— some languages' codes have changed. 1202 * Locale's constructor recognizes both the new and the old codes for the languages 1203 * whose codes have changed, but this function always returns the old code. If you 1204 * want to check for a specific language whose code has changed, don't do 1205 * <pre> 1206 * if (locale.getLanguage().equals("he")) // BAD! 1207 * ... 1208 * </pre> 1209 * Instead, do 1210 * <pre> 1211 * if (locale.getLanguage().equals(new Locale("he").getLanguage())) 1212 * ... 1213 * </pre> 1214 * @return The language code, or the empty string if none is defined. 1215 * @see #getDisplayLanguage 1216 */ 1217 public String getLanguage() { 1218 return baseLocale.getLanguage(); 1219 } 1220 1221 /** 1222 * Returns the script for this locale, which should 1223 * either be the empty string or an ISO 15924 4-letter script 1224 * code. The first letter is uppercase and the rest are 1225 * lowercase, for example, 'Latn', 'Cyrl'. 1226 * 1227 * @return The script code, or the empty string if none is defined. 1228 * @see #getDisplayScript 1229 * @since 1.7 1230 */ 1231 public String getScript() { 1232 return baseLocale.getScript(); 1233 } 1234 1235 /** 1236 * Returns the country/region code for this locale, which should 1237 * either be the empty string, an uppercase ISO 3166 2-letter code, 1238 * or a UN M.49 3-digit code. 1239 * 1240 * @return The country/region code, or the empty string if none is defined. 1241 * @see #getDisplayCountry 1242 */ 1243 public String getCountry() { 1244 return baseLocale.getRegion(); 1245 } 1246 1247 /** 1248 * Returns the variant code for this locale. 1249 * 1250 * @return The variant code, or the empty string if none is defined. 1251 * @see #getDisplayVariant 1252 */ 1253 public String getVariant() { 1254 return baseLocale.getVariant(); 1255 } 1256 1257 /** 1258 * Returns {@code true} if this {@code Locale} has any <a href="#def_extensions"> 1259 * extensions</a>. 1260 * 1261 * @return {@code true} if this {@code Locale} has any extensions 1262 * @since 1.8 1263 */ 1264 public boolean hasExtensions() { 1265 return localeExtensions != null; 1266 } 1267 1268 /** 1269 * Returns a copy of this {@code Locale} with no <a href="#def_extensions"> 1270 * extensions</a>. If this {@code Locale} has no extensions, this {@code Locale} 1271 * is returned. 1272 * 1273 * @return a copy of this {@code Locale} with no extensions, or {@code this} 1274 * if {@code this} has no extensions 1275 * @since 1.8 1276 */ 1277 public Locale stripExtensions() { 1278 return hasExtensions() ? Locale.getInstance(baseLocale, null) : this; 1279 } 1280 1281 /** 1282 * Returns the extension (or private use) value associated with 1283 * the specified key, or null if there is no extension 1284 * associated with the key. To be well-formed, the key must be one 1285 * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so 1286 * for example 'z' and 'Z' represent the same extension. 1287 * 1288 * @param key the extension key 1289 * @return The extension, or null if this locale defines no 1290 * extension for the specified key. 1291 * @throws IllegalArgumentException if key is not well-formed 1292 * @see #PRIVATE_USE_EXTENSION 1293 * @see #UNICODE_LOCALE_EXTENSION 1294 * @since 1.7 1295 */ 1296 public String getExtension(char key) { 1297 if (!LocaleExtensions.isValidKey(key)) { 1298 throw new IllegalArgumentException("Ill-formed extension key: " + key); 1299 } 1300 return hasExtensions() ? localeExtensions.getExtensionValue(key) : null; 1301 } 1302 1303 /** 1304 * Returns the set of extension keys associated with this locale, or the 1305 * empty set if it has no extensions. The returned set is unmodifiable. 1306 * The keys will all be lower-case. 1307 * 1308 * @return The set of extension keys, or the empty set if this locale has 1309 * no extensions. 1310 * @since 1.7 1311 */ 1312 public Set<Character> getExtensionKeys() { 1313 if (!hasExtensions()) { 1314 return Collections.emptySet(); 1315 } 1316 return localeExtensions.getKeys(); 1317 } 1318 1319 /** 1320 * Returns the set of unicode locale attributes associated with 1321 * this locale, or the empty set if it has no attributes. The 1322 * returned set is unmodifiable. 1323 * 1324 * @return The set of attributes. 1325 * @since 1.7 1326 */ 1327 public Set<String> getUnicodeLocaleAttributes() { 1328 if (!hasExtensions()) { 1329 return Collections.emptySet(); 1330 } 1331 return localeExtensions.getUnicodeLocaleAttributes(); 1332 } 1333 1334 /** 1335 * Returns the Unicode locale type associated with the specified Unicode locale key 1336 * for this locale. Returns the empty string for keys that are defined with no type. 1337 * Returns null if the key is not defined. Keys are case-insensitive. The key must 1338 * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is 1339 * thrown. 1340 * 1341 * @param key the Unicode locale key 1342 * @return The Unicode locale type associated with the key, or null if the 1343 * locale does not define the key. 1344 * @throws IllegalArgumentException if the key is not well-formed 1345 * @throws NullPointerException if <code>key</code> is null 1346 * @since 1.7 1347 */ 1348 public String getUnicodeLocaleType(String key) { 1349 if (!isUnicodeExtensionKey(key)) { 1350 throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key); 1351 } 1352 return hasExtensions() ? localeExtensions.getUnicodeLocaleType(key) : null; 1353 } 1354 1355 /** 1356 * Returns the set of Unicode locale keys defined by this locale, or the empty set if 1357 * this locale has none. The returned set is immutable. Keys are all lower case. 1358 * 1359 * @return The set of Unicode locale keys, or the empty set if this locale has 1360 * no Unicode locale keywords. 1361 * @since 1.7 1362 */ 1363 public Set<String> getUnicodeLocaleKeys() { 1364 if (localeExtensions == null) { 1365 return Collections.emptySet(); 1366 } 1367 return localeExtensions.getUnicodeLocaleKeys(); 1368 } 1369 1370 /** 1371 * Package locale method returning the Locale's BaseLocale, 1372 * used by ResourceBundle 1373 * @return base locale of this Locale 1374 */ 1375 BaseLocale getBaseLocale() { 1376 return baseLocale; 1377 } 1378 1379 /** 1380 * Package private method returning the Locale's LocaleExtensions, 1381 * used by ResourceBundle. 1382 * @return locale extensions of this Locale, 1383 * or {@code null} if no extensions are defined 1384 */ 1385 LocaleExtensions getLocaleExtensions() { 1386 return localeExtensions; 1387 } 1388 1389 /** 1390 * Returns a string representation of this <code>Locale</code> 1391 * object, consisting of language, country, variant, script, 1392 * and extensions as below: 1393 * <blockquote> 1394 * language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions 1395 * </blockquote> 1396 * 1397 * Language is always lower case, country is always upper case, script is always title 1398 * case, and extensions are always lower case. Extensions and private use subtags 1399 * will be in canonical order as explained in {@link #toLanguageTag}. 1400 * 1401 * <p>When the locale has neither script nor extensions, the result is the same as in 1402 * Java 6 and prior. 1403 * 1404 * <p>If both the language and country fields are missing, this function will return 1405 * the empty string, even if the variant, script, or extensions field is present (you 1406 * can't have a locale with just a variant, the variant must accompany a well-formed 1407 * language or country code). 1408 * 1409 * <p>If script or extensions are present and variant is missing, no underscore is 1410 * added before the "#". 1411 * 1412 * <p>This behavior is designed to support debugging and to be compatible with 1413 * previous uses of <code>toString</code> that expected language, country, and variant 1414 * fields only. To represent a Locale as a String for interchange purposes, use 1415 * {@link #toLanguageTag}. 1416 * 1417 * <p>Examples: <ul> 1418 * <li>{@code en}</li> 1419 * <li>{@code de_DE}</li> 1420 * <li>{@code _GB}</li> 1421 * <li>{@code en_US_WIN}</li> 1422 * <li>{@code de__POSIX}</li> 1423 * <li>{@code zh_CN_#Hans}</li> 1424 * <li>{@code zh_TW_#Hant_x-java}</li> 1425 * <li>{@code th_TH_TH_#u-nu-thai}</li></ul> 1426 * 1427 * @return A string representation of the Locale, for debugging. 1428 * @see #getDisplayName 1429 * @see #toLanguageTag 1430 */ 1431 @Override 1432 public final String toString() { 1433 boolean l = !baseLocale.getLanguage().isEmpty(); 1434 boolean s = !baseLocale.getScript().isEmpty(); 1435 boolean r = !baseLocale.getRegion().isEmpty(); 1436 boolean v = !baseLocale.getVariant().isEmpty(); 1437 boolean e = localeExtensions != null && !localeExtensions.getID().isEmpty(); 1438 1439 StringBuilder result = new StringBuilder(baseLocale.getLanguage()); 1440 if (r || (l && (v || s || e))) { 1441 result.append('_') 1442 .append(baseLocale.getRegion()); // This may just append '_' 1443 } 1444 if (v && (l || r)) { 1445 result.append('_') 1446 .append(baseLocale.getVariant()); 1447 } 1448 1449 if (s && (l || r)) { 1450 result.append("_#") 1451 .append(baseLocale.getScript()); 1452 } 1453 1454 if (e && (l || r)) { 1455 result.append('_'); 1456 if (!s) { 1457 result.append('#'); 1458 } 1459 result.append(localeExtensions.getID()); 1460 } 1461 1462 return result.toString(); 1463 } 1464 1465 /** 1466 * Returns a well-formed IETF BCP 47 language tag representing 1467 * this locale. 1468 * 1469 * <p>If this <code>Locale</code> has a language, country, or 1470 * variant that does not satisfy the IETF BCP 47 language tag 1471 * syntax requirements, this method handles these fields as 1472 * described below: 1473 * 1474 * <p><b>Language:</b> If language is empty, or not <a 1475 * href="#def_language" >well-formed</a> (for example "a" or 1476 * "e2"), it will be emitted as "und" (Undetermined). 1477 * 1478 * <p><b>Country:</b> If country is not <a 1479 * href="#def_region">well-formed</a> (for example "12" or "USA"), 1480 * it will be omitted. 1481 * 1482 * <p><b>Variant:</b> If variant <b>is</b> <a 1483 * href="#def_variant">well-formed</a>, each sub-segment 1484 * (delimited by '-' or '_') is emitted as a subtag. Otherwise: 1485 * <ul> 1486 * 1487 * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code> 1488 * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first 1489 * ill-formed sub-segment and all following will be appended to 1490 * the private use subtag. The first appended subtag will be 1491 * "lvariant", followed by the sub-segments in order, separated by 1492 * hyphen. For example, "x-lvariant-WIN", 1493 * "Oracle-x-lvariant-JDK-Standard-Edition". 1494 * 1495 * <li>if any sub-segment does not match 1496 * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated 1497 * and the problematic sub-segment and all following sub-segments 1498 * will be omitted. If the remainder is non-empty, it will be 1499 * emitted as a private use subtag as above (even if the remainder 1500 * turns out to be well-formed). For example, 1501 * "Solaris_isjustthecoolestthing" is emitted as 1502 * "x-lvariant-Solaris", not as "solaris".</li></ul> 1503 * 1504 * <p><b>Special Conversions:</b> Java supports some old locale 1505 * representations, including deprecated ISO language codes, 1506 * for compatibility. This method performs the following 1507 * conversions: 1508 * <ul> 1509 * 1510 * <li>Deprecated ISO language codes "iw", "ji", and "in" are 1511 * converted to "he", "yi", and "id", respectively. 1512 * 1513 * <li>A locale with language "no", country "NO", and variant 1514 * "NY", representing Norwegian Nynorsk (Norway), is converted 1515 * to a language tag "nn-NO".</li></ul> 1516 * 1517 * <p><b>Note:</b> Although the language tag created by this 1518 * method is well-formed (satisfies the syntax requirements 1519 * defined by the IETF BCP 47 specification), it is not 1520 * necessarily a valid BCP 47 language tag. For example, 1521 * <pre> 1522 * new Locale("xx", "YY").toLanguageTag();</pre> 1523 * 1524 * will return "xx-YY", but the language subtag "xx" and the 1525 * region subtag "YY" are invalid because they are not registered 1526 * in the IANA Language Subtag Registry. 1527 * 1528 * @return a BCP47 language tag representing the locale 1529 * @see #forLanguageTag(String) 1530 * @since 1.7 1531 */ 1532 public String toLanguageTag() { 1533 if (languageTag != null) { 1534 return languageTag; 1535 } 1536 1537 LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions); 1538 StringBuilder buf = new StringBuilder(); 1539 1540 String subtag = tag.getLanguage(); 1541 if (!subtag.isEmpty()) { 1542 buf.append(LanguageTag.canonicalizeLanguage(subtag)); 1543 } 1544 1545 subtag = tag.getScript(); 1546 if (!subtag.isEmpty()) { 1547 buf.append(LanguageTag.SEP); 1548 buf.append(LanguageTag.canonicalizeScript(subtag)); 1549 } 1550 1551 subtag = tag.getRegion(); 1552 if (!subtag.isEmpty()) { 1553 buf.append(LanguageTag.SEP); 1554 buf.append(LanguageTag.canonicalizeRegion(subtag)); 1555 } 1556 1557 List<String>subtags = tag.getVariants(); 1558 for (String s : subtags) { 1559 buf.append(LanguageTag.SEP); 1560 // preserve casing 1561 buf.append(s); 1562 } 1563 1564 subtags = tag.getExtensions(); 1565 for (String s : subtags) { 1566 buf.append(LanguageTag.SEP); 1567 buf.append(LanguageTag.canonicalizeExtension(s)); 1568 } 1569 1570 subtag = tag.getPrivateuse(); 1571 if (!subtag.isEmpty()) { 1572 if (buf.length() > 0) { 1573 buf.append(LanguageTag.SEP); 1574 } 1575 buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP); 1576 // preserve casing 1577 buf.append(subtag); 1578 } 1579 1580 String langTag = buf.toString(); 1581 synchronized (this) { 1582 if (languageTag == null) { 1583 languageTag = langTag; 1584 } 1585 } 1586 return languageTag; 1587 } 1588 1589 /** 1590 * Returns a locale for the specified IETF BCP 47 language tag string. 1591 * 1592 * <p>If the specified language tag contains any ill-formed subtags, 1593 * the first such subtag and all following subtags are ignored. Compare 1594 * to {@link Locale.Builder#setLanguageTag} which throws an exception 1595 * in this case. 1596 * 1597 * <p>The following <b>conversions</b> are performed:<ul> 1598 * 1599 * <li>The language code "und" is mapped to language "". 1600 * 1601 * <li>The language codes "he", "yi", and "id" are mapped to "iw", 1602 * "ji", and "in" respectively. (This is the same canonicalization 1603 * that's done in Locale's constructors.) 1604 * 1605 * <li>The portion of a private use subtag prefixed by "lvariant", 1606 * if any, is removed and appended to the variant field in the 1607 * result locale (without case normalization). If it is then 1608 * empty, the private use subtag is discarded: 1609 * 1610 * <pre> 1611 * Locale loc; 1612 * loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX"); 1613 * loc.getVariant(); // returns "POSIX" 1614 * loc.getExtension('x'); // returns null 1615 * 1616 * loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def"); 1617 * loc.getVariant(); // returns "POSIX_Abc_Def" 1618 * loc.getExtension('x'); // returns "urp" 1619 * </pre> 1620 * 1621 * <li>When the languageTag argument contains an extlang subtag, 1622 * the first such subtag is used as the language, and the primary 1623 * language subtag and other extlang subtags are ignored: 1624 * 1625 * <pre> 1626 * Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao" 1627 * Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US" 1628 * </pre> 1629 * 1630 * <li>Case is normalized except for variant tags, which are left 1631 * unchanged. Language is normalized to lower case, script to 1632 * title case, country to upper case, and extensions to lower 1633 * case. 1634 * 1635 * <li>If, after processing, the locale would exactly match either 1636 * ja_JP_JP or th_TH_TH with no extensions, the appropriate 1637 * extensions are added as though the constructor had been called: 1638 * 1639 * <pre> 1640 * Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag(); 1641 * // returns "ja-JP-u-ca-japanese-x-lvariant-JP" 1642 * Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag(); 1643 * // returns "th-TH-u-nu-thai-x-lvariant-TH" 1644 * </pre></ul> 1645 * 1646 * <p>This implements the 'Language-Tag' production of BCP47, and 1647 * so supports grandfathered (regular and irregular) as well as 1648 * private use language tags. Stand alone private use tags are 1649 * represented as empty language and extension 'x-whatever', 1650 * and grandfathered tags are converted to their canonical replacements 1651 * where they exist. 1652 * 1653 * <p>Grandfathered tags with canonical replacements are as follows: 1654 * 1655 * <table class="striped"> 1656 * <caption style="display:none">Grandfathered tags with canonical replacements</caption> 1657 * <thead style="text-align:center"> 1658 * <tr><th scope="col" style="padding: 0 2px">grandfathered tag</th><th scope="col" style="padding: 0 2px">modern replacement</th></tr> 1659 * </thead> 1660 * <tbody style="text-align:center"> 1661 * <tr><th scope="row">art-lojban</th><td>jbo</td></tr> 1662 * <tr><th scope="row">i-ami</th><td>ami</td></tr> 1663 * <tr><th scope="row">i-bnn</th><td>bnn</td></tr> 1664 * <tr><th scope="row">i-hak</th><td>hak</td></tr> 1665 * <tr><th scope="row">i-klingon</th><td>tlh</td></tr> 1666 * <tr><th scope="row">i-lux</th><td>lb</td></tr> 1667 * <tr><th scope="row">i-navajo</th><td>nv</td></tr> 1668 * <tr><th scope="row">i-pwn</th><td>pwn</td></tr> 1669 * <tr><th scope="row">i-tao</th><td>tao</td></tr> 1670 * <tr><th scope="row">i-tay</th><td>tay</td></tr> 1671 * <tr><th scope="row">i-tsu</th><td>tsu</td></tr> 1672 * <tr><th scope="row">no-bok</th><td>nb</td></tr> 1673 * <tr><th scope="row">no-nyn</th><td>nn</td></tr> 1674 * <tr><th scope="row">sgn-BE-FR</th><td>sfb</td></tr> 1675 * <tr><th scope="row">sgn-BE-NL</th><td>vgt</td></tr> 1676 * <tr><th scope="row">sgn-CH-DE</th><td>sgg</td></tr> 1677 * <tr><th scope="row">zh-guoyu</th><td>cmn</td></tr> 1678 * <tr><th scope="row">zh-hakka</th><td>hak</td></tr> 1679 * <tr><th scope="row">zh-min-nan</th><td>nan</td></tr> 1680 * <tr><th scope="row">zh-xiang</th><td>hsn</td></tr> 1681 * </tbody> 1682 * </table> 1683 * 1684 * <p>Grandfathered tags with no modern replacement will be 1685 * converted as follows: 1686 * 1687 * <table class="striped"> 1688 * <caption style="display:none">Grandfathered tags with no modern replacement</caption> 1689 * <thead style="text-align:center"> 1690 * <tr><th scope="col" style="padding: 0 2px">grandfathered tag</th><th scope="col" style="padding: 0 2px">converts to</th></tr> 1691 * </thead> 1692 * <tbody style="text-align:center"> 1693 * <tr><th scope="row">cel-gaulish</th><td>xtg-x-cel-gaulish</td></tr> 1694 * <tr><th scope="row">en-GB-oed</th><td>en-GB-x-oed</td></tr> 1695 * <tr><th scope="row">i-default</th><td>en-x-i-default</td></tr> 1696 * <tr><th scope="row">i-enochian</th><td>und-x-i-enochian</td></tr> 1697 * <tr><th scope="row">i-mingo</th><td>see-x-i-mingo</td></tr> 1698 * <tr><th scope="row">zh-min</th><td>nan-x-zh-min</td></tr> 1699 * </tbody> 1700 * </table> 1701 * 1702 * <p>For a list of all grandfathered tags, see the 1703 * IANA Language Subtag Registry (search for "Type: grandfathered"). 1704 * 1705 * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code> 1706 * and <code>forLanguageTag</code> will round-trip. 1707 * 1708 * @param languageTag the language tag 1709 * @return The locale that best represents the language tag. 1710 * @throws NullPointerException if <code>languageTag</code> is <code>null</code> 1711 * @see #toLanguageTag() 1712 * @see java.util.Locale.Builder#setLanguageTag(String) 1713 * @since 1.7 1714 */ 1715 public static Locale forLanguageTag(String languageTag) { 1716 LanguageTag tag = LanguageTag.parse(languageTag, null); 1717 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 1718 bldr.setLanguageTag(tag); 1719 BaseLocale base = bldr.getBaseLocale(); 1720 LocaleExtensions exts = bldr.getLocaleExtensions(); 1721 if (exts == null && !base.getVariant().isEmpty()) { 1722 exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(), 1723 base.getRegion(), base.getVariant()); 1724 } 1725 return getInstance(base, exts); 1726 } 1727 1728 /** 1729 * Returns a three-letter abbreviation of this locale's language. 1730 * If the language matches an ISO 639-1 two-letter code, the 1731 * corresponding ISO 639-2/T three-letter lowercase code is 1732 * returned. The ISO 639-2 language codes can be found on-line, 1733 * see "Codes for the Representation of Names of Languages Part 2: 1734 * Alpha-3 Code". If the locale specifies a three-letter 1735 * language, the language is returned as is. If the locale does 1736 * not specify a language the empty string is returned. 1737 * 1738 * @return A three-letter abbreviation of this locale's language. 1739 * @exception MissingResourceException Throws MissingResourceException if 1740 * three-letter language abbreviation is not available for this locale. 1741 */ 1742 public String getISO3Language() throws MissingResourceException { 1743 String lang = baseLocale.getLanguage(); 1744 if (lang.length() == 3) { 1745 return lang; 1746 } 1747 1748 String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable); 1749 if (language3 == null) { 1750 throw new MissingResourceException("Couldn't find 3-letter language code for " 1751 + lang, "FormatData_" + toString(), "ShortLanguage"); 1752 } 1753 return language3; 1754 } 1755 1756 /** 1757 * Returns a three-letter abbreviation for this locale's country. 1758 * If the country matches an ISO 3166-1 alpha-2 code, the 1759 * corresponding ISO 3166-1 alpha-3 uppercase code is returned. 1760 * If the locale doesn't specify a country, this will be the empty 1761 * string. 1762 * 1763 * <p>The ISO 3166-1 codes can be found on-line. 1764 * 1765 * @return A three-letter abbreviation of this locale's country. 1766 * @exception MissingResourceException Throws MissingResourceException if the 1767 * three-letter country abbreviation is not available for this locale. 1768 */ 1769 public String getISO3Country() throws MissingResourceException { 1770 String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable); 1771 if (country3 == null) { 1772 throw new MissingResourceException("Couldn't find 3-letter country code for " 1773 + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry"); 1774 } 1775 return country3; 1776 } 1777 1778 private static String getISO3Code(String iso2Code, String table) { 1779 int codeLength = iso2Code.length(); 1780 if (codeLength == 0) { 1781 return ""; 1782 } 1783 1784 int tableLength = table.length(); 1785 int index = tableLength; 1786 if (codeLength == 2) { 1787 char c1 = iso2Code.charAt(0); 1788 char c2 = iso2Code.charAt(1); 1789 for (index = 0; index < tableLength; index += 5) { 1790 if (table.charAt(index) == c1 1791 && table.charAt(index + 1) == c2) { 1792 break; 1793 } 1794 } 1795 } 1796 return index < tableLength ? table.substring(index + 2, index + 5) : null; 1797 } 1798 1799 /** 1800 * Returns a name for the locale's language that is appropriate for display to the 1801 * user. 1802 * If possible, the name returned will be localized for the default 1803 * {@link Locale.Category#DISPLAY DISPLAY} locale. 1804 * For example, if the locale is fr_FR and the default 1805 * {@link Locale.Category#DISPLAY DISPLAY} locale 1806 * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and 1807 * the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR, 1808 * getDisplayLanguage() will return "anglais". 1809 * If the name returned cannot be localized for the default 1810 * {@link Locale.Category#DISPLAY DISPLAY} locale, 1811 * (say, we don't have a Japanese name for Croatian), 1812 * this function falls back on the English name, and uses the ISO code as a last-resort 1813 * value. If the locale doesn't specify a language, this function returns the empty string. 1814 * 1815 * @return The name of the display language. 1816 */ 1817 public final String getDisplayLanguage() { 1818 return getDisplayLanguage(getDefault(Category.DISPLAY)); 1819 } 1820 1821 /** 1822 * Returns a name for the locale's language that is appropriate for display to the 1823 * user. 1824 * If possible, the name returned will be localized according to inLocale. 1825 * For example, if the locale is fr_FR and inLocale 1826 * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and 1827 * inLocale is fr_FR, getDisplayLanguage() will return "anglais". 1828 * If the name returned cannot be localized according to inLocale, 1829 * (say, we don't have a Japanese name for Croatian), 1830 * this function falls back on the English name, and finally 1831 * on the ISO code as a last-resort value. If the locale doesn't specify a language, 1832 * this function returns the empty string. 1833 * 1834 * @param inLocale The locale for which to retrieve the display language. 1835 * @return The name of the display language appropriate to the given locale. 1836 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1837 */ 1838 public String getDisplayLanguage(Locale inLocale) { 1839 return getDisplayString(baseLocale.getLanguage(), null, inLocale, DISPLAY_LANGUAGE); 1840 } 1841 1842 /** 1843 * Returns a name for the locale's script that is appropriate for display to 1844 * the user. If possible, the name will be localized for the default 1845 * {@link Locale.Category#DISPLAY DISPLAY} locale. Returns 1846 * the empty string if this locale doesn't specify a script code. 1847 * 1848 * @return the display name of the script code for the current default 1849 * {@link Locale.Category#DISPLAY DISPLAY} locale 1850 * @since 1.7 1851 */ 1852 public String getDisplayScript() { 1853 return getDisplayScript(getDefault(Category.DISPLAY)); 1854 } 1855 1856 /** 1857 * Returns a name for the locale's script that is appropriate 1858 * for display to the user. If possible, the name will be 1859 * localized for the given locale. Returns the empty string if 1860 * this locale doesn't specify a script code. 1861 * 1862 * @param inLocale The locale for which to retrieve the display script. 1863 * @return the display name of the script code for the current default 1864 * {@link Locale.Category#DISPLAY DISPLAY} locale 1865 * @throws NullPointerException if <code>inLocale</code> is <code>null</code> 1866 * @since 1.7 1867 */ 1868 public String getDisplayScript(Locale inLocale) { 1869 return getDisplayString(baseLocale.getScript(), null, inLocale, DISPLAY_SCRIPT); 1870 } 1871 1872 /** 1873 * Returns a name for the locale's country that is appropriate for display to the 1874 * user. 1875 * If possible, the name returned will be localized for the default 1876 * {@link Locale.Category#DISPLAY DISPLAY} locale. 1877 * For example, if the locale is fr_FR and the default 1878 * {@link Locale.Category#DISPLAY DISPLAY} locale 1879 * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and 1880 * the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR, 1881 * getDisplayCountry() will return "Etats-Unis". 1882 * If the name returned cannot be localized for the default 1883 * {@link Locale.Category#DISPLAY DISPLAY} locale, 1884 * (say, we don't have a Japanese name for Croatia), 1885 * this function falls back on the English name, and uses the ISO code as a last-resort 1886 * value. If the locale doesn't specify a country, this function returns the empty string. 1887 * 1888 * @return The name of the country appropriate to the locale. 1889 */ 1890 public final String getDisplayCountry() { 1891 return getDisplayCountry(getDefault(Category.DISPLAY)); 1892 } 1893 1894 /** 1895 * Returns a name for the locale's country that is appropriate for display to the 1896 * user. 1897 * If possible, the name returned will be localized according to inLocale. 1898 * For example, if the locale is fr_FR and inLocale 1899 * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and 1900 * inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis". 1901 * If the name returned cannot be localized according to inLocale. 1902 * (say, we don't have a Japanese name for Croatia), 1903 * this function falls back on the English name, and finally 1904 * on the ISO code as a last-resort value. If the locale doesn't specify a country, 1905 * this function returns the empty string. 1906 * 1907 * @param inLocale The locale for which to retrieve the display country. 1908 * @return The name of the country appropriate to the given locale. 1909 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1910 */ 1911 public String getDisplayCountry(Locale inLocale) { 1912 return getDisplayString(baseLocale.getRegion(), null, inLocale, DISPLAY_COUNTRY); 1913 } 1914 1915 private String getDisplayString(String code, String cat, Locale inLocale, int type) { 1916 Objects.requireNonNull(inLocale); 1917 Objects.requireNonNull(code); 1918 1919 if (code.isEmpty()) { 1920 return ""; 1921 } 1922 1923 LocaleServiceProviderPool pool = 1924 LocaleServiceProviderPool.getPool(LocaleNameProvider.class); 1925 String rbKey = (type == DISPLAY_VARIANT ? "%%"+code : code); 1926 String result = pool.getLocalizedObject( 1927 LocaleNameGetter.INSTANCE, 1928 inLocale, rbKey, type, code, cat); 1929 return result != null ? result : code; 1930 } 1931 1932 /** 1933 * Returns a name for the locale's variant code that is appropriate for display to the 1934 * user. If possible, the name will be localized for the default 1935 * {@link Locale.Category#DISPLAY DISPLAY} locale. If the locale 1936 * doesn't specify a variant code, this function returns the empty string. 1937 * 1938 * @return The name of the display variant code appropriate to the locale. 1939 */ 1940 public final String getDisplayVariant() { 1941 return getDisplayVariant(getDefault(Category.DISPLAY)); 1942 } 1943 1944 /** 1945 * Returns a name for the locale's variant code that is appropriate for display to the 1946 * user. If possible, the name will be localized for inLocale. If the locale 1947 * doesn't specify a variant code, this function returns the empty string. 1948 * 1949 * @param inLocale The locale for which to retrieve the display variant code. 1950 * @return The name of the display variant code appropriate to the given locale. 1951 * @exception NullPointerException if <code>inLocale</code> is <code>null</code> 1952 */ 1953 public String getDisplayVariant(Locale inLocale) { 1954 if (baseLocale.getVariant().isEmpty()) 1955 return ""; 1956 1957 LocaleResources lr = LocaleProviderAdapter 1958 .getResourceBundleBased() 1959 .getLocaleResources(inLocale); 1960 1961 String names[] = getDisplayVariantArray(inLocale); 1962 1963 // Get the localized patterns for formatting a list, and use 1964 // them to format the list. 1965 return formatList(names, 1966 lr.getLocaleName("ListCompositionPattern")); 1967 } 1968 1969 /** 1970 * Returns a name for the locale that is appropriate for display to the 1971 * user. This will be the values returned by getDisplayLanguage(), 1972 * getDisplayScript(), getDisplayCountry(), getDisplayVariant() and 1973 * optional <a href="./Locale.html#def_locale_extension">Unicode extensions</a> 1974 * assembled into a single string. The non-empty values are used in order, with 1975 * the second and subsequent names in parentheses. For example: 1976 * <blockquote> 1977 * language (script, country, variant(, extension)*)<br> 1978 * language (country(, extension)*)<br> 1979 * language (variant(, extension)*)<br> 1980 * script (country(, extension)*)<br> 1981 * country (extension)*<br> 1982 * </blockquote> 1983 * depending on which fields are specified in the locale. The field 1984 * separator in the above parentheses, denoted as a comma character, may 1985 * be localized depending on the locale. If the language, script, country, 1986 * and variant fields are all empty, this function returns the empty string. 1987 * 1988 * @return The name of the locale appropriate to display. 1989 */ 1990 public final String getDisplayName() { 1991 return getDisplayName(getDefault(Category.DISPLAY)); 1992 } 1993 1994 /** 1995 * Returns a name for the locale that is appropriate for display 1996 * to the user. This will be the values returned by 1997 * getDisplayLanguage(), getDisplayScript(),getDisplayCountry() 1998 * getDisplayVariant(), and optional <a href="./Locale.html#def_locale_extension"> 1999 * Unicode extensions</a> assembled into a single string. The non-empty 2000 * values are used in order, with the second and subsequent names in 2001 * parentheses. For example: 2002 * <blockquote> 2003 * language (script, country, variant(, extension)*)<br> 2004 * language (country(, extension)*)<br> 2005 * language (variant(, extension)*)<br> 2006 * script (country(, extension)*)<br> 2007 * country (extension)*<br> 2008 * </blockquote> 2009 * depending on which fields are specified in the locale. The field 2010 * separator in the above parentheses, denoted as a comma character, may 2011 * be localized depending on the locale. If the language, script, country, 2012 * and variant fields are all empty, this function returns the empty string. 2013 * 2014 * @param inLocale The locale for which to retrieve the display name. 2015 * @return The name of the locale appropriate to display. 2016 * @throws NullPointerException if <code>inLocale</code> is <code>null</code> 2017 */ 2018 public String getDisplayName(Locale inLocale) { 2019 LocaleResources lr = LocaleProviderAdapter 2020 .getResourceBundleBased() 2021 .getLocaleResources(inLocale); 2022 2023 String languageName = getDisplayLanguage(inLocale); 2024 String scriptName = getDisplayScript(inLocale); 2025 String countryName = getDisplayCountry(inLocale); 2026 String[] variantNames = getDisplayVariantArray(inLocale); 2027 2028 // Get the localized patterns for formatting a display name. 2029 String displayNamePattern = lr.getLocaleName("DisplayNamePattern"); 2030 String listCompositionPattern = lr.getLocaleName("ListCompositionPattern"); 2031 2032 // The display name consists of a main name, followed by qualifiers. 2033 // Typically, the format is "MainName (Qualifier, Qualifier)" but this 2034 // depends on what pattern is stored in the display locale. 2035 String mainName; 2036 String[] qualifierNames; 2037 2038 // The main name is the language, or if there is no language, the script, 2039 // then if no script, the country. If there is no language/script/country 2040 // (an anomalous situation) then the display name is simply the variant's 2041 // display name. 2042 if (languageName.isEmpty() && scriptName.isEmpty() && countryName.isEmpty()) { 2043 if (variantNames.length == 0) { 2044 return ""; 2045 } else { 2046 return formatList(variantNames, listCompositionPattern); 2047 } 2048 } 2049 ArrayList<String> names = new ArrayList<>(4); 2050 if (!languageName.isEmpty()) { 2051 names.add(languageName); 2052 } 2053 if (!scriptName.isEmpty()) { 2054 names.add(scriptName); 2055 } 2056 if (!countryName.isEmpty()) { 2057 names.add(countryName); 2058 } 2059 if (variantNames.length != 0) { 2060 names.addAll(Arrays.asList(variantNames)); 2061 } 2062 2063 // add Unicode extensions 2064 if (localeExtensions != null) { 2065 localeExtensions.getUnicodeLocaleAttributes().stream() 2066 .map(key -> getDisplayString(key, null, inLocale, DISPLAY_UEXT_KEY)) 2067 .forEach(names::add); 2068 localeExtensions.getUnicodeLocaleKeys().stream() 2069 .map(key -> getDisplayKeyTypeExtensionString(key, lr, inLocale)) 2070 .forEach(names::add); 2071 } 2072 2073 // The first one in the main name 2074 mainName = names.get(0); 2075 2076 // Others are qualifiers 2077 int numNames = names.size(); 2078 qualifierNames = (numNames > 1) ? 2079 names.subList(1, numNames).toArray(new String[numNames - 1]) : new String[0]; 2080 2081 // Create an array whose first element is the number of remaining 2082 // elements. This serves as a selector into a ChoiceFormat pattern from 2083 // the resource. The second and third elements are the main name and 2084 // the qualifier; if there are no qualifiers, the third element is 2085 // unused by the format pattern. 2086 Object[] displayNames = { 2087 qualifierNames.length != 0 ? 2 : 1, 2088 mainName, 2089 // We could also just call formatList() and have it handle the empty 2090 // list case, but this is more efficient, and we want it to be 2091 // efficient since all the language-only locales will not have any 2092 // qualifiers. 2093 qualifierNames.length != 0 ? formatList(qualifierNames, listCompositionPattern) : null 2094 }; 2095 2096 if (displayNamePattern != null) { 2097 return new MessageFormat(displayNamePattern).format(displayNames); 2098 } 2099 else { 2100 // If we cannot get the message format pattern, then we use a simple 2101 // hard-coded pattern. This should not occur in practice unless the 2102 // installation is missing some core files (FormatData etc.). 2103 StringBuilder result = new StringBuilder(); 2104 result.append((String)displayNames[1]); 2105 if (displayNames.length > 2) { 2106 result.append(" ("); 2107 result.append((String)displayNames[2]); 2108 result.append(')'); 2109 } 2110 return result.toString(); 2111 } 2112 } 2113 2114 /** 2115 * Overrides Cloneable. 2116 */ 2117 @Override 2118 public Object clone() 2119 { 2120 try { 2121 Locale that = (Locale)super.clone(); 2122 return that; 2123 } catch (CloneNotSupportedException e) { 2124 throw new InternalError(e); 2125 } 2126 } 2127 2128 /** 2129 * Override hashCode. 2130 * Since Locales are often used in hashtables, caches the value 2131 * for speed. 2132 */ 2133 @Override 2134 public int hashCode() { 2135 int hc = hashCodeValue; 2136 if (hc == 0) { 2137 hc = baseLocale.hashCode(); 2138 if (localeExtensions != null) { 2139 hc ^= localeExtensions.hashCode(); 2140 } 2141 hashCodeValue = hc; 2142 } 2143 return hc; 2144 } 2145 2146 // Overrides 2147 2148 /** 2149 * Returns true if this Locale is equal to another object. A Locale is 2150 * deemed equal to another Locale with identical language, script, country, 2151 * variant and extensions, and unequal to all other objects. 2152 * 2153 * @return true if this Locale is equal to the specified object. 2154 */ 2155 @Override 2156 public boolean equals(Object obj) { 2157 if (this == obj) // quick check 2158 return true; 2159 if (!(obj instanceof Locale)) 2160 return false; 2161 BaseLocale otherBase = ((Locale)obj).baseLocale; 2162 if (!baseLocale.equals(otherBase)) { 2163 return false; 2164 } 2165 if (localeExtensions == null) { 2166 return ((Locale)obj).localeExtensions == null; 2167 } 2168 return localeExtensions.equals(((Locale)obj).localeExtensions); 2169 } 2170 2171 // ================= privates ===================================== 2172 2173 private transient BaseLocale baseLocale; 2174 private transient LocaleExtensions localeExtensions; 2175 2176 /** 2177 * Calculated hashcode 2178 */ 2179 private transient volatile int hashCodeValue; 2180 2181 private static volatile Locale defaultLocale = initDefault(); 2182 private static volatile Locale defaultDisplayLocale; 2183 private static volatile Locale defaultFormatLocale; 2184 2185 private transient volatile String languageTag; 2186 2187 /** 2188 * Return an array of the display names of the variant. 2189 * @param bundle the ResourceBundle to use to get the display names 2190 * @return an array of display names, possible of zero length. 2191 */ 2192 private String[] getDisplayVariantArray(Locale inLocale) { 2193 // Split the variant name into tokens separated by '_'. 2194 StringTokenizer tokenizer = new StringTokenizer(baseLocale.getVariant(), "_"); 2195 String[] names = new String[tokenizer.countTokens()]; 2196 2197 // For each variant token, lookup the display name. If 2198 // not found, use the variant name itself. 2199 for (int i=0; i<names.length; ++i) { 2200 names[i] = getDisplayString(tokenizer.nextToken(), null, 2201 inLocale, DISPLAY_VARIANT); 2202 } 2203 2204 return names; 2205 } 2206 2207 private String getDisplayKeyTypeExtensionString(String key, LocaleResources lr, Locale inLocale) { 2208 String type = localeExtensions.getUnicodeLocaleType(key); 2209 String ret = getDisplayString(type, key, inLocale, DISPLAY_UEXT_TYPE); 2210 2211 if (ret == null || ret.equals(type)) { 2212 // no localization for this type. try combining key/type separately 2213 String displayType = type; 2214 switch (key) { 2215 case "cu": 2216 displayType = lr.getCurrencyName(type.toLowerCase(Locale.ROOT)); 2217 break; 2218 case "rg": 2219 if (type != null && 2220 // UN M.49 code should not be allowed here 2221 type.matches("^[a-zA-Z]{2}[zZ]{4}$")) { 2222 displayType = lr.getLocaleName(type.substring(0, 2).toUpperCase(Locale.ROOT)); 2223 } 2224 break; 2225 case "tz": 2226 displayType = TimeZoneNameUtility.convertLDMLShortID(type) 2227 .map(id -> TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, inLocale)) 2228 .orElse(type); 2229 break; 2230 } 2231 ret = MessageFormat.format(lr.getLocaleName("ListKeyTypePattern"), 2232 getDisplayString(key, null, inLocale, DISPLAY_UEXT_KEY), 2233 Optional.ofNullable(displayType).orElse(type)); 2234 } 2235 2236 return ret; 2237 } 2238 2239 /** 2240 * Format a list using given pattern strings. 2241 * If either of the patterns is null, then a the list is 2242 * formatted by concatenation with the delimiter ','. 2243 * @param stringList the list of strings to be formatted. 2244 * and formatting them into a list. 2245 * @param pattern should take 2 arguments for reduction 2246 * @return a string representing the list. 2247 */ 2248 private static String formatList(String[] stringList, String pattern) { 2249 // If we have no list patterns, compose the list in a simple, 2250 // non-localized way. 2251 if (pattern == null) { 2252 return Arrays.stream(stringList).collect(Collectors.joining(",")); 2253 } 2254 2255 switch (stringList.length) { 2256 case 0: 2257 return ""; 2258 case 1: 2259 return stringList[0]; 2260 default: 2261 return Arrays.stream(stringList).reduce("", 2262 (s1, s2) -> { 2263 if (s1.isEmpty()) { 2264 return s2; 2265 } 2266 if (s2.isEmpty()) { 2267 return s1; 2268 } 2269 return MessageFormat.format(pattern, s1, s2); 2270 }); 2271 } 2272 } 2273 2274 // Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to 2275 // avoid its class loading. 2276 private static boolean isUnicodeExtensionKey(String s) { 2277 // 2alphanum 2278 return (s.length() == 2) && LocaleUtils.isAlphaNumericString(s); 2279 } 2280 2281 /** 2282 * @serialField language String 2283 * language subtag in lower case. 2284 * (See <a href="java.base/java/util/Locale.html#getLanguage()">getLanguage()</a>) 2285 * @serialField country String 2286 * country subtag in upper case. 2287 * (See <a href="java.base/java/util/Locale.html#getCountry()">getCountry()</a>) 2288 * @serialField variant String 2289 * variant subtags separated by LOWLINE characters. 2290 * (See <a href="java.base/java/util/Locale.html#getVariant()">getVariant()</a>) 2291 * @serialField hashcode int 2292 * deprecated, for forward compatibility only 2293 * @serialField script String 2294 * script subtag in title case 2295 * (See <a href="java.base/java/util/Locale.html#getScript()">getScript()</a>) 2296 * @serialField extensions String 2297 * canonical representation of extensions, that is, 2298 * BCP47 extensions in alphabetical order followed by 2299 * BCP47 private use subtags, all in lower case letters 2300 * separated by HYPHEN-MINUS characters. 2301 * (See <a href="java.base/java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>, 2302 * <a href="java.base/java/util/Locale.html#getExtension(char)">getExtension(char)</a>) 2303 */ 2304 private static final ObjectStreamField[] serialPersistentFields = { 2305 new ObjectStreamField("language", String.class), 2306 new ObjectStreamField("country", String.class), 2307 new ObjectStreamField("variant", String.class), 2308 new ObjectStreamField("hashcode", int.class), 2309 new ObjectStreamField("script", String.class), 2310 new ObjectStreamField("extensions", String.class), 2311 }; 2312 2313 /** 2314 * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>. 2315 * @param out the <code>ObjectOutputStream</code> to write 2316 * @throws IOException 2317 * @since 1.7 2318 */ 2319 private void writeObject(ObjectOutputStream out) throws IOException { 2320 ObjectOutputStream.PutField fields = out.putFields(); 2321 fields.put("language", baseLocale.getLanguage()); 2322 fields.put("script", baseLocale.getScript()); 2323 fields.put("country", baseLocale.getRegion()); 2324 fields.put("variant", baseLocale.getVariant()); 2325 fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID()); 2326 fields.put("hashcode", -1); // place holder just for backward support 2327 out.writeFields(); 2328 } 2329 2330 /** 2331 * Deserializes this <code>Locale</code>. 2332 * @param in the <code>ObjectInputStream</code> to read 2333 * @throws IOException 2334 * @throws ClassNotFoundException 2335 * @throws IllformedLocaleException 2336 * @since 1.7 2337 */ 2338 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 2339 ObjectInputStream.GetField fields = in.readFields(); 2340 String language = (String)fields.get("language", ""); 2341 String script = (String)fields.get("script", ""); 2342 String country = (String)fields.get("country", ""); 2343 String variant = (String)fields.get("variant", ""); 2344 String extStr = (String)fields.get("extensions", ""); 2345 2346 baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant); 2347 if (!extStr.isEmpty()) { 2348 try { 2349 InternalLocaleBuilder bldr = new InternalLocaleBuilder(); 2350 bldr.setExtensions(extStr); 2351 localeExtensions = bldr.getLocaleExtensions(); 2352 } catch (LocaleSyntaxException e) { 2353 throw new IllformedLocaleException(e.getMessage()); 2354 } 2355 } else { 2356 localeExtensions = null; 2357 } 2358 } 2359 2360 /** 2361 * Returns a cached <code>Locale</code> instance equivalent to 2362 * the deserialized <code>Locale</code>. When serialized 2363 * language, country and variant fields read from the object data stream 2364 * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions 2365 * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code> 2366 * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script 2367 * type is "thai"). See <a href="Locale.html#special_cases_constructor">Special Cases</a> 2368 * for more information. 2369 * 2370 * @return an instance of <code>Locale</code> equivalent to 2371 * the deserialized <code>Locale</code>. 2372 * @throws java.io.ObjectStreamException 2373 */ 2374 private Object readResolve() throws java.io.ObjectStreamException { 2375 return getInstance(baseLocale.getLanguage(), baseLocale.getScript(), 2376 baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions); 2377 } 2378 2379 private static volatile String[] isoLanguages; 2380 2381 private static volatile String[] isoCountries; 2382 2383 private static String convertOldISOCodes(String language) { 2384 // we accept both the old and the new ISO codes for the languages whose ISO 2385 // codes have changed, but we always store the OLD code, for backward compatibility 2386 language = LocaleUtils.toLowerString(language).intern(); 2387 if (language == "he") { 2388 return "iw"; 2389 } else if (language == "yi") { 2390 return "ji"; 2391 } else if (language == "id") { 2392 return "in"; 2393 } else { 2394 return language; 2395 } 2396 } 2397 2398 private static LocaleExtensions getCompatibilityExtensions(String language, 2399 String script, 2400 String country, 2401 String variant) { 2402 LocaleExtensions extensions = null; 2403 // Special cases for backward compatibility support 2404 if (LocaleUtils.caseIgnoreMatch(language, "ja") 2405 && script.isEmpty() 2406 && LocaleUtils.caseIgnoreMatch(country, "jp") 2407 && "JP".equals(variant)) { 2408 // ja_JP_JP -> u-ca-japanese (calendar = japanese) 2409 extensions = LocaleExtensions.CALENDAR_JAPANESE; 2410 } else if (LocaleUtils.caseIgnoreMatch(language, "th") 2411 && script.isEmpty() 2412 && LocaleUtils.caseIgnoreMatch(country, "th") 2413 && "TH".equals(variant)) { 2414 // th_TH_TH -> u-nu-thai (numbersystem = thai) 2415 extensions = LocaleExtensions.NUMBER_THAI; 2416 } 2417 return extensions; 2418 } 2419 2420 /** 2421 * Obtains a localized locale names from a LocaleNameProvider 2422 * implementation. 2423 */ 2424 private static class LocaleNameGetter 2425 implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> { 2426 private static final LocaleNameGetter INSTANCE = new LocaleNameGetter(); 2427 2428 @Override 2429 public String getObject(LocaleNameProvider localeNameProvider, 2430 Locale locale, 2431 String key, 2432 Object... params) { 2433 assert params.length == 3; 2434 int type = (Integer)params[0]; 2435 String code = (String)params[1]; 2436 String cat = (String)params[2]; 2437 2438 switch(type) { 2439 case DISPLAY_LANGUAGE: 2440 return localeNameProvider.getDisplayLanguage(code, locale); 2441 case DISPLAY_COUNTRY: 2442 return localeNameProvider.getDisplayCountry(code, locale); 2443 case DISPLAY_VARIANT: 2444 return localeNameProvider.getDisplayVariant(code, locale); 2445 case DISPLAY_SCRIPT: 2446 return localeNameProvider.getDisplayScript(code, locale); 2447 case DISPLAY_UEXT_KEY: 2448 return localeNameProvider.getDisplayUnicodeExtensionKey(code, locale); 2449 case DISPLAY_UEXT_TYPE: 2450 return localeNameProvider.getDisplayUnicodeExtensionType(code, cat, locale); 2451 default: 2452 assert false; // shouldn't happen 2453 } 2454 2455 return null; 2456 } 2457 } 2458 2459 /** 2460 * Enum for locale categories. These locale categories are used to get/set 2461 * the default locale for the specific functionality represented by the 2462 * category. 2463 * 2464 * @see #getDefault(Locale.Category) 2465 * @see #setDefault(Locale.Category, Locale) 2466 * @since 1.7 2467 */ 2468 public enum Category { 2469 2470 /** 2471 * Category used to represent the default locale for 2472 * displaying user interfaces. 2473 */ 2474 DISPLAY("user.language.display", 2475 "user.script.display", 2476 "user.country.display", 2477 "user.variant.display", 2478 "user.extensions.display"), 2479 2480 /** 2481 * Category used to represent the default locale for 2482 * formatting dates, numbers, and/or currencies. 2483 */ 2484 FORMAT("user.language.format", 2485 "user.script.format", 2486 "user.country.format", 2487 "user.variant.format", 2488 "user.extensions.format"); 2489 2490 Category(String languageKey, String scriptKey, String countryKey, 2491 String variantKey, String extensionsKey) { 2492 this.languageKey = languageKey; 2493 this.scriptKey = scriptKey; 2494 this.countryKey = countryKey; 2495 this.variantKey = variantKey; 2496 this.extensionsKey = extensionsKey; 2497 } 2498 2499 final String languageKey; 2500 final String scriptKey; 2501 final String countryKey; 2502 final String variantKey; 2503 final String extensionsKey; 2504 } 2505 2506 /** 2507 * <code>Builder</code> is used to build instances of <code>Locale</code> 2508 * from values configured by the setters. Unlike the <code>Locale</code> 2509 * constructors, the <code>Builder</code> checks if a value configured by a 2510 * setter satisfies the syntax requirements defined by the <code>Locale</code> 2511 * class. A <code>Locale</code> object created by a <code>Builder</code> is 2512 * well-formed and can be transformed to a well-formed IETF BCP 47 language tag 2513 * without losing information. 2514 * 2515 * <p><b>Note:</b> The <code>Locale</code> class does not provide any 2516 * syntactic restrictions on variant, while BCP 47 requires each variant 2517 * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3 2518 * alphanumerics. The method <code>setVariant</code> throws 2519 * <code>IllformedLocaleException</code> for a variant that does not satisfy 2520 * this restriction. If it is necessary to support such a variant, use a 2521 * Locale constructor. However, keep in mind that a <code>Locale</code> 2522 * object created this way might lose the variant information when 2523 * transformed to a BCP 47 language tag. 2524 * 2525 * <p>The following example shows how to create a <code>Locale</code> object 2526 * with the <code>Builder</code>. 2527 * <blockquote> 2528 * <pre> 2529 * Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build(); 2530 * </pre> 2531 * </blockquote> 2532 * 2533 * <p>Builders can be reused; <code>clear()</code> resets all 2534 * fields to their default values. 2535 * 2536 * @see Locale#forLanguageTag 2537 * @since 1.7 2538 */ 2539 public static final class Builder { 2540 private final InternalLocaleBuilder localeBuilder; 2541 2542 /** 2543 * Constructs an empty Builder. The default value of all 2544 * fields, extensions, and private use information is the 2545 * empty string. 2546 */ 2547 public Builder() { 2548 localeBuilder = new InternalLocaleBuilder(); 2549 } 2550 2551 /** 2552 * Resets the <code>Builder</code> to match the provided 2553 * <code>locale</code>. Existing state is discarded. 2554 * 2555 * <p>All fields of the locale must be well-formed, see {@link Locale}. 2556 * 2557 * <p>Locales with any ill-formed fields cause 2558 * <code>IllformedLocaleException</code> to be thrown, except for the 2559 * following three cases which are accepted for compatibility 2560 * reasons:<ul> 2561 * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese" 2562 * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai" 2563 * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul> 2564 * 2565 * @param locale the locale 2566 * @return This builder. 2567 * @throws IllformedLocaleException if <code>locale</code> has 2568 * any ill-formed fields. 2569 * @throws NullPointerException if <code>locale</code> is null. 2570 */ 2571 public Builder setLocale(Locale locale) { 2572 try { 2573 localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions); 2574 } catch (LocaleSyntaxException e) { 2575 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2576 } 2577 return this; 2578 } 2579 2580 /** 2581 * Resets the Builder to match the provided IETF BCP 47 2582 * language tag. Discards the existing state. Null and the 2583 * empty string cause the builder to be reset, like {@link 2584 * #clear}. Grandfathered tags (see {@link 2585 * Locale#forLanguageTag}) are converted to their canonical 2586 * form before being processed. Otherwise, the language tag 2587 * must be well-formed (see {@link Locale}) or an exception is 2588 * thrown (unlike <code>Locale.forLanguageTag</code>, which 2589 * just discards ill-formed and following portions of the 2590 * tag). 2591 * 2592 * @param languageTag the language tag 2593 * @return This builder. 2594 * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed 2595 * @see Locale#forLanguageTag(String) 2596 */ 2597 public Builder setLanguageTag(String languageTag) { 2598 ParseStatus sts = new ParseStatus(); 2599 LanguageTag tag = LanguageTag.parse(languageTag, sts); 2600 if (sts.isError()) { 2601 throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex()); 2602 } 2603 localeBuilder.setLanguageTag(tag); 2604 return this; 2605 } 2606 2607 /** 2608 * Sets the language. If <code>language</code> is the empty string or 2609 * null, the language in this <code>Builder</code> is removed. Otherwise, 2610 * the language must be <a href="./Locale.html#def_language">well-formed</a> 2611 * or an exception is thrown. 2612 * 2613 * <p>The typical language value is a two or three-letter language 2614 * code as defined in ISO639. 2615 * 2616 * @param language the language 2617 * @return This builder. 2618 * @throws IllformedLocaleException if <code>language</code> is ill-formed 2619 */ 2620 public Builder setLanguage(String language) { 2621 try { 2622 localeBuilder.setLanguage(language); 2623 } catch (LocaleSyntaxException e) { 2624 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2625 } 2626 return this; 2627 } 2628 2629 /** 2630 * Sets the script. If <code>script</code> is null or the empty string, 2631 * the script in this <code>Builder</code> is removed. 2632 * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an 2633 * exception is thrown. 2634 * 2635 * <p>The typical script value is a four-letter script code as defined by ISO 15924. 2636 * 2637 * @param script the script 2638 * @return This builder. 2639 * @throws IllformedLocaleException if <code>script</code> is ill-formed 2640 */ 2641 public Builder setScript(String script) { 2642 try { 2643 localeBuilder.setScript(script); 2644 } catch (LocaleSyntaxException e) { 2645 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2646 } 2647 return this; 2648 } 2649 2650 /** 2651 * Sets the region. If region is null or the empty string, the region 2652 * in this <code>Builder</code> is removed. Otherwise, 2653 * the region must be <a href="./Locale.html#def_region">well-formed</a> or an 2654 * exception is thrown. 2655 * 2656 * <p>The typical region value is a two-letter ISO 3166 code or a 2657 * three-digit UN M.49 area code. 2658 * 2659 * <p>The country value in the <code>Locale</code> created by the 2660 * <code>Builder</code> is always normalized to upper case. 2661 * 2662 * @param region the region 2663 * @return This builder. 2664 * @throws IllformedLocaleException if <code>region</code> is ill-formed 2665 */ 2666 public Builder setRegion(String region) { 2667 try { 2668 localeBuilder.setRegion(region); 2669 } catch (LocaleSyntaxException e) { 2670 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2671 } 2672 return this; 2673 } 2674 2675 /** 2676 * Sets the variant. If variant is null or the empty string, the 2677 * variant in this <code>Builder</code> is removed. Otherwise, it 2678 * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a> 2679 * subtags, or an exception is thrown. 2680 * 2681 * <p><b>Note:</b> This method checks if <code>variant</code> 2682 * satisfies the IETF BCP 47 variant subtag's syntax requirements, 2683 * and normalizes the value to lowercase letters. However, 2684 * the <code>Locale</code> class does not impose any syntactic 2685 * restriction on variant, and the variant value in 2686 * <code>Locale</code> is case sensitive. To set such a variant, 2687 * use a Locale constructor. 2688 * 2689 * @param variant the variant 2690 * @return This builder. 2691 * @throws IllformedLocaleException if <code>variant</code> is ill-formed 2692 */ 2693 public Builder setVariant(String variant) { 2694 try { 2695 localeBuilder.setVariant(variant); 2696 } catch (LocaleSyntaxException e) { 2697 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2698 } 2699 return this; 2700 } 2701 2702 /** 2703 * Sets the extension for the given key. If the value is null or the 2704 * empty string, the extension is removed. Otherwise, the extension 2705 * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception 2706 * is thrown. 2707 * 2708 * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION 2709 * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension. 2710 * Setting a value for this key replaces any existing Unicode locale key/type 2711 * pairs with those defined in the extension. 2712 * 2713 * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION 2714 * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be 2715 * well-formed, the value for this key needs only to have subtags of one to 2716 * eight alphanumeric characters, not two to eight as in the general case. 2717 * 2718 * @param key the extension key 2719 * @param value the extension value 2720 * @return This builder. 2721 * @throws IllformedLocaleException if <code>key</code> is illegal 2722 * or <code>value</code> is ill-formed 2723 * @see #setUnicodeLocaleKeyword(String, String) 2724 */ 2725 public Builder setExtension(char key, String value) { 2726 try { 2727 localeBuilder.setExtension(key, value); 2728 } catch (LocaleSyntaxException e) { 2729 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2730 } 2731 return this; 2732 } 2733 2734 /** 2735 * Sets the Unicode locale keyword type for the given key. If the type 2736 * is null, the Unicode keyword is removed. Otherwise, the key must be 2737 * non-null and both key and type must be <a 2738 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2739 * is thrown. 2740 * 2741 * <p>Keys and types are converted to lower case. 2742 * 2743 * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension} 2744 * replaces all Unicode locale keywords with those defined in the 2745 * extension. 2746 * 2747 * @param key the Unicode locale key 2748 * @param type the Unicode locale type 2749 * @return This builder. 2750 * @throws IllformedLocaleException if <code>key</code> or <code>type</code> 2751 * is ill-formed 2752 * @throws NullPointerException if <code>key</code> is null 2753 * @see #setExtension(char, String) 2754 */ 2755 public Builder setUnicodeLocaleKeyword(String key, String type) { 2756 try { 2757 localeBuilder.setUnicodeLocaleKeyword(key, type); 2758 } catch (LocaleSyntaxException e) { 2759 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2760 } 2761 return this; 2762 } 2763 2764 /** 2765 * Adds a unicode locale attribute, if not already present, otherwise 2766 * has no effect. The attribute must not be null and must be <a 2767 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2768 * is thrown. 2769 * 2770 * @param attribute the attribute 2771 * @return This builder. 2772 * @throws NullPointerException if <code>attribute</code> is null 2773 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2774 * @see #setExtension(char, String) 2775 */ 2776 public Builder addUnicodeLocaleAttribute(String attribute) { 2777 try { 2778 localeBuilder.addUnicodeLocaleAttribute(attribute); 2779 } catch (LocaleSyntaxException e) { 2780 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2781 } 2782 return this; 2783 } 2784 2785 /** 2786 * Removes a unicode locale attribute, if present, otherwise has no 2787 * effect. The attribute must not be null and must be <a 2788 * href="./Locale.html#def_locale_extension">well-formed</a> or an exception 2789 * is thrown. 2790 * 2791 * <p>Attribute comparison for removal is case-insensitive. 2792 * 2793 * @param attribute the attribute 2794 * @return This builder. 2795 * @throws NullPointerException if <code>attribute</code> is null 2796 * @throws IllformedLocaleException if <code>attribute</code> is ill-formed 2797 * @see #setExtension(char, String) 2798 */ 2799 public Builder removeUnicodeLocaleAttribute(String attribute) { 2800 Objects.requireNonNull(attribute); 2801 try { 2802 localeBuilder.removeUnicodeLocaleAttribute(attribute); 2803 } catch (LocaleSyntaxException e) { 2804 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex()); 2805 } 2806 return this; 2807 } 2808 2809 /** 2810 * Resets the builder to its initial, empty state. 2811 * 2812 * @return This builder. 2813 */ 2814 public Builder clear() { 2815 localeBuilder.clear(); 2816 return this; 2817 } 2818 2819 /** 2820 * Resets the extensions to their initial, empty state. 2821 * Language, script, region and variant are unchanged. 2822 * 2823 * @return This builder. 2824 * @see #setExtension(char, String) 2825 */ 2826 public Builder clearExtensions() { 2827 localeBuilder.clearExtensions(); 2828 return this; 2829 } 2830 2831 /** 2832 * Returns an instance of <code>Locale</code> created from the fields set 2833 * on this builder. 2834 * 2835 * <p>This applies the conversions listed in {@link Locale#forLanguageTag} 2836 * when constructing a Locale. (Grandfathered tags are handled in 2837 * {@link #setLanguageTag}.) 2838 * 2839 * @return A Locale. 2840 */ 2841 public Locale build() { 2842 BaseLocale baseloc = localeBuilder.getBaseLocale(); 2843 LocaleExtensions extensions = localeBuilder.getLocaleExtensions(); 2844 if (extensions == null && !baseloc.getVariant().isEmpty()) { 2845 extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(), 2846 baseloc.getRegion(), baseloc.getVariant()); 2847 } 2848 return Locale.getInstance(baseloc, extensions); 2849 } 2850 } 2851 2852 /** 2853 * This enum provides constants to select a filtering mode for locale 2854 * matching. Refer to <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 2855 * Matching of Language Tags</a> for details. 2856 * 2857 * <p>As an example, think of two Language Priority Lists each of which 2858 * includes only one language range and a set of following language tags: 2859 * 2860 * <pre> 2861 * de (German) 2862 * de-DE (German, Germany) 2863 * de-Deva (German, in Devanagari script) 2864 * de-Deva-DE (German, in Devanagari script, Germany) 2865 * de-DE-1996 (German, Germany, orthography of 1996) 2866 * de-Latn-DE (German, in Latin script, Germany) 2867 * de-Latn-DE-1996 (German, in Latin script, Germany, orthography of 1996) 2868 * </pre> 2869 * 2870 * The filtering method will behave as follows: 2871 * 2872 * <table class="striped"> 2873 * <caption>Filtering method behavior</caption> 2874 * <thead> 2875 * <tr> 2876 * <th scope="col">Filtering Mode</th> 2877 * <th scope="col">Language Priority List: {@code "de-DE"}</th> 2878 * <th scope="col">Language Priority List: {@code "de-*-DE"}</th> 2879 * </tr> 2880 * </thead> 2881 * <tbody> 2882 * <tr> 2883 * <th scope="row" style="vertical-align:top"> 2884 * {@link FilteringMode#AUTOSELECT_FILTERING AUTOSELECT_FILTERING} 2885 * </th> 2886 * <td style="vertical-align:top"> 2887 * Performs <em>basic</em> filtering and returns {@code "de-DE"} and 2888 * {@code "de-DE-1996"}. 2889 * </td> 2890 * <td style="vertical-align:top"> 2891 * Performs <em>extended</em> filtering and returns {@code "de-DE"}, 2892 * {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and 2893 * {@code "de-Latn-DE-1996"}. 2894 * </td> 2895 * </tr> 2896 * <tr> 2897 * <th scope="row" style="vertical-align:top"> 2898 * {@link FilteringMode#EXTENDED_FILTERING EXTENDED_FILTERING} 2899 * </th> 2900 * <td style="vertical-align:top"> 2901 * Performs <em>extended</em> filtering and returns {@code "de-DE"}, 2902 * {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and 2903 * {@code "de-Latn-DE-1996"}. 2904 * </td> 2905 * <td style="vertical-align:top">Same as above.</td> 2906 * </tr> 2907 * <tr> 2908 * <th scope="row" style="vertical-align:top"> 2909 * {@link FilteringMode#IGNORE_EXTENDED_RANGES IGNORE_EXTENDED_RANGES} 2910 * </th> 2911 * <td style="vertical-align:top"> 2912 * Performs <em>basic</em> filtering and returns {@code "de-DE"} and 2913 * {@code "de-DE-1996"}. 2914 * </td> 2915 * <td style="vertical-align:top"> 2916 * Performs <em>basic</em> filtering and returns {@code null} because 2917 * nothing matches. 2918 * </td> 2919 * </tr> 2920 * <tr> 2921 * <th scope="row" style="vertical-align:top"> 2922 * {@link FilteringMode#MAP_EXTENDED_RANGES MAP_EXTENDED_RANGES} 2923 * </th> 2924 * <td style="vertical-align:top">Same as above.</td> 2925 * <td style="vertical-align:top"> 2926 * Performs <em>basic</em> filtering and returns {@code "de-DE"} and 2927 * {@code "de-DE-1996"} because {@code "de-*-DE"} is mapped to 2928 * {@code "de-DE"}. 2929 * </td> 2930 * </tr> 2931 * <tr> 2932 * <th scope="row" style="vertical-align:top"> 2933 * {@link FilteringMode#REJECT_EXTENDED_RANGES REJECT_EXTENDED_RANGES} 2934 * </th> 2935 * <td style="vertical-align:top">Same as above.</td> 2936 * <td style="vertical-align:top"> 2937 * Throws {@link IllegalArgumentException} because {@code "de-*-DE"} is 2938 * not a valid basic language range. 2939 * </td> 2940 * </tr> 2941 * </tbody> 2942 * </table> 2943 * 2944 * @see #filter(List, Collection, FilteringMode) 2945 * @see #filterTags(List, Collection, FilteringMode) 2946 * 2947 * @since 1.8 2948 */ 2949 public static enum FilteringMode { 2950 /** 2951 * Specifies automatic filtering mode based on the given Language 2952 * Priority List consisting of language ranges. If all of the ranges 2953 * are basic, basic filtering is selected. Otherwise, extended 2954 * filtering is selected. 2955 */ 2956 AUTOSELECT_FILTERING, 2957 2958 /** 2959 * Specifies extended filtering. 2960 */ 2961 EXTENDED_FILTERING, 2962 2963 /** 2964 * Specifies basic filtering: Note that any extended language ranges 2965 * included in the given Language Priority List are ignored. 2966 */ 2967 IGNORE_EXTENDED_RANGES, 2968 2969 /** 2970 * Specifies basic filtering: If any extended language ranges are 2971 * included in the given Language Priority List, they are mapped to the 2972 * basic language range. Specifically, a language range starting with a 2973 * subtag {@code "*"} is treated as a language range {@code "*"}. For 2974 * example, {@code "*-US"} is treated as {@code "*"}. If {@code "*"} is 2975 * not the first subtag, {@code "*"} and extra {@code "-"} are removed. 2976 * For example, {@code "ja-*-JP"} is mapped to {@code "ja-JP"}. 2977 */ 2978 MAP_EXTENDED_RANGES, 2979 2980 /** 2981 * Specifies basic filtering: If any extended language ranges are 2982 * included in the given Language Priority List, the list is rejected 2983 * and the filtering method throws {@link IllegalArgumentException}. 2984 */ 2985 REJECT_EXTENDED_RANGES 2986 }; 2987 2988 /** 2989 * This class expresses a <em>Language Range</em> defined in 2990 * <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 Matching of 2991 * Language Tags</a>. A language range is an identifier which is used to 2992 * select language tag(s) meeting specific requirements by using the 2993 * mechanisms described in <a href="Locale.html#LocaleMatching">Locale 2994 * Matching</a>. A list which represents a user's preferences and consists 2995 * of language ranges is called a <em>Language Priority List</em>. 2996 * 2997 * <p>There are two types of language ranges: basic and extended. In RFC 2998 * 4647, the syntax of language ranges is expressed in 2999 * <a href="http://tools.ietf.org/html/rfc4234">ABNF</a> as follows: 3000 * <blockquote> 3001 * <pre> 3002 * basic-language-range = (1*8ALPHA *("-" 1*8alphanum)) / "*" 3003 * extended-language-range = (1*8ALPHA / "*") 3004 * *("-" (1*8alphanum / "*")) 3005 * alphanum = ALPHA / DIGIT 3006 * </pre> 3007 * </blockquote> 3008 * For example, {@code "en"} (English), {@code "ja-JP"} (Japanese, Japan), 3009 * {@code "*"} (special language range which matches any language tag) are 3010 * basic language ranges, whereas {@code "*-CH"} (any languages, 3011 * Switzerland), {@code "es-*"} (Spanish, any regions), and 3012 * {@code "zh-Hant-*"} (Traditional Chinese, any regions) are extended 3013 * language ranges. 3014 * 3015 * @see #filter 3016 * @see #filterTags 3017 * @see #lookup 3018 * @see #lookupTag 3019 * 3020 * @since 1.8 3021 */ 3022 public static final class LanguageRange { 3023 3024 /** 3025 * A constant holding the maximum value of weight, 1.0, which indicates 3026 * that the language range is a good fit for the user. 3027 */ 3028 public static final double MAX_WEIGHT = 1.0; 3029 3030 /** 3031 * A constant holding the minimum value of weight, 0.0, which indicates 3032 * that the language range is not a good fit for the user. 3033 */ 3034 public static final double MIN_WEIGHT = 0.0; 3035 3036 private final String range; 3037 private final double weight; 3038 3039 private volatile int hash; 3040 3041 /** 3042 * Constructs a {@code LanguageRange} using the given {@code range}. 3043 * Note that no validation is done against the IANA Language Subtag 3044 * Registry at time of construction. 3045 * 3046 * <p>This is equivalent to {@code LanguageRange(range, MAX_WEIGHT)}. 3047 * 3048 * @param range a language range 3049 * @throws NullPointerException if the given {@code range} is 3050 * {@code null} 3051 * @throws IllegalArgumentException if the given {@code range} does not 3052 * comply with the syntax of the language range mentioned in RFC 4647 3053 */ 3054 public LanguageRange(String range) { 3055 this(range, MAX_WEIGHT); 3056 } 3057 3058 /** 3059 * Constructs a {@code LanguageRange} using the given {@code range} and 3060 * {@code weight}. Note that no validation is done against the IANA 3061 * Language Subtag Registry at time of construction. 3062 * 3063 * @param range a language range 3064 * @param weight a weight value between {@code MIN_WEIGHT} and 3065 * {@code MAX_WEIGHT} 3066 * @throws NullPointerException if the given {@code range} is 3067 * {@code null} 3068 * @throws IllegalArgumentException if the given {@code range} does not 3069 * comply with the syntax of the language range mentioned in RFC 4647 3070 * or if the given {@code weight} is less than {@code MIN_WEIGHT} 3071 * or greater than {@code MAX_WEIGHT} 3072 */ 3073 public LanguageRange(String range, double weight) { 3074 if (range == null) { 3075 throw new NullPointerException(); 3076 } 3077 if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) { 3078 throw new IllegalArgumentException("weight=" + weight); 3079 } 3080 3081 range = range.toLowerCase(Locale.ROOT); 3082 3083 // Do syntax check. 3084 boolean isIllFormed = false; 3085 String[] subtags = range.split("-"); 3086 if (isSubtagIllFormed(subtags[0], true) 3087 || range.endsWith("-")) { 3088 isIllFormed = true; 3089 } else { 3090 for (int i = 1; i < subtags.length; i++) { 3091 if (isSubtagIllFormed(subtags[i], false)) { 3092 isIllFormed = true; 3093 break; 3094 } 3095 } 3096 } 3097 if (isIllFormed) { 3098 throw new IllegalArgumentException("range=" + range); 3099 } 3100 3101 this.range = range; 3102 this.weight = weight; 3103 } 3104 3105 private static boolean isSubtagIllFormed(String subtag, 3106 boolean isFirstSubtag) { 3107 if (subtag.isEmpty() || subtag.length() > 8) { 3108 return true; 3109 } else if (subtag.equals("*")) { 3110 return false; 3111 } 3112 char[] charArray = subtag.toCharArray(); 3113 if (isFirstSubtag) { // ALPHA 3114 for (char c : charArray) { 3115 if (c < 'a' || c > 'z') { 3116 return true; 3117 } 3118 } 3119 } else { // ALPHA / DIGIT 3120 for (char c : charArray) { 3121 if (c < '0' || (c > '9' && c < 'a') || c > 'z') { 3122 return true; 3123 } 3124 } 3125 } 3126 return false; 3127 } 3128 3129 /** 3130 * Returns the language range of this {@code LanguageRange}. 3131 * 3132 * @return the language range. 3133 */ 3134 public String getRange() { 3135 return range; 3136 } 3137 3138 /** 3139 * Returns the weight of this {@code LanguageRange}. 3140 * 3141 * @return the weight value. 3142 */ 3143 public double getWeight() { 3144 return weight; 3145 } 3146 3147 /** 3148 * Parses the given {@code ranges} to generate a Language Priority List. 3149 * 3150 * <p>This method performs a syntactic check for each language range in 3151 * the given {@code ranges} but doesn't do validation using the IANA 3152 * Language Subtag Registry. 3153 * 3154 * <p>The {@code ranges} to be given can take one of the following 3155 * forms: 3156 * 3157 * <pre> 3158 * "Accept-Language: ja,en;q=0.4" (weighted list with Accept-Language prefix) 3159 * "ja,en;q=0.4" (weighted list) 3160 * "ja,en" (prioritized list) 3161 * </pre> 3162 * 3163 * In a weighted list, each language range is given a weight value. 3164 * The weight value is identical to the "quality value" in 3165 * <a href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>, and it 3166 * expresses how much the user prefers the language. A weight value is 3167 * specified after a corresponding language range followed by 3168 * {@code ";q="}, and the default weight value is {@code MAX_WEIGHT} 3169 * when it is omitted. 3170 * 3171 * <p>Unlike a weighted list, language ranges in a prioritized list 3172 * are sorted in the descending order based on its priority. The first 3173 * language range has the highest priority and meets the user's 3174 * preference most. 3175 * 3176 * <p>In either case, language ranges are sorted in descending order in 3177 * the Language Priority List based on priority or weight. If a 3178 * language range appears in the given {@code ranges} more than once, 3179 * only the first one is included on the Language Priority List. 3180 * 3181 * <p>The returned list consists of language ranges from the given 3182 * {@code ranges} and their equivalents found in the IANA Language 3183 * Subtag Registry. For example, if the given {@code ranges} is 3184 * {@code "Accept-Language: iw,en-us;q=0.7,en;q=0.3"}, the elements in 3185 * the list to be returned are: 3186 * 3187 * <pre> 3188 * <b>Range</b> <b>Weight</b> 3189 * "iw" (older tag for Hebrew) 1.0 3190 * "he" (new preferred code for Hebrew) 1.0 3191 * "en-us" (English, United States) 0.7 3192 * "en" (English) 0.3 3193 * </pre> 3194 * 3195 * Two language ranges, {@code "iw"} and {@code "he"}, have the same 3196 * highest priority in the list. By adding {@code "he"} to the user's 3197 * Language Priority List, locale-matching method can find Hebrew as a 3198 * matching locale (or language tag) even if the application or system 3199 * offers only {@code "he"} as a supported locale (or language tag). 3200 * 3201 * @param ranges a list of comma-separated language ranges or a list of 3202 * language ranges in the form of the "Accept-Language" header 3203 * defined in <a href="http://tools.ietf.org/html/rfc2616">RFC 3204 * 2616</a> 3205 * @return a Language Priority List consisting of language ranges 3206 * included in the given {@code ranges} and their equivalent 3207 * language ranges if available. The list is modifiable. 3208 * @throws NullPointerException if {@code ranges} is null 3209 * @throws IllegalArgumentException if a language range or a weight 3210 * found in the given {@code ranges} is ill-formed 3211 */ 3212 public static List<LanguageRange> parse(String ranges) { 3213 return LocaleMatcher.parse(ranges); 3214 } 3215 3216 /** 3217 * Parses the given {@code ranges} to generate a Language Priority 3218 * List, and then customizes the list using the given {@code map}. 3219 * This method is equivalent to 3220 * {@code mapEquivalents(parse(ranges), map)}. 3221 * 3222 * @param ranges a list of comma-separated language ranges or a list 3223 * of language ranges in the form of the "Accept-Language" header 3224 * defined in <a href="http://tools.ietf.org/html/rfc2616">RFC 3225 * 2616</a> 3226 * @param map a map containing information to customize language ranges 3227 * @return a Language Priority List with customization. The list is 3228 * modifiable. 3229 * @throws NullPointerException if {@code ranges} is null 3230 * @throws IllegalArgumentException if a language range or a weight 3231 * found in the given {@code ranges} is ill-formed 3232 * @see #parse(String) 3233 * @see #mapEquivalents 3234 */ 3235 public static List<LanguageRange> parse(String ranges, 3236 Map<String, List<String>> map) { 3237 return mapEquivalents(parse(ranges), map); 3238 } 3239 3240 /** 3241 * Generates a new customized Language Priority List using the given 3242 * {@code priorityList} and {@code map}. If the given {@code map} is 3243 * empty, this method returns a copy of the given {@code priorityList}. 3244 * 3245 * <p>In the map, a key represents a language range whereas a value is 3246 * a list of equivalents of it. {@code '*'} cannot be used in the map. 3247 * Each equivalent language range has the same weight value as its 3248 * original language range. 3249 * 3250 * <pre> 3251 * An example of map: 3252 * <b>Key</b> <b>Value</b> 3253 * "zh" (Chinese) "zh", 3254 * "zh-Hans"(Simplified Chinese) 3255 * "zh-HK" (Chinese, Hong Kong) "zh-HK" 3256 * "zh-TW" (Chinese, Taiwan) "zh-TW" 3257 * </pre> 3258 * 3259 * The customization is performed after modification using the IANA 3260 * Language Subtag Registry. 3261 * 3262 * <p>For example, if a user's Language Priority List consists of five 3263 * language ranges ({@code "zh"}, {@code "zh-CN"}, {@code "en"}, 3264 * {@code "zh-TW"}, and {@code "zh-HK"}), the newly generated Language 3265 * Priority List which is customized using the above map example will 3266 * consists of {@code "zh"}, {@code "zh-Hans"}, {@code "zh-CN"}, 3267 * {@code "zh-Hans-CN"}, {@code "en"}, {@code "zh-TW"}, and 3268 * {@code "zh-HK"}. 3269 * 3270 * <p>{@code "zh-HK"} and {@code "zh-TW"} aren't converted to 3271 * {@code "zh-Hans-HK"} nor {@code "zh-Hans-TW"} even if they are 3272 * included in the Language Priority List. In this example, mapping 3273 * is used to clearly distinguish Simplified Chinese and Traditional 3274 * Chinese. 3275 * 3276 * <p>If the {@code "zh"}-to-{@code "zh"} mapping isn't included in the 3277 * map, a simple replacement will be performed and the customized list 3278 * won't include {@code "zh"} and {@code "zh-CN"}. 3279 * 3280 * @param priorityList user's Language Priority List 3281 * @param map a map containing information to customize language ranges 3282 * @return a new Language Priority List with customization. The list is 3283 * modifiable. 3284 * @throws NullPointerException if {@code priorityList} is {@code null} 3285 * @see #parse(String, Map) 3286 */ 3287 public static List<LanguageRange> mapEquivalents( 3288 List<LanguageRange>priorityList, 3289 Map<String, List<String>> map) { 3290 return LocaleMatcher.mapEquivalents(priorityList, map); 3291 } 3292 3293 /** 3294 * Returns a hash code value for the object. 3295 * 3296 * @return a hash code value for this object. 3297 */ 3298 @Override 3299 public int hashCode() { 3300 int h = hash; 3301 if (h == 0) { 3302 h = 17; 3303 h = 37*h + range.hashCode(); 3304 long bitsWeight = Double.doubleToLongBits(weight); 3305 h = 37*h + (int)(bitsWeight ^ (bitsWeight >>> 32)); 3306 if (h != 0) { 3307 hash = h; 3308 } 3309 } 3310 return h; 3311 } 3312 3313 /** 3314 * Compares this object to the specified object. The result is true if 3315 * and only if the argument is not {@code null} and is a 3316 * {@code LanguageRange} object that contains the same {@code range} 3317 * and {@code weight} values as this object. 3318 * 3319 * @param obj the object to compare with 3320 * @return {@code true} if this object's {@code range} and 3321 * {@code weight} are the same as the {@code obj}'s; {@code false} 3322 * otherwise. 3323 */ 3324 @Override 3325 public boolean equals(Object obj) { 3326 if (this == obj) { 3327 return true; 3328 } 3329 if (!(obj instanceof LanguageRange)) { 3330 return false; 3331 } 3332 LanguageRange other = (LanguageRange)obj; 3333 return hash == other.hash 3334 && range.equals(other.range) 3335 && weight == other.weight; 3336 } 3337 3338 /** 3339 * Returns an informative string representation of this {@code LanguageRange} 3340 * object, consisting of language range and weight if the range is 3341 * weighted and the weight is less than the max weight. 3342 * 3343 * @return a string representation of this {@code LanguageRange} object. 3344 */ 3345 @Override 3346 public String toString() { 3347 return (weight == MAX_WEIGHT) ? range : range + ";q=" + weight; 3348 } 3349 } 3350 3351 /** 3352 * Returns a list of matching {@code Locale} instances using the filtering 3353 * mechanism defined in RFC 4647. 3354 * 3355 * This filter operation on the given {@code locales} ensures that only 3356 * unique matching locale(s) are returned. 3357 * 3358 * @param priorityList user's Language Priority List in which each language 3359 * tag is sorted in descending order based on priority or weight 3360 * @param locales {@code Locale} instances used for matching 3361 * @param mode filtering mode 3362 * @return a list of {@code Locale} instances for matching language tags 3363 * sorted in descending order based on priority or weight, or an empty 3364 * list if nothing matches. The list is modifiable. 3365 * @throws NullPointerException if {@code priorityList} or {@code locales} 3366 * is {@code null} 3367 * @throws IllegalArgumentException if one or more extended language ranges 3368 * are included in the given list when 3369 * {@link FilteringMode#REJECT_EXTENDED_RANGES} is specified 3370 * 3371 * @since 1.8 3372 */ 3373 public static List<Locale> filter(List<LanguageRange> priorityList, 3374 Collection<Locale> locales, 3375 FilteringMode mode) { 3376 return LocaleMatcher.filter(priorityList, locales, mode); 3377 } 3378 3379 /** 3380 * Returns a list of matching {@code Locale} instances using the filtering 3381 * mechanism defined in RFC 4647. This is equivalent to 3382 * {@link #filter(List, Collection, FilteringMode)} when {@code mode} is 3383 * {@link FilteringMode#AUTOSELECT_FILTERING}. 3384 * 3385 * This filter operation on the given {@code locales} ensures that only 3386 * unique matching locale(s) are returned. 3387 * 3388 * @param priorityList user's Language Priority List in which each language 3389 * tag is sorted in descending order based on priority or weight 3390 * @param locales {@code Locale} instances used for matching 3391 * @return a list of {@code Locale} instances for matching language tags 3392 * sorted in descending order based on priority or weight, or an empty 3393 * list if nothing matches. The list is modifiable. 3394 * @throws NullPointerException if {@code priorityList} or {@code locales} 3395 * is {@code null} 3396 * 3397 * @since 1.8 3398 */ 3399 public static List<Locale> filter(List<LanguageRange> priorityList, 3400 Collection<Locale> locales) { 3401 return filter(priorityList, locales, FilteringMode.AUTOSELECT_FILTERING); 3402 } 3403 3404 /** 3405 * Returns a list of matching languages tags using the basic filtering 3406 * mechanism defined in RFC 4647. 3407 * 3408 * This filter operation on the given {@code tags} ensures that only 3409 * unique matching tag(s) are returned with preserved case. In case of 3410 * duplicate matching tags with the case difference, the first matching 3411 * tag with preserved case is returned. 3412 * For example, "de-ch" is returned out of the duplicate matching tags 3413 * "de-ch" and "de-CH", if "de-ch" is checked first for matching in the 3414 * given {@code tags}. Note that if the given {@code tags} is an unordered 3415 * {@code Collection}, the returned matching tag out of duplicate tags is 3416 * subject to change, depending on the implementation of the 3417 * {@code Collection}. 3418 * 3419 * @param priorityList user's Language Priority List in which each language 3420 * tag is sorted in descending order based on priority or weight 3421 * @param tags language tags 3422 * @param mode filtering mode 3423 * @return a list of matching language tags sorted in descending order 3424 * based on priority or weight, or an empty list if nothing matches. 3425 * The list is modifiable. 3426 * @throws NullPointerException if {@code priorityList} or {@code tags} is 3427 * {@code null} 3428 * @throws IllegalArgumentException if one or more extended language ranges 3429 * are included in the given list when 3430 * {@link FilteringMode#REJECT_EXTENDED_RANGES} is specified 3431 * 3432 * @since 1.8 3433 */ 3434 public static List<String> filterTags(List<LanguageRange> priorityList, 3435 Collection<String> tags, 3436 FilteringMode mode) { 3437 return LocaleMatcher.filterTags(priorityList, tags, mode); 3438 } 3439 3440 /** 3441 * Returns a list of matching languages tags using the basic filtering 3442 * mechanism defined in RFC 4647. This is equivalent to 3443 * {@link #filterTags(List, Collection, FilteringMode)} when {@code mode} 3444 * is {@link FilteringMode#AUTOSELECT_FILTERING}. 3445 * 3446 * This filter operation on the given {@code tags} ensures that only 3447 * unique matching tag(s) are returned with preserved case. In case of 3448 * duplicate matching tags with the case difference, the first matching 3449 * tag with preserved case is returned. 3450 * For example, "de-ch" is returned out of the duplicate matching tags 3451 * "de-ch" and "de-CH", if "de-ch" is checked first for matching in the 3452 * given {@code tags}. Note that if the given {@code tags} is an unordered 3453 * {@code Collection}, the returned matching tag out of duplicate tags is 3454 * subject to change, depending on the implementation of the 3455 * {@code Collection}. 3456 * 3457 * @param priorityList user's Language Priority List in which each language 3458 * tag is sorted in descending order based on priority or weight 3459 * @param tags language tags 3460 * @return a list of matching language tags sorted in descending order 3461 * based on priority or weight, or an empty list if nothing matches. 3462 * The list is modifiable. 3463 * @throws NullPointerException if {@code priorityList} or {@code tags} is 3464 * {@code null} 3465 * 3466 * @since 1.8 3467 */ 3468 public static List<String> filterTags(List<LanguageRange> priorityList, 3469 Collection<String> tags) { 3470 return filterTags(priorityList, tags, FilteringMode.AUTOSELECT_FILTERING); 3471 } 3472 3473 /** 3474 * Returns a {@code Locale} instance for the best-matching language 3475 * tag using the lookup mechanism defined in RFC 4647. 3476 * 3477 * @param priorityList user's Language Priority List in which each language 3478 * tag is sorted in descending order based on priority or weight 3479 * @param locales {@code Locale} instances used for matching 3480 * @return the best matching <code>Locale</code> instance chosen based on 3481 * priority or weight, or {@code null} if nothing matches. 3482 * @throws NullPointerException if {@code priorityList} or {@code tags} is 3483 * {@code null} 3484 * 3485 * @since 1.8 3486 */ 3487 public static Locale lookup(List<LanguageRange> priorityList, 3488 Collection<Locale> locales) { 3489 return LocaleMatcher.lookup(priorityList, locales); 3490 } 3491 3492 /** 3493 * Returns the best-matching language tag using the lookup mechanism 3494 * defined in RFC 4647. 3495 * 3496 * This lookup operation on the given {@code tags} ensures that the 3497 * first matching tag with preserved case is returned. 3498 * 3499 * @param priorityList user's Language Priority List in which each language 3500 * tag is sorted in descending order based on priority or weight 3501 * @param tags language tangs used for matching 3502 * @return the best matching language tag chosen based on priority or 3503 * weight, or {@code null} if nothing matches. 3504 * @throws NullPointerException if {@code priorityList} or {@code tags} is 3505 * {@code null} 3506 * 3507 * @since 1.8 3508 */ 3509 public static String lookupTag(List<LanguageRange> priorityList, 3510 Collection<String> tags) { 3511 return LocaleMatcher.lookupTag(priorityList, tags); 3512 } 3513 3514 }