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