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