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