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