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