1 /*
   2  * Copyright (c) 1996, 2011, 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.security.AccessController;
  49 import java.text.MessageFormat;
  50 import java.util.spi.LocaleNameProvider;
  51 
  52 import sun.security.action.GetPropertyAction;
  53 import sun.util.LocaleServiceProviderPool;
  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.LocaleObjectCache;
  59 import sun.util.locale.LocaleSyntaxException;
  60 import sun.util.locale.LocaleUtils;
  61 import sun.util.locale.ParseStatus;
  62 import sun.util.locale.UnicodeLocaleExtension;
  63 import sun.util.resources.LocaleData;
  64 import sun.util.resources.OpenListResourceBundle;
  65 
  66 /**
  67  * A <code>Locale</code> object represents a specific geographical, political,
  68  * or cultural region. An operation that requires a <code>Locale</code> to perform
  69  * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
  70  * to tailor information for the user. For example, displaying a number
  71  * is a locale-sensitive operation&mdash; the number should be formatted
  72  * according to the customs and conventions of the user's native country,
  73  * region, or culture.
  74  *
  75  * <p> The <code>Locale</code> class implements identifiers
  76  * interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying
  77  * Languages"), with support for the LDML (UTS#35, "Unicode Locale
  78  * Data Markup Language") BCP 47-compatible extensions for locale data
  79  * exchange.
  80  *
  81  * <p> A <code>Locale</code> object logically consists of the fields
  82  * described below.
  83  *
  84  * <dl>
  85  *   <dt><a name="def_language"/><b>language</b></dt>
  86  *
  87  *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
  88  *   language subtags up to 8 alpha letters (for future enhancements).
  89  *   When a language has both an alpha-2 code and an alpha-3 code, the
  90  *   alpha-2 code must be used.  You can find a full list of valid
  91  *   language codes in the IANA Language Subtag Registry (search for
  92  *   "Type: language").  The language field is case insensitive, but
  93  *   <code>Locale</code> always canonicalizes to lower case.</dd><br>
  94  *
  95  *   <dd>Well-formed language values have the form
  96  *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the the full
  97  *   BCP47 language production, since it excludes extlang.  They are
  98  *   not needed since modern three-letter language codes replace
  99  *   them.</dd><br>
 100  *
 101  *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br>
 102  *
 103  *   <dt><a name="def_script"/><b>script</b></dt>
 104  *
 105  *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
 106  *   valid script codes in the IANA Language Subtag Registry (search
 107  *   for "Type: script").  The script field is case insensitive, but
 108  *   <code>Locale</code> always canonicalizes to title case (the first
 109  *   letter is upper case and the rest of the letters are lower
 110  *   case).</dd><br>
 111  *
 112  *   <dd>Well-formed script values have the form
 113  *   <code>[a-zA-Z]{4}</code></dd><br>
 114  *
 115  *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br>
 116  *
 117  *   <dt><a name="def_region"/><b>country (region)</b></dt>
 118  *
 119  *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
 120  *   You can find a full list of valid country and region codes in the
 121  *   IANA Language Subtag Registry (search for "Type: region").  The
 122  *   country (region) field is case insensitive, but
 123  *   <code>Locale</code> always canonicalizes to upper case.</dd><br>
 124  *
 125  *   <dd>Well-formed country/region values have
 126  *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br>
 127  *
 128  *   <dd>Example: "US" (United States), "FR" (France), "029"
 129  *   (Caribbean)</dd><br>
 130  *
 131  *   <dt><a name="def_variant"/><b>variant</b></dt>
 132  *
 133  *   <dd>Any arbitrary value used to indicate a variation of a
 134  *   <code>Locale</code>.  Where there are two or more variant values
 135  *   each indicating its own semantics, these values should be ordered
 136  *   by importance, with most important first, separated by
 137  *   underscore('_').  The variant field is case sensitive.</dd><br>
 138  *
 139  *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
 140  *   subtags.  Also BCP 47 subtags are strictly used to indicate
 141  *   additional variations that define a language or its dialects that
 142  *   are not covered by any combinations of language, script and
 143  *   region subtags.  You can find a full list of valid variant codes
 144  *   in the IANA Language Subtag Registry (search for "Type: variant").
 145  *
 146  *   <p>However, the variant field in <code>Locale</code> has
 147  *   historically been used for any kind of variation, not just
 148  *   language variations.  For example, some supported variants
 149  *   available in Java SE Runtime Environments indicate alternative
 150  *   cultural behaviors such as calendar type or number script.  In
 151  *   BCP 47 this kind of information, which does not identify the
 152  *   language, is supported by extension subtags or private use
 153  *   subtags.</dd><br>
 154  *
 155  *   <dd>Well-formed variant values have the form <code>SUBTAG
 156  *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
 157  *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
 158  *   uses hyphen ('-') as a delimiter, this is more lenient).</dd><br>
 159  *
 160  *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br>
 161  *
 162  *   <dt><a name="def_extensions"/><b>extensions</b></dt>
 163  *
 164  *   <dd>A map from single character keys to string values, indicating
 165  *   extensions apart from language identification.  The extensions in
 166  *   <code>Locale</code> implement the semantics and syntax of BCP 47
 167  *   extension subtags and private use subtags. The extensions are
 168  *   case insensitive, but <code>Locale</code> canonicalizes all
 169  *   extension keys and values to lower case. Note that extensions
 170  *   cannot have empty values.</dd><br>
 171  *
 172  *   <dd>Well-formed keys are single characters from the set
 173  *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
 174  *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
 175  *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
 176  *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
 177  *   single-character subtags).</dd><br>
 178  *
 179  *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
 180  *   key="x"/value="java-1-7"</dd>
 181  * </dl>
 182  *
 183  * <b>Note:</b> Although BCP 47 requires field values to be registered
 184  * in the IANA Language Subtag Registry, the <code>Locale</code> class
 185  * does not provide any validation features.  The <code>Builder</code>
 186  * only checks if an individual field satisfies the syntactic
 187  * requirement (is well-formed), but does not validate the value
 188  * itself.  See {@link Builder} for details.
 189  *
 190  * <h4><a name="def_locale_extension">Unicode locale/language extension</h4>
 191  *
 192  * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
 193  * attributes and keywords to override or refine the default behavior
 194  * associated with a locale.  A keyword is represented by a pair of
 195  * key and type.  For example, "nu-thai" indicates that Thai local
 196  * digits (value:"thai") should be used for formatting numbers
 197  * (key:"nu").
 198  *
 199  * <p>The keywords are mapped to a BCP 47 extension value using the
 200  * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}).  The above
 201  * example, "nu-thai", becomes the extension "u-nu-thai".code
 202  *
 203  * <p>Thus, when a <code>Locale</code> object contains Unicode locale
 204  * attributes and keywords,
 205  * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a
 206  * String representing this information, for example, "nu-thai".  The
 207  * <code>Locale</code> class also provides {@link
 208  * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and
 209  * {@link #getUnicodeLocaleType} which allow you to access Unicode
 210  * locale attributes and key/type pairs directly.  When represented as
 211  * a string, the Unicode Locale Extension lists attributes
 212  * alphabetically, followed by key/type sequences with keys listed
 213  * alphabetically (the order of subtags comprising a key's type is
 214  * fixed when the type is defined)
 215  *
 216  * <p>A well-formed locale key has the form
 217  * <code>[0-9a-zA-Z]{2}</code>.  A well-formed locale type has the
 218  * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it
 219  * can be empty, or a series of subtags 3-8 alphanums in length).  A
 220  * well-formed locale attribute has the form
 221  * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same
 222  * form as a locale type subtag).
 223  *
 224  * <p>The Unicode locale extension specifies optional behavior in
 225  * locale-sensitive services.  Although the LDML specification defines
 226  * various keys and values, actual locale-sensitive service
 227  * implementations in a Java Runtime Environment might not support any
 228  * particular Unicode locale attributes or key/type pairs.
 229  *
 230  * <h4>Creating a Locale</h4>
 231  *
 232  * <p>There are several different ways to create a <code>Locale</code>
 233  * object.
 234  *
 235  * <h5>Builder</h5>
 236  *
 237  * <p>Using {@link Builder} you can construct a <code>Locale</code> object
 238  * that conforms to BCP 47 syntax.
 239  *
 240  * <h5>Constructors</h5>
 241  *
 242  * <p>The <code>Locale</code> class provides three constructors:
 243  * <blockquote>
 244  * <pre>
 245  *     {@link #Locale(String language)}
 246  *     {@link #Locale(String language, String country)}
 247  *     {@link #Locale(String language, String country, String variant)}
 248  * </pre>
 249  * </blockquote>
 250  * These constructors allow you to create a <code>Locale</code> object
 251  * with language, country and variant, but you cannot specify
 252  * script or extensions.
 253  *
 254  * <h5>Factory Methods</h5>
 255  *
 256  * <p>The method {@link #forLanguageTag} creates a <code>Locale</code>
 257  * object for a well-formed BCP 47 language tag.
 258  *
 259  * <h5>Locale Constants</h5>
 260  *
 261  * <p>The <code>Locale</code> class provides a number of convenient constants
 262  * that you can use to create <code>Locale</code> objects for commonly used
 263  * locales. For example, the following creates a <code>Locale</code> object
 264  * for the United States:
 265  * <blockquote>
 266  * <pre>
 267  *     Locale.US
 268  * </pre>
 269  * </blockquote>
 270  *
 271  * <h4>Use of Locale</h4>
 272  *
 273  * <p>Once you've created a <code>Locale</code> you can query it for information
 274  * about itself. Use <code>getCountry</code> to get the country (or region)
 275  * code and <code>getLanguage</code> to get the language code.
 276  * You can use <code>getDisplayCountry</code> to get the
 277  * name of the country suitable for displaying to the user. Similarly,
 278  * you can use <code>getDisplayLanguage</code> to get the name of
 279  * the language suitable for displaying to the user. Interestingly,
 280  * the <code>getDisplayXXX</code> methods are themselves locale-sensitive
 281  * and have two versions: one that uses the default locale and one
 282  * that uses the locale specified as an argument.
 283  *
 284  * <p>The Java Platform provides a number of classes that perform locale-sensitive
 285  * operations. For example, the <code>NumberFormat</code> class formats
 286  * numbers, currency, and percentages in a locale-sensitive manner. Classes
 287  * such as <code>NumberFormat</code> have several convenience methods
 288  * for creating a default object of that type. For example, the
 289  * <code>NumberFormat</code> class provides these three convenience methods
 290  * for creating a default <code>NumberFormat</code> object:
 291  * <blockquote>
 292  * <pre>
 293  *     NumberFormat.getInstance()
 294  *     NumberFormat.getCurrencyInstance()
 295  *     NumberFormat.getPercentInstance()
 296  * </pre>
 297  * </blockquote>
 298  * Each of these methods has two variants; one with an explicit locale
 299  * and one without; the latter uses the default locale:
 300  * <blockquote>
 301  * <pre>
 302  *     NumberFormat.getInstance(myLocale)
 303  *     NumberFormat.getCurrencyInstance(myLocale)
 304  *     NumberFormat.getPercentInstance(myLocale)
 305  * </pre>
 306  * </blockquote>
 307  * A <code>Locale</code> is the mechanism for identifying the kind of object
 308  * (<code>NumberFormat</code>) that you would like to get. The locale is
 309  * <STRONG>just</STRONG> a mechanism for identifying objects,
 310  * <STRONG>not</STRONG> a container for the objects themselves.
 311  *
 312  * <h4>Compatibility</h4>
 313  *
 314  * <p>In order to maintain compatibility with existing usage, Locale's
 315  * constructors retain their behavior prior to the Java Runtime
 316  * Environment version 1.7.  The same is largely true for the
 317  * <code>toString</code> method. Thus Locale objects can continue to
 318  * be used as they were. In particular, clients who parse the output
 319  * of toString into language, country, and variant fields can continue
 320  * to do so (although this is strongly discouraged), although the
 321  * variant field will have additional information in it if script or
 322  * extensions are present.
 323  *
 324  * <p>In addition, BCP 47 imposes syntax restrictions that are not
 325  * imposed by Locale's constructors. This means that conversions
 326  * between some Locales and BCP 47 language tags cannot be made without
 327  * losing information. Thus <code>toLanguageTag</code> cannot
 328  * represent the state of locales whose language, country, or variant
 329  * do not conform to BCP 47.
 330  *
 331  * <p>Because of these issues, it is recommended that clients migrate
 332  * away from constructing non-conforming locales and use the
 333  * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead.
 334  * Clients desiring a string representation of the complete locale can
 335  * then always rely on <code>toLanguageTag</code> for this purpose.
 336  *
 337  * <h5><a name="special_cases_constructor"/>Special cases</h5>
 338  *
 339  * <p>For compatibility reasons, two
 340  * non-conforming locales are treated as special cases.  These are
 341  * <b><tt>ja_JP_JP</tt></b> and <b><tt>th_TH_TH</tt></b>. These are ill-formed
 342  * in BCP 47 since the variants are too short. To ease migration to BCP 47,
 343  * these are treated specially during construction.  These two cases (and only
 344  * these) cause a constructor to generate an extension, all other values behave
 345  * exactly as they did prior to Java 7.
 346  *
 347  * <p>Java has used <tt>ja_JP_JP</tt> to represent Japanese as used in
 348  * Japan together with the Japanese Imperial calendar. This is now
 349  * representable using a Unicode locale extension, by specifying the
 350  * Unicode locale key <tt>ca</tt> (for "calendar") and type
 351  * <tt>japanese</tt>. When the Locale constructor is called with the
 352  * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is
 353  * automatically added.
 354  *
 355  * <p>Java has used <tt>th_TH_TH</tt> to represent Thai as used in
 356  * Thailand together with Thai digits. This is also now representable using
 357  * a Unicode locale extension, by specifying the Unicode locale key
 358  * <tt>nu</tt> (for "number") and value <tt>thai</tt>. When the Locale
 359  * constructor is called with the arguments "th", "TH", "TH", the
 360  * extension "u-nu-thai" is automatically added.
 361  *
 362  * <h5>Serialization</h5>
 363  *
 364  * <p>During serialization, writeObject writes all fields to the output
 365  * stream, including extensions.
 366  *
 367  * <p>During deserialization, readResolve adds extensions as described
 368  * in <a href="#special_cases_constructor">Special Cases</a>, only
 369  * for the two cases th_TH_TH and ja_JP_JP.
 370  *
 371  * <h5>Legacy language codes</h5>
 372  *
 373  * <p>Locale's constructor has always converted three language codes to
 374  * their earlier, obsoleted forms: <tt>he</tt> maps to <tt>iw</tt>,
 375  * <tt>yi</tt> maps to <tt>ji</tt>, and <tt>id</tt> maps to
 376  * <tt>in</tt>.  This continues to be the case, in order to not break
 377  * backwards compatibility.
 378  *
 379  * <p>The APIs added in 1.7 map between the old and new language codes,
 380  * maintaining the old codes internal to Locale (so that
 381  * <code>getLanguage</code> and <code>toString</code> reflect the old
 382  * code), but using the new codes in the BCP 47 language tag APIs (so
 383  * that <code>toLanguageTag</code> reflects the new one). This
 384  * preserves the equivalence between Locales no matter which code or
 385  * API is used to construct them. Java's default resource bundle
 386  * lookup mechanism also implements this mapping, so that resources
 387  * can be named using either convention, see {@link ResourceBundle.Control}.
 388  *
 389  * <h5>Three-letter language/country(region) codes</h5>
 390  *
 391  * <p>The Locale constructors have always specified that the language
 392  * and the country param be two characters in length, although in
 393  * practice they have accepted any length.  The specification has now
 394  * been relaxed to allow language codes of two to eight characters and
 395  * country (region) codes of two to three characters, and in
 396  * particular, three-letter language codes and three-digit region
 397  * codes as specified in the IANA Language Subtag Registry.  For
 398  * compatibility, the implementation still does not impose a length
 399  * constraint.
 400  *
 401  * @see Builder
 402  * @see ResourceBundle
 403  * @see java.text.Format
 404  * @see java.text.NumberFormat
 405  * @see java.text.Collator
 406  * @author Mark Davis
 407  * @since 1.1
 408  */
 409 public final class Locale implements Cloneable, Serializable {
 410 
 411     static private final  Cache LOCALECACHE = new Cache();
 412 
 413     /** Useful constant for language.
 414      */
 415     static public final Locale ENGLISH = createConstant("en", "");
 416 
 417     /** Useful constant for language.
 418      */
 419     static public final Locale FRENCH = createConstant("fr", "");
 420 
 421     /** Useful constant for language.
 422      */
 423     static public final Locale GERMAN = createConstant("de", "");
 424 
 425     /** Useful constant for language.
 426      */
 427     static public final Locale ITALIAN = createConstant("it", "");
 428 
 429     /** Useful constant for language.
 430      */
 431     static public final Locale JAPANESE = createConstant("ja", "");
 432 
 433     /** Useful constant for language.
 434      */
 435     static public final Locale KOREAN = createConstant("ko", "");
 436 
 437     /** Useful constant for language.
 438      */
 439     static public final Locale CHINESE = createConstant("zh", "");
 440 
 441     /** Useful constant for language.
 442      */
 443     static public final Locale SIMPLIFIED_CHINESE = createConstant("zh", "CN");
 444 
 445     /** Useful constant for language.
 446      */
 447     static public final Locale TRADITIONAL_CHINESE = createConstant("zh", "TW");
 448 
 449     /** Useful constant for country.
 450      */
 451     static public final Locale FRANCE = createConstant("fr", "FR");
 452 
 453     /** Useful constant for country.
 454      */
 455     static public final Locale GERMANY = createConstant("de", "DE");
 456 
 457     /** Useful constant for country.
 458      */
 459     static public final Locale ITALY = createConstant("it", "IT");
 460 
 461     /** Useful constant for country.
 462      */
 463     static public final Locale JAPAN = createConstant("ja", "JP");
 464 
 465     /** Useful constant for country.
 466      */
 467     static public final Locale KOREA = createConstant("ko", "KR");
 468 
 469     /** Useful constant for country.
 470      */
 471     static public final Locale CHINA = SIMPLIFIED_CHINESE;
 472 
 473     /** Useful constant for country.
 474      */
 475     static public final Locale PRC = SIMPLIFIED_CHINESE;
 476 
 477     /** Useful constant for country.
 478      */
 479     static public final Locale TAIWAN = TRADITIONAL_CHINESE;
 480 
 481     /** Useful constant for country.
 482      */
 483     static public final Locale UK = createConstant("en", "GB");
 484 
 485     /** Useful constant for country.
 486      */
 487     static public final Locale US = createConstant("en", "US");
 488 
 489     /** Useful constant for country.
 490      */
 491     static public final Locale CANADA = createConstant("en", "CA");
 492 
 493     /** Useful constant for country.
 494      */
 495     static public final Locale CANADA_FRENCH = createConstant("fr", "CA");
 496 
 497     /**
 498      * Useful constant for the root locale.  The root locale is the locale whose
 499      * language, country, and variant are empty ("") strings.  This is regarded
 500      * as the base locale of all locales, and is used as the language/country
 501      * neutral locale for the locale sensitive operations.
 502      *
 503      * @since 1.6
 504      */
 505     static public final Locale ROOT = createConstant("", "");
 506 
 507     /**
 508      * The key for the private use extension ('x').
 509      *
 510      * @see #getExtension(char)
 511      * @see Builder#setExtension(char, String)
 512      * @since 1.7
 513      */
 514     static public final char PRIVATE_USE_EXTENSION = 'x';
 515 
 516     /**
 517      * The key for Unicode locale extension ('u').
 518      *
 519      * @see #getExtension(char)
 520      * @see Builder#setExtension(char, String)
 521      * @since 1.7
 522      */
 523     static public final char UNICODE_LOCALE_EXTENSION = 'u';
 524 
 525     /** serialization ID
 526      */
 527     static final long serialVersionUID = 9149081749638150636L;
 528 
 529     /**
 530      * Display types for retrieving localized names from the name providers.
 531      */
 532     private static final int DISPLAY_LANGUAGE = 0;
 533     private static final int DISPLAY_COUNTRY  = 1;
 534     private static final int DISPLAY_VARIANT  = 2;
 535     private static final int DISPLAY_SCRIPT   = 3;
 536 
 537     /**
 538      * Private constructor used by getInstance method
 539      */
 540     private Locale(BaseLocale baseLocale, LocaleExtensions extensions) {
 541         this.baseLocale = baseLocale;
 542         this.localeExtensions = extensions;
 543     }
 544 
 545     /**
 546      * Construct a locale from language, country and variant.
 547      * This constructor normalizes the language value to lowercase and
 548      * the country value to uppercase.
 549      * <p>
 550      * <b>Note:</b>
 551      * <ul>
 552      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 553      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 554      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 555      * API on Locale will return only the OLD codes.
 556      * <li>For backward compatibility reasons, this constructor does not make
 557      * any syntactic checks on the input.
 558      * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially,
 559      * see <a href="#special_cases_constructor">Special Cases</a> for more information.
 560      * </ul>
 561      *
 562      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 563      * up to 8 characters in length.  See the <code>Locale</code> class description about
 564      * valid language values.
 565      * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
 566      * See the <code>Locale</code> class description about valid country values.
 567      * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>.
 568      * See the <code>Locale</code> class description for the details.
 569      * @exception NullPointerException thrown if any argument is null.
 570      */
 571     public Locale(String language, String country, String variant) {
 572         if (language== null || country == null || variant == null) {
 573             throw new NullPointerException();
 574         }
 575         baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
 576         localeExtensions = getCompatibilityExtensions(language, "", country, variant);
 577     }
 578 
 579     /**
 580      * Construct a locale from language and country.
 581      * This constructor normalizes the language value to lowercase and
 582      * the country value to uppercase.
 583      * <p>
 584      * <b>Note:</b>
 585      * <ul>
 586      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 587      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 588      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 589      * API on Locale will return only the OLD codes.
 590      * <li>For backward compatibility reasons, this constructor does not make
 591      * any syntactic checks on the input.
 592      * </ul>
 593      *
 594      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 595      * up to 8 characters in length.  See the <code>Locale</code> class description about
 596      * valid language values.
 597      * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
 598      * See the <code>Locale</code> class description about valid country values.
 599      * @exception NullPointerException thrown if either argument is null.
 600      */
 601     public Locale(String language, String country) {
 602         this(language, country, "");
 603     }
 604 
 605     /**
 606      * Construct a locale from a language code.
 607      * This constructor normalizes the language value to lowercase.
 608      * <p>
 609      * <b>Note:</b>
 610      * <ul>
 611      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 612      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 613      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 614      * API on Locale will return only the OLD codes.
 615      * <li>For backward compatibility reasons, this constructor does not make
 616      * any syntactic checks on the input.
 617      * </ul>
 618      *
 619      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 620      * up to 8 characters in length.  See the <code>Locale</code> class description about
 621      * valid language values.
 622      * @exception NullPointerException thrown if argument is null.
 623      * @since 1.4
 624      */
 625     public Locale(String language) {
 626         this(language, "", "");
 627     }
 628 
 629     /**
 630      * This method must be called only for creating the Locale.*
 631      * constants due to making shortcuts.
 632      */
 633     private static Locale createConstant(String lang, String country) {
 634         BaseLocale base = BaseLocale.createInstance(lang, country);
 635         return getInstance(base, null);
 636     }
 637 
 638     /**
 639      * Returns a <code>Locale</code> constructed from the given
 640      * <code>language</code>, <code>country</code> and
 641      * <code>variant</code>. If the same <code>Locale</code> instance
 642      * is available in the cache, then that instance is
 643      * returned. Otherwise, a new <code>Locale</code> instance is
 644      * created and cached.
 645      *
 646      * @param language lowercase 2 to 8 language code.
 647      * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code.
 648      * @param variant vendor and browser specific code. See class description.
 649      * @return the <code>Locale</code> instance requested
 650      * @exception NullPointerException if any argument is null.
 651      */
 652     static Locale getInstance(String language, String country, String variant) {
 653         return getInstance(language, "", country, variant, null);
 654     }
 655 
 656     static Locale getInstance(String language, String script, String country,
 657                                       String variant, LocaleExtensions extensions) {
 658         if (language== null || script == null || country == null || variant == null) {
 659             throw new NullPointerException();
 660         }
 661 
 662         if (extensions == null) {
 663             extensions = getCompatibilityExtensions(language, script, country, variant);
 664         }
 665 
 666         BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant);
 667         return getInstance(baseloc, extensions);
 668     }
 669 
 670     static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) {
 671         LocaleKey key = new LocaleKey(baseloc, extensions);
 672         return LOCALECACHE.get(key);
 673     }
 674 
 675     private static class Cache extends LocaleObjectCache<LocaleKey, Locale> {
 676         private Cache() {
 677         }
 678 
 679         @Override
 680         protected Locale createObject(LocaleKey key) {
 681             return new Locale(key.base, key.exts);
 682         }
 683     }
 684 
 685     private static final class LocaleKey {
 686         private final BaseLocale base;
 687         private final LocaleExtensions exts;
 688         private final int hash;
 689 
 690         private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) {
 691             base = baseLocale;
 692             exts = extensions;
 693 
 694             // Calculate the hash value here because it's always used.
 695             int h = base.hashCode();
 696             if (exts != null) {
 697                 h ^= exts.hashCode();
 698             }
 699             hash = h;
 700         }
 701 
 702         @Override
 703         public boolean equals(Object obj) {
 704             if (this == obj) {
 705                 return true;
 706             }
 707             if (!(obj instanceof LocaleKey)) {
 708                 return false;
 709             }
 710             LocaleKey other = (LocaleKey)obj;
 711             if (hash != other.hash || !base.equals(other.base)) {
 712                 return false;
 713             }
 714             if (exts == null) {
 715                 return other.exts == null;
 716             }
 717             return exts.equals(other.exts);
 718         }
 719 
 720         @Override
 721         public int hashCode() {
 722             return hash;
 723         }
 724     }
 725 
 726     /**
 727      * Gets the current value of the default locale for this instance
 728      * of the Java Virtual Machine.
 729      * <p>
 730      * The Java Virtual Machine sets the default locale during startup
 731      * based on the host environment. It is used by many locale-sensitive
 732      * methods if no locale is explicitly specified.
 733      * It can be changed using the
 734      * {@link #setDefault(java.util.Locale) setDefault} method.
 735      *
 736      * @return the default locale for this instance of the Java Virtual Machine
 737      */
 738     public static Locale getDefault() {
 739         // do not synchronize this method - see 4071298
 740         return defaultLocale;
 741     }
 742 
 743     /**
 744      * Gets the current value of the default locale for the specified Category
 745      * for this instance of the Java Virtual Machine.
 746      * <p>
 747      * The Java Virtual Machine sets the default locale during startup based
 748      * on the host environment. It is used by many locale-sensitive methods
 749      * if no locale is explicitly specified. It can be changed using the
 750      * setDefault(Locale.Category, Locale) method.
 751      *
 752      * @param category - the specified category to get the default locale
 753      * @throws NullPointerException - if category is null
 754      * @return the default locale for the specified Category for this instance
 755      *     of the Java Virtual Machine
 756      * @see #setDefault(Locale.Category, Locale)
 757      * @since 1.7
 758      */
 759     public static Locale getDefault(Locale.Category category) {
 760         // do not synchronize this method - see 4071298
 761         switch (category) {
 762         case DISPLAY:
 763             if (defaultDisplayLocale == null) {
 764                 synchronized(Locale.class) {
 765                     if (defaultDisplayLocale == null) {
 766                         defaultDisplayLocale = initDefault(category);
 767                     }
 768                 }
 769             }
 770             return defaultDisplayLocale;
 771         case FORMAT:
 772             if (defaultFormatLocale == null) {
 773                 synchronized(Locale.class) {
 774                     if (defaultFormatLocale == null) {
 775                         defaultFormatLocale = initDefault(category);
 776                     }
 777                 }
 778             }
 779             return defaultFormatLocale;
 780         default:
 781             assert false: "Unknown Category";
 782         }
 783         return getDefault();
 784     }
 785 
 786     private static Locale initDefault() {
 787         String language, region, script, country, variant;
 788         language = AccessController.doPrivileged(
 789             new GetPropertyAction("user.language", "en"));
 790         // for compatibility, check for old user.region property
 791         region = AccessController.doPrivileged(
 792             new GetPropertyAction("user.region"));
 793         if (region != null) {
 794             // region can be of form country, country_variant, or _variant
 795             int i = region.indexOf('_');
 796             if (i >= 0) {
 797                 country = region.substring(0, i);
 798                 variant = region.substring(i + 1);
 799             } else {
 800                 country = region;
 801                 variant = "";
 802             }
 803             script = "";
 804         } else {
 805             script = AccessController.doPrivileged(
 806                 new GetPropertyAction("user.script", ""));
 807             country = AccessController.doPrivileged(
 808                 new GetPropertyAction("user.country", ""));
 809             variant = AccessController.doPrivileged(
 810                 new GetPropertyAction("user.variant", ""));
 811         }
 812 
 813         return getInstance(language, script, country, variant, null);
 814     }
 815 
 816     private static Locale initDefault(Locale.Category category) {
 817         return getInstance(
 818             AccessController.doPrivileged(
 819                 new GetPropertyAction(category.languageKey, defaultLocale.getLanguage())),
 820             AccessController.doPrivileged(
 821                 new GetPropertyAction(category.scriptKey, defaultLocale.getScript())),
 822             AccessController.doPrivileged(
 823                 new GetPropertyAction(category.countryKey, defaultLocale.getCountry())),
 824             AccessController.doPrivileged(
 825                 new GetPropertyAction(category.variantKey, defaultLocale.getVariant())),
 826             null);
 827     }
 828 
 829     /**
 830      * Sets the default locale for this instance of the Java Virtual Machine.
 831      * This does not affect the host locale.
 832      * <p>
 833      * If there is a security manager, its <code>checkPermission</code>
 834      * method is called with a <code>PropertyPermission("user.language", "write")</code>
 835      * permission before the default locale is changed.
 836      * <p>
 837      * The Java Virtual Machine sets the default locale during startup
 838      * based on the host environment. It is used by many locale-sensitive
 839      * methods if no locale is explicitly specified.
 840      * <p>
 841      * Since changing the default locale may affect many different areas
 842      * of functionality, this method should only be used if the caller
 843      * is prepared to reinitialize locale-sensitive code running
 844      * within the same Java Virtual Machine.
 845      * <p>
 846      * By setting the default locale with this method, all of the default
 847      * locales for each Category are also set to the specified default locale.
 848      *
 849      * @throws SecurityException
 850      *        if a security manager exists and its
 851      *        <code>checkPermission</code> method doesn't allow the operation.
 852      * @throws NullPointerException if <code>newLocale</code> is null
 853      * @param newLocale the new default locale
 854      * @see SecurityManager#checkPermission
 855      * @see java.util.PropertyPermission
 856      */
 857     public static synchronized void setDefault(Locale newLocale) {
 858         setDefault(Category.DISPLAY, newLocale);
 859         setDefault(Category.FORMAT, newLocale);
 860         defaultLocale = newLocale;
 861     }
 862 
 863     /**
 864      * Sets the default locale for the specified Category for this instance
 865      * of the Java Virtual Machine. This does not affect the host locale.
 866      * <p>
 867      * If there is a security manager, its checkPermission method is called
 868      * with a PropertyPermission("user.language", "write") permission before
 869      * the default locale is changed.
 870      * <p>
 871      * The Java Virtual Machine sets the default locale during startup based
 872      * on the host environment. It is used by many locale-sensitive methods
 873      * if no locale is explicitly specified.
 874      * <p>
 875      * Since changing the default locale may affect many different areas of
 876      * functionality, this method should only be used if the caller is
 877      * prepared to reinitialize locale-sensitive code running within the
 878      * same Java Virtual Machine.
 879      * <p>
 880      *
 881      * @param category - the specified category to set the default locale
 882      * @param newLocale - the new default locale
 883      * @throws SecurityException - if a security manager exists and its
 884      *     checkPermission method doesn't allow the operation.
 885      * @throws NullPointerException - if category and/or newLocale is null
 886      * @see SecurityManager#checkPermission(java.security.Permission)
 887      * @see PropertyPermission
 888      * @see #getDefault(Locale.Category)
 889      * @since 1.7
 890      */
 891     public static synchronized void setDefault(Locale.Category category,
 892         Locale newLocale) {
 893         if (category == null)
 894             throw new NullPointerException("Category cannot be NULL");
 895         if (newLocale == null)
 896             throw new NullPointerException("Can't set default locale to NULL");
 897 
 898         SecurityManager sm = System.getSecurityManager();
 899         if (sm != null) sm.checkPermission(new PropertyPermission
 900                         ("user.language", "write"));
 901         switch (category) {
 902         case DISPLAY:
 903             defaultDisplayLocale = newLocale;
 904             break;
 905         case FORMAT:
 906             defaultFormatLocale = newLocale;
 907             break;
 908         default:
 909             assert false: "Unknown Category";
 910         }
 911     }
 912 
 913     /**
 914      * Returns an array of all installed locales.
 915      * The returned array represents the union of locales supported
 916      * by the Java runtime environment and by installed
 917      * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider}
 918      * implementations.  It must contain at least a <code>Locale</code>
 919      * instance equal to {@link java.util.Locale#US Locale.US}.
 920      *
 921      * @return An array of installed locales.
 922      */
 923     public static Locale[] getAvailableLocales() {
 924         return LocaleServiceProviderPool.getAllAvailableLocales();
 925     }
 926 
 927     /**
 928      * Returns a list of all 2-letter country codes defined in ISO 3166.
 929      * Can be used to create Locales.
 930      * <p>
 931      * <b>Note:</b> The <code>Locale</code> class also supports other codes for
 932      * country (region), such as 3-letter numeric UN M.49 area codes.
 933      * Therefore, the list returned by this method does not contain ALL valid
 934      * codes that can be used to create Locales.
 935      */
 936     public static String[] getISOCountries() {
 937         if (isoCountries == null) {
 938             isoCountries = getISO2Table(LocaleISOData.isoCountryTable);
 939         }
 940         String[] result = new String[isoCountries.length];
 941         System.arraycopy(isoCountries, 0, result, 0, isoCountries.length);
 942         return result;
 943     }
 944 
 945     /**
 946      * Returns a list of all 2-letter language codes defined in ISO 639.
 947      * Can be used to create Locales.
 948      * <p>
 949      * <b>Note:</b>
 950      * <ul>
 951      * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
 952      * The list this function returns includes both the new and the old codes for the
 953      * languages whose codes have changed.
 954      * <li>The <code>Locale</code> class also supports language codes up to
 955      * 8 characters in length.  Therefore, the list returned by this method does
 956      * not contain ALL valid codes that can be used to create Locales.
 957      * </ul>
 958      */
 959     public static String[] getISOLanguages() {
 960         if (isoLanguages == null) {
 961             isoLanguages = getISO2Table(LocaleISOData.isoLanguageTable);
 962         }
 963         String[] result = new String[isoLanguages.length];
 964         System.arraycopy(isoLanguages, 0, result, 0, isoLanguages.length);
 965         return result;
 966     }
 967 
 968     private static final String[] getISO2Table(String table) {
 969         int len = table.length() / 5;
 970         String[] isoTable = new String[len];
 971         for (int i = 0, j = 0; i < len; i++, j += 5) {
 972             isoTable[i] = table.substring(j, j + 2);
 973         }
 974         return isoTable;
 975     }
 976 
 977     /**
 978      * Returns the language code of this Locale.
 979      *
 980      * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
 981      * Locale's constructor recognizes both the new and the old codes for the languages
 982      * whose codes have changed, but this function always returns the old code.  If you
 983      * want to check for a specific language whose code has changed, don't do
 984      * <pre>
 985      * if (locale.getLanguage().equals("he")) // BAD!
 986      *    ...
 987      * </pre>
 988      * Instead, do
 989      * <pre>
 990      * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
 991      *    ...
 992      * </pre>
 993      * @return The language code, or the empty string if none is defined.
 994      * @see #getDisplayLanguage
 995      */
 996     public String getLanguage() {
 997         return baseLocale.getLanguage();
 998     }
 999 
1000     /**
1001      * Returns the script for this locale, which should
1002      * either be the empty string or an ISO 15924 4-letter script
1003      * code. The first letter is uppercase and the rest are
1004      * lowercase, for example, 'Latn', 'Cyrl'.
1005      *
1006      * @return The script code, or the empty string if none is defined.
1007      * @see #getDisplayScript
1008      * @since 1.7
1009      */
1010     public String getScript() {
1011         return baseLocale.getScript();
1012     }
1013 
1014     /**
1015      * Returns the country/region code for this locale, which should
1016      * either be the empty string, an uppercase ISO 3166 2-letter code,
1017      * or a UN M.49 3-digit code.
1018      *
1019      * @return The country/region code, or the empty string if none is defined.
1020      * @see #getDisplayCountry
1021      */
1022     public String getCountry() {
1023         return baseLocale.getRegion();
1024     }
1025 
1026     /**
1027      * Returns the variant code for this locale.
1028      *
1029      * @return The variant code, or the empty string if none is defined.
1030      * @see #getDisplayVariant
1031      */
1032     public String getVariant() {
1033         return baseLocale.getVariant();
1034     }
1035 
1036     /**
1037      * Returns the extension (or private use) value associated with
1038      * the specified key, or null if there is no extension
1039      * associated with the key. To be well-formed, the key must be one
1040      * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
1041      * for example 'z' and 'Z' represent the same extension.
1042      *
1043      * @param key the extension key
1044      * @return The extension, or null if this locale defines no
1045      * extension for the specified key.
1046      * @throws IllegalArgumentException if key is not well-formed
1047      * @see #PRIVATE_USE_EXTENSION
1048      * @see #UNICODE_LOCALE_EXTENSION
1049      * @since 1.7
1050      */
1051     public String getExtension(char key) {
1052         if (!LocaleExtensions.isValidKey(key)) {
1053             throw new IllegalArgumentException("Ill-formed extension key: " + key);
1054         }
1055         return (localeExtensions == null) ? null : localeExtensions.getExtensionValue(key);
1056     }
1057 
1058     /**
1059      * Returns the set of extension keys associated with this locale, or the
1060      * empty set if it has no extensions. The returned set is unmodifiable.
1061      * The keys will all be lower-case.
1062      *
1063      * @return The set of extension keys, or the empty set if this locale has
1064      * no extensions.
1065      * @since 1.7
1066      */
1067     public Set<Character> getExtensionKeys() {
1068         if (localeExtensions == null) {
1069             return Collections.emptySet();
1070         }
1071         return localeExtensions.getKeys();
1072     }
1073 
1074     /**
1075      * Returns the set of unicode locale attributes associated with
1076      * this locale, or the empty set if it has no attributes. The
1077      * returned set is unmodifiable.
1078      *
1079      * @return The set of attributes.
1080      * @since 1.7
1081      */
1082     public Set<String> getUnicodeLocaleAttributes() {
1083         if (localeExtensions == null) {
1084             return Collections.emptySet();
1085         }
1086         return localeExtensions.getUnicodeLocaleAttributes();
1087     }
1088 
1089     /**
1090      * Returns the Unicode locale type associated with the specified Unicode locale key
1091      * for this locale. Returns the empty string for keys that are defined with no type.
1092      * Returns null if the key is not defined. Keys are case-insensitive. The key must
1093      * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
1094      * thrown.
1095      *
1096      * @param key the Unicode locale key
1097      * @return The Unicode locale type associated with the key, or null if the
1098      * locale does not define the key.
1099      * @throws IllegalArgumentException if the key is not well-formed
1100      * @throws NullPointerException if <code>key</code> is null
1101      * @since 1.7
1102      */
1103     public String getUnicodeLocaleType(String key) {
1104         if (!UnicodeLocaleExtension.isKey(key)) {
1105             throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
1106         }
1107         return (localeExtensions == null) ? null : localeExtensions.getUnicodeLocaleType(key);
1108     }
1109 
1110     /**
1111      * Returns the set of Unicode locale keys defined by this locale, or the empty set if
1112      * this locale has none.  The returned set is immutable.  Keys are all lower case.
1113      *
1114      * @return The set of Unicode locale keys, or the empty set if this locale has
1115      * no Unicode locale keywords.
1116      * @since 1.7
1117      */
1118     public Set<String> getUnicodeLocaleKeys() {
1119         if (localeExtensions == null) {
1120             return Collections.emptySet();
1121         }
1122         return localeExtensions.getUnicodeLocaleKeys();
1123     }
1124 
1125     /**
1126      * Package locale method returning the Locale's BaseLocale,
1127      * used by ResourceBundle
1128      * @return base locale of this Locale
1129      */
1130     BaseLocale getBaseLocale() {
1131         return baseLocale;
1132     }
1133 
1134     /**
1135      * Package private method returning the Locale's LocaleExtensions,
1136      * used by ResourceBundle.
1137      * @return locale exnteions of this Locale,
1138      *         or {@code null} if no extensions are defined
1139      */
1140      LocaleExtensions getLocaleExtensions() {
1141          return localeExtensions;
1142      }
1143 
1144     /**
1145      * Returns a string representation of this <code>Locale</code>
1146      * object, consisting of language, country, variant, script,
1147      * and extensions as below:
1148      * <p><blockquote>
1149      * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
1150      * </blockquote>
1151      *
1152      * Language is always lower case, country is always upper case, script is always title
1153      * case, and extensions are always lower case.  Extensions and private use subtags
1154      * will be in canonical order as explained in {@link #toLanguageTag}.
1155      *
1156      * <p>When the locale has neither script nor extensions, the result is the same as in
1157      * Java 6 and prior.
1158      *
1159      * <p>If both the language and country fields are missing, this function will return
1160      * the empty string, even if the variant, script, or extensions field is present (you
1161      * can't have a locale with just a variant, the variant must accompany a well-formed
1162      * language or country code).
1163      *
1164      * <p>If script or extensions are present and variant is missing, no underscore is
1165      * added before the "#".
1166      *
1167      * <p>This behavior is designed to support debugging and to be compatible with
1168      * previous uses of <code>toString</code> that expected language, country, and variant
1169      * fields only.  To represent a Locale as a String for interchange purposes, use
1170      * {@link #toLanguageTag}.
1171      *
1172      * <p>Examples: <ul><tt>
1173      * <li>en
1174      * <li>de_DE
1175      * <li>_GB
1176      * <li>en_US_WIN
1177      * <li>de__POSIX
1178      * <li>zh_CN_#Hans
1179      * <li>zh_TW_#Hant-x-java
1180      * <li>th_TH_TH_#u-nu-thai</tt></ul>
1181      *
1182      * @return A string representation of the Locale, for debugging.
1183      * @see #getDisplayName
1184      * @see #toLanguageTag
1185      */
1186     @Override
1187     public final String toString() {
1188         boolean l = (baseLocale.getLanguage().length() != 0);
1189         boolean s = (baseLocale.getScript().length() != 0);
1190         boolean r = (baseLocale.getRegion().length() != 0);
1191         boolean v = (baseLocale.getVariant().length() != 0);
1192         boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0);
1193 
1194         StringBuilder result = new StringBuilder(baseLocale.getLanguage());
1195         if (r || (l && (v || s || e))) {
1196             result.append('_')
1197                 .append(baseLocale.getRegion()); // This may just append '_'
1198         }
1199         if (v && (l || r)) {
1200             result.append('_')
1201                 .append(baseLocale.getVariant());
1202         }
1203 
1204         if (s && (l || r)) {
1205             result.append("_#")
1206                 .append(baseLocale.getScript());
1207         }
1208 
1209         if (e && (l || r)) {
1210             result.append('_');
1211             if (!s) {
1212                 result.append('#');
1213             }
1214             result.append(localeExtensions.getID());
1215         }
1216 
1217         return result.toString();
1218     }
1219 
1220     /**
1221      * Returns a well-formed IETF BCP 47 language tag representing
1222      * this locale.
1223      *
1224      * <p>If this <code>Locale</code> has a language, country, or
1225      * variant that does not satisfy the IETF BCP 47 language tag
1226      * syntax requirements, this method handles these fields as
1227      * described below:
1228      *
1229      * <p><b>Language:</b> If language is empty, or not <a
1230      * href="#def_language" >well-formed</a> (for example "a" or
1231      * "e2"), it will be emitted as "und" (Undetermined).
1232      *
1233      * <p><b>Country:</b> If country is not <a
1234      * href="#def_region">well-formed</a> (for example "12" or "USA"),
1235      * it will be omitted.
1236      *
1237      * <p><b>Variant:</b> If variant <b>is</b> <a
1238      * href="#def_variant">well-formed</a>, each sub-segment
1239      * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
1240      * <ul>
1241      *
1242      * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
1243      * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
1244      * ill-formed sub-segment and all following will be appended to
1245      * the private use subtag.  The first appended subtag will be
1246      * "lvariant", followed by the sub-segments in order, separated by
1247      * hyphen. For example, "x-lvariant-WIN",
1248      * "Oracle-x-lvariant-JDK-Standard-Edition".
1249      *
1250      * <li>if any sub-segment does not match
1251      * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
1252      * and the problematic sub-segment and all following sub-segments
1253      * will be omitted.  If the remainder is non-empty, it will be
1254      * emitted as a private use subtag as above (even if the remainder
1255      * turns out to be well-formed).  For example,
1256      * "Solaris_isjustthecoolestthing" is emitted as
1257      * "x-lvariant-Solaris", not as "solaris".</li></ul>
1258      *
1259      * <p><b>Special Conversions:</b> Java supports some old locale
1260      * representations, including deprecated ISO language codes,
1261      * for compatibility. This method performs the following
1262      * conversions:
1263      * <ul>
1264      *
1265      * <li>Deprecated ISO language codes "iw", "ji", and "in" are
1266      * converted to "he", "yi", and "id", respectively.
1267      *
1268      * <li>A locale with language "no", country "NO", and variant
1269      * "NY", representing Norwegian Nynorsk (Norway), is converted
1270      * to a language tag "nn-NO".</li></ul>
1271      *
1272      * <p><b>Note:</b> Although the language tag created by this
1273      * method is well-formed (satisfies the syntax requirements
1274      * defined by the IETF BCP 47 specification), it is not
1275      * necessarily a valid BCP 47 language tag.  For example,
1276      * <pre>
1277      *   new Locale("xx", "YY").toLanguageTag();</pre>
1278      *
1279      * will return "xx-YY", but the language subtag "xx" and the
1280      * region subtag "YY" are invalid because they are not registered
1281      * in the IANA Language Subtag Registry.
1282      *
1283      * @return a BCP47 language tag representing the locale
1284      * @see #forLanguageTag(String)
1285      * @since 1.7
1286      */
1287     public String toLanguageTag() {
1288         LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions);
1289         StringBuilder buf = new StringBuilder();
1290 
1291         String subtag = tag.getLanguage();
1292         if (subtag.length() > 0) {
1293             buf.append(LanguageTag.canonicalizeLanguage(subtag));
1294         }
1295 
1296         subtag = tag.getScript();
1297         if (subtag.length() > 0) {
1298             buf.append(LanguageTag.SEP);
1299             buf.append(LanguageTag.canonicalizeScript(subtag));
1300         }
1301 
1302         subtag = tag.getRegion();
1303         if (subtag.length() > 0) {
1304             buf.append(LanguageTag.SEP);
1305             buf.append(LanguageTag.canonicalizeRegion(subtag));
1306         }
1307 
1308         List<String>subtags = tag.getVariants();
1309         for (String s : subtags) {
1310             buf.append(LanguageTag.SEP);
1311             // preserve casing
1312             buf.append(s);
1313         }
1314 
1315         subtags = tag.getExtensions();
1316         for (String s : subtags) {
1317             buf.append(LanguageTag.SEP);
1318             buf.append(LanguageTag.canonicalizeExtension(s));
1319         }
1320 
1321         subtag = tag.getPrivateuse();
1322         if (subtag.length() > 0) {
1323             if (buf.length() > 0) {
1324                 buf.append(LanguageTag.SEP);
1325             }
1326             buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
1327             // preserve casing
1328             buf.append(subtag);
1329         }
1330 
1331         return buf.toString();
1332     }
1333 
1334     /**
1335      * Returns a locale for the specified IETF BCP 47 language tag string.
1336      *
1337      * <p>If the specified language tag contains any ill-formed subtags,
1338      * the first such subtag and all following subtags are ignored.  Compare
1339      * to {@link Locale.Builder#setLanguageTag} which throws an exception
1340      * in this case.
1341      *
1342      * <p>The following <b>conversions</b> are performed:<ul>
1343      *
1344      * <li>The language code "und" is mapped to language "".
1345      *
1346      * <li>The language codes "he", "yi", and "id" are mapped to "iw",
1347      * "ji", and "in" respectively. (This is the same canonicalization
1348      * that's done in Locale's constructors.)
1349      *
1350      * <li>The portion of a private use subtag prefixed by "lvariant",
1351      * if any, is removed and appended to the variant field in the
1352      * result locale (without case normalization).  If it is then
1353      * empty, the private use subtag is discarded:
1354      *
1355      * <pre>
1356      *     Locale loc;
1357      *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX");
1358      *     loc.getVariant(); // returns "POSIX"
1359      *     loc.getExtension('x'); // returns null
1360      *
1361      *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
1362      *     loc.getVariant(); // returns "POSIX_Abc_Def"
1363      *     loc.getExtension('x'); // returns "urp"
1364      * </pre>
1365      *
1366      * <li>When the languageTag argument contains an extlang subtag,
1367      * the first such subtag is used as the language, and the primary
1368      * language subtag and other extlang subtags are ignored:
1369      *
1370      * <pre>
1371      *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
1372      *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
1373      * </pre>
1374      *
1375      * <li>Case is normalized except for variant tags, which are left
1376      * unchanged.  Language is normalized to lower case, script to
1377      * title case, country to upper case, and extensions to lower
1378      * case.
1379      *
1380      * <li>If, after processing, the locale would exactly match either
1381      * ja_JP_JP or th_TH_TH with no extensions, the appropriate
1382      * extensions are added as though the constructor had been called:
1383      *
1384      * <pre>
1385      *    Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag();
1386      *    // returns "ja-JP-u-ca-japanese-x-lvariant-JP"
1387      *    Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag();
1388      *    // returns "th-TH-u-nu-thai-x-lvariant-TH"
1389      * <pre></ul>
1390      *
1391      * <p>This implements the 'Language-Tag' production of BCP47, and
1392      * so supports grandfathered (regular and irregular) as well as
1393      * private use language tags.  Stand alone private use tags are
1394      * represented as empty language and extension 'x-whatever',
1395      * and grandfathered tags are converted to their canonical replacements
1396      * where they exist.
1397      *
1398      * <p>Grandfathered tags with canonical replacements are as follows:
1399      *
1400      * <table>
1401      * <tbody align="center">
1402      * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
1403      * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
1404      * <tr><td>i-ami</td><td>&nbsp;</td><td>ami</td></tr>
1405      * <tr><td>i-bnn</td><td>&nbsp;</td><td>bnn</td></tr>
1406      * <tr><td>i-hak</td><td>&nbsp;</td><td>hak</td></tr>
1407      * <tr><td>i-klingon</td><td>&nbsp;</td><td>tlh</td></tr>
1408      * <tr><td>i-lux</td><td>&nbsp;</td><td>lb</td></tr>
1409      * <tr><td>i-navajo</td><td>&nbsp;</td><td>nv</td></tr>
1410      * <tr><td>i-pwn</td><td>&nbsp;</td><td>pwn</td></tr>
1411      * <tr><td>i-tao</td><td>&nbsp;</td><td>tao</td></tr>
1412      * <tr><td>i-tay</td><td>&nbsp;</td><td>tay</td></tr>
1413      * <tr><td>i-tsu</td><td>&nbsp;</td><td>tsu</td></tr>
1414      * <tr><td>no-bok</td><td>&nbsp;</td><td>nb</td></tr>
1415      * <tr><td>no-nyn</td><td>&nbsp;</td><td>nn</td></tr>
1416      * <tr><td>sgn-BE-FR</td><td>&nbsp;</td><td>sfb</td></tr>
1417      * <tr><td>sgn-BE-NL</td><td>&nbsp;</td><td>vgt</td></tr>
1418      * <tr><td>sgn-CH-DE</td><td>&nbsp;</td><td>sgg</td></tr>
1419      * <tr><td>zh-guoyu</td><td>&nbsp;</td><td>cmn</td></tr>
1420      * <tr><td>zh-hakka</td><td>&nbsp;</td><td>hak</td></tr>
1421      * <tr><td>zh-min-nan</td><td>&nbsp;</td><td>nan</td></tr>
1422      * <tr><td>zh-xiang</td><td>&nbsp;</td><td>hsn</td></tr>
1423      * </tbody>
1424      * </table>
1425      *
1426      * <p>Grandfathered tags with no modern replacement will be
1427      * converted as follows:
1428      *
1429      * <table>
1430      * <tbody align="center">
1431      * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
1432      * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
1433      * <tr><td>en-GB-oed</td><td>&nbsp;</td><td>en-GB-x-oed</td></tr>
1434      * <tr><td>i-default</td><td>&nbsp;</td><td>en-x-i-default</td></tr>
1435      * <tr><td>i-enochian</td><td>&nbsp;</td><td>und-x-i-enochian</td></tr>
1436      * <tr><td>i-mingo</td><td>&nbsp;</td><td>see-x-i-mingo</td></tr>
1437      * <tr><td>zh-min</td><td>&nbsp;</td><td>nan-x-zh-min</td></tr>
1438      * </tbody>
1439      * </table>
1440      *
1441      * <p>For a list of all grandfathered tags, see the
1442      * IANA Language Subtag Registry (search for "Type: grandfathered").
1443      *
1444      * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
1445      * and <code>forLanguageTag</code> will round-trip.
1446      *
1447      * @param languageTag the language tag
1448      * @return The locale that best represents the language tag.
1449      * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
1450      * @see #toLanguageTag()
1451      * @see java.util.Locale.Builder#setLanguageTag(String)
1452      * @since 1.7
1453      */
1454     public static Locale forLanguageTag(String languageTag) {
1455         LanguageTag tag = LanguageTag.parse(languageTag, null);
1456         InternalLocaleBuilder bldr = new InternalLocaleBuilder();
1457         bldr.setLanguageTag(tag);
1458         BaseLocale base = bldr.getBaseLocale();
1459         LocaleExtensions exts = bldr.getLocaleExtensions();
1460         if (exts == null && base.getVariant().length() > 0) {
1461             exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(),
1462                                               base.getRegion(), base.getVariant());
1463         }
1464         return getInstance(base, exts);
1465     }
1466 
1467     /**
1468      * Returns a three-letter abbreviation of this locale's language.
1469      * If the language matches an ISO 639-1 two-letter code, the
1470      * corresponding ISO 639-2/T three-letter lowercase code is
1471      * returned.  The ISO 639-2 language codes can be found on-line,
1472      * see "Codes for the Representation of Names of Languages Part 2:
1473      * Alpha-3 Code".  If the locale specifies a three-letter
1474      * language, the language is returned as is.  If the locale does
1475      * not specify a language the empty string is returned.
1476      *
1477      * @return A three-letter abbreviation of this locale's language.
1478      * @exception MissingResourceException Throws MissingResourceException if
1479      * three-letter language abbreviation is not available for this locale.
1480      */
1481     public String getISO3Language() throws MissingResourceException {
1482         String lang = baseLocale.getLanguage();
1483         if (lang.length() == 3) {
1484             return lang;
1485         }
1486 
1487         String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
1488         if (language3 == null) {
1489             throw new MissingResourceException("Couldn't find 3-letter language code for "
1490                     + lang, "FormatData_" + toString(), "ShortLanguage");
1491         }
1492         return language3;
1493     }
1494 
1495     /**
1496      * Returns a three-letter abbreviation for this locale's country.
1497      * If the country matches an ISO 3166-1 alpha-2 code, the
1498      * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
1499      * If the locale doesn't specify a country, this will be the empty
1500      * string.
1501      *
1502      * <p>The ISO 3166-1 codes can be found on-line.
1503      *
1504      * @return A three-letter abbreviation of this locale's country.
1505      * @exception MissingResourceException Throws MissingResourceException if the
1506      * three-letter country abbreviation is not available for this locale.
1507      */
1508     public String getISO3Country() throws MissingResourceException {
1509         String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable);
1510         if (country3 == null) {
1511             throw new MissingResourceException("Couldn't find 3-letter country code for "
1512                     + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
1513         }
1514         return country3;
1515     }
1516 
1517     private static final String getISO3Code(String iso2Code, String table) {
1518         int codeLength = iso2Code.length();
1519         if (codeLength == 0) {
1520             return "";
1521         }
1522 
1523         int tableLength = table.length();
1524         int index = tableLength;
1525         if (codeLength == 2) {
1526             char c1 = iso2Code.charAt(0);
1527             char c2 = iso2Code.charAt(1);
1528             for (index = 0; index < tableLength; index += 5) {
1529                 if (table.charAt(index) == c1
1530                     && table.charAt(index + 1) == c2) {
1531                     break;
1532                 }
1533             }
1534         }
1535         return index < tableLength ? table.substring(index + 2, index + 5) : null;
1536     }
1537 
1538     /**
1539      * Returns a name for the locale's language that is appropriate for display to the
1540      * user.
1541      * If possible, the name returned will be localized for the default locale.
1542      * For example, if the locale is fr_FR and the default locale
1543      * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1544      * the default locale is fr_FR, getDisplayLanguage() will return "anglais".
1545      * If the name returned cannot be localized for the default locale,
1546      * (say, we don't have a Japanese name for Croatian),
1547      * this function falls back on the English name, and uses the ISO code as a last-resort
1548      * value.  If the locale doesn't specify a language, this function returns the empty string.
1549      */
1550     public final String getDisplayLanguage() {
1551         return getDisplayLanguage(getDefault(Category.DISPLAY));
1552     }
1553 
1554     /**
1555      * Returns a name for the locale's language that is appropriate for display to the
1556      * user.
1557      * If possible, the name returned will be localized according to inLocale.
1558      * For example, if the locale is fr_FR and inLocale
1559      * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1560      * inLocale is fr_FR, getDisplayLanguage() will return "anglais".
1561      * If the name returned cannot be localized according to inLocale,
1562      * (say, we don't have a Japanese name for Croatian),
1563      * this function falls back on the English name, and finally
1564      * on the ISO code as a last-resort value.  If the locale doesn't specify a language,
1565      * this function returns the empty string.
1566      *
1567      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1568      */
1569     public String getDisplayLanguage(Locale inLocale) {
1570         return getDisplayString(baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE);
1571     }
1572 
1573     /**
1574      * Returns a name for the the locale's script that is appropriate for display to
1575      * the user. If possible, the name will be localized for the default locale.  Returns
1576      * the empty string if this locale doesn't specify a script code.
1577      *
1578      * @return the display name of the script code for the current default locale
1579      * @since 1.7
1580      */
1581     public String getDisplayScript() {
1582         return getDisplayScript(getDefault(Category.DISPLAY));
1583     }
1584 
1585     /**
1586      * Returns a name for the locale's script that is appropriate
1587      * for display to the user. If possible, the name will be
1588      * localized for the given locale. Returns the empty string if
1589      * this locale doesn't specify a script code.
1590      *
1591      * @return the display name of the script code for the current default locale
1592      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
1593      * @since 1.7
1594      */
1595     public String getDisplayScript(Locale inLocale) {
1596         return getDisplayString(baseLocale.getScript(), inLocale, DISPLAY_SCRIPT);
1597     }
1598 
1599     /**
1600      * Returns a name for the locale's country that is appropriate for display to the
1601      * user.
1602      * If possible, the name returned will be localized for the default locale.
1603      * For example, if the locale is fr_FR and the default locale
1604      * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1605      * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis".
1606      * If the name returned cannot be localized for the default locale,
1607      * (say, we don't have a Japanese name for Croatia),
1608      * this function falls back on the English name, and uses the ISO code as a last-resort
1609      * value.  If the locale doesn't specify a country, this function returns the empty string.
1610      */
1611     public final String getDisplayCountry() {
1612         return getDisplayCountry(getDefault(Category.DISPLAY));
1613     }
1614 
1615     /**
1616      * Returns a name for the locale's country that is appropriate for display to the
1617      * user.
1618      * If possible, the name returned will be localized according to inLocale.
1619      * For example, if the locale is fr_FR and inLocale
1620      * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1621      * inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis".
1622      * If the name returned cannot be localized according to inLocale.
1623      * (say, we don't have a Japanese name for Croatia),
1624      * this function falls back on the English name, and finally
1625      * on the ISO code as a last-resort value.  If the locale doesn't specify a country,
1626      * this function returns the empty string.
1627      *
1628      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1629      */
1630     public String getDisplayCountry(Locale inLocale) {
1631         return getDisplayString(baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY);
1632     }
1633 
1634     private String getDisplayString(String code, Locale inLocale, int type) {
1635         if (code.length() == 0) {
1636             return "";
1637         }
1638 
1639         if (inLocale == null) {
1640             throw new NullPointerException();
1641         }
1642 
1643         try {
1644             OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
1645             String key = (type == DISPLAY_VARIANT ? "%%"+code : code);
1646             String result = null;
1647 
1648             // Check whether a provider can provide an implementation that's closer
1649             // to the requested locale than what the Java runtime itself can provide.
1650             LocaleServiceProviderPool pool =
1651                 LocaleServiceProviderPool.getPool(LocaleNameProvider.class);
1652             if (pool.hasProviders()) {
1653                 result = pool.getLocalizedObject(
1654                                     LocaleNameGetter.INSTANCE,
1655                                     inLocale, bundle, key,
1656                                     type, code);
1657             }
1658 
1659             if (result == null) {
1660                 result = bundle.getString(key);
1661             }
1662 
1663             if (result != null) {
1664                 return result;
1665             }
1666         }
1667         catch (Exception e) {
1668             // just fall through
1669         }
1670         return code;
1671     }
1672 
1673     /**
1674      * Returns a name for the locale's variant code that is appropriate for display to the
1675      * user.  If possible, the name will be localized for the default locale.  If the locale
1676      * doesn't specify a variant code, this function returns the empty string.
1677      */
1678     public final String getDisplayVariant() {
1679         return getDisplayVariant(getDefault(Category.DISPLAY));
1680     }
1681 
1682     /**
1683      * Returns a name for the locale's variant code that is appropriate for display to the
1684      * user.  If possible, the name will be localized for inLocale.  If the locale
1685      * doesn't specify a variant code, this function returns the empty string.
1686      *
1687      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1688      */
1689     public String getDisplayVariant(Locale inLocale) {
1690         if (baseLocale.getVariant().length() == 0)
1691             return "";
1692 
1693         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
1694 
1695         String names[] = getDisplayVariantArray(bundle, inLocale);
1696 
1697         // Get the localized patterns for formatting a list, and use
1698         // them to format the list.
1699         String listPattern = null;
1700         String listCompositionPattern = null;
1701         try {
1702             listPattern = bundle.getString("ListPattern");
1703             listCompositionPattern = bundle.getString("ListCompositionPattern");
1704         } catch (MissingResourceException e) {
1705         }
1706         return formatList(names, listPattern, listCompositionPattern);
1707     }
1708 
1709     /**
1710      * Returns a name for the locale that is appropriate for display to the
1711      * user. This will be the values returned by getDisplayLanguage(),
1712      * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
1713      * into a single string. The the non-empty values are used in order,
1714      * with the second and subsequent names in parentheses.  For example:
1715      * <blockquote>
1716      * language (script, country, variant)<br>
1717      * language (country)<br>
1718      * language (variant)<br>
1719      * script (country)<br>
1720      * country<br>
1721      * </blockquote>
1722      * depending on which fields are specified in the locale.  If the
1723      * language, sacript, country, and variant fields are all empty,
1724      * this function returns the empty string.
1725      */
1726     public final String getDisplayName() {
1727         return getDisplayName(getDefault(Category.DISPLAY));
1728     }
1729 
1730     /**
1731      * Returns a name for the locale that is appropriate for display
1732      * to the user.  This will be the values returned by
1733      * getDisplayLanguage(), getDisplayScript(),getDisplayCountry(),
1734      * and getDisplayVariant() assembled into a single string.
1735      * The non-empty values are used in order,
1736      * with the second and subsequent names in parentheses.  For example:
1737      * <blockquote>
1738      * language (script, country, variant)<br>
1739      * language (country)<br>
1740      * language (variant)<br>
1741      * script (country)<br>
1742      * country<br>
1743      * </blockquote>
1744      * depending on which fields are specified in the locale.  If the
1745      * language, script, country, and variant fields are all empty,
1746      * this function returns the empty string.
1747      *
1748      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
1749      */
1750     public String getDisplayName(Locale inLocale) {
1751         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
1752 
1753         String languageName = getDisplayLanguage(inLocale);
1754         String scriptName = getDisplayScript(inLocale);
1755         String countryName = getDisplayCountry(inLocale);
1756         String[] variantNames = getDisplayVariantArray(bundle, inLocale);
1757 
1758         // Get the localized patterns for formatting a display name.
1759         String displayNamePattern = null;
1760         String listPattern = null;
1761         String listCompositionPattern = null;
1762         try {
1763             displayNamePattern = bundle.getString("DisplayNamePattern");
1764             listPattern = bundle.getString("ListPattern");
1765             listCompositionPattern = bundle.getString("ListCompositionPattern");
1766         } catch (MissingResourceException e) {
1767         }
1768 
1769         // The display name consists of a main name, followed by qualifiers.
1770         // Typically, the format is "MainName (Qualifier, Qualifier)" but this
1771         // depends on what pattern is stored in the display locale.
1772         String   mainName       = null;
1773         String[] qualifierNames = null;
1774 
1775         // The main name is the language, or if there is no language, the script,
1776         // then if no script, the country. If there is no language/script/country
1777         // (an anomalous situation) then the display name is simply the variant's
1778         // display name.
1779         if (languageName.length() == 0 && scriptName.length() == 0 && countryName.length() == 0) {
1780             if (variantNames.length == 0) {
1781                 return "";
1782             } else {
1783                 return formatList(variantNames, listPattern, listCompositionPattern);
1784             }
1785         }
1786         ArrayList<String> names = new ArrayList<>(4);
1787         if (languageName.length() != 0) {
1788             names.add(languageName);
1789         }
1790         if (scriptName.length() != 0) {
1791             names.add(scriptName);
1792         }
1793         if (countryName.length() != 0) {
1794             names.add(countryName);
1795         }
1796         if (variantNames.length != 0) {
1797             for (String var : variantNames) {
1798                 names.add(var);
1799             }
1800         }
1801 
1802         // The first one in the main name
1803         mainName = names.get(0);
1804 
1805         // Others are qualifiers
1806         int numNames = names.size();
1807         qualifierNames = (numNames > 1) ?
1808                 names.subList(1, numNames).toArray(new String[numNames - 1]) : new String[0];
1809 
1810         // Create an array whose first element is the number of remaining
1811         // elements.  This serves as a selector into a ChoiceFormat pattern from
1812         // the resource.  The second and third elements are the main name and
1813         // the qualifier; if there are no qualifiers, the third element is
1814         // unused by the format pattern.
1815         Object[] displayNames = {
1816             new Integer(qualifierNames.length != 0 ? 2 : 1),
1817             mainName,
1818             // We could also just call formatList() and have it handle the empty
1819             // list case, but this is more efficient, and we want it to be
1820             // efficient since all the language-only locales will not have any
1821             // qualifiers.
1822             qualifierNames.length != 0 ? formatList(qualifierNames, listPattern, listCompositionPattern) : null
1823         };
1824 
1825         if (displayNamePattern != null) {
1826             return new MessageFormat(displayNamePattern).format(displayNames);
1827         }
1828         else {
1829             // If we cannot get the message format pattern, then we use a simple
1830             // hard-coded pattern.  This should not occur in practice unless the
1831             // installation is missing some core files (FormatData etc.).
1832             StringBuilder result = new StringBuilder();
1833             result.append((String)displayNames[1]);
1834             if (displayNames.length > 2) {
1835                 result.append(" (");
1836                 result.append((String)displayNames[2]);
1837                 result.append(')');
1838             }
1839             return result.toString();
1840         }
1841     }
1842 
1843     /**
1844      * Overrides Cloneable.
1845      */
1846     public Object clone()
1847     {
1848         try {
1849             Locale that = (Locale)super.clone();
1850             return that;
1851         } catch (CloneNotSupportedException e) {
1852             throw new InternalError(e);
1853         }
1854     }
1855 
1856     /**
1857      * Override hashCode.
1858      * Since Locales are often used in hashtables, caches the value
1859      * for speed.
1860      */
1861     @Override
1862     public int hashCode() {
1863         int hc = hashCodeValue;
1864         if (hc == 0) {
1865             hc = baseLocale.hashCode();
1866             if (localeExtensions != null) {
1867                 hc ^= localeExtensions.hashCode();
1868             }
1869             hashCodeValue = hc;
1870         }
1871         return hc;
1872     }
1873 
1874     // Overrides
1875 
1876     /**
1877      * Returns true if this Locale is equal to another object.  A Locale is
1878      * deemed equal to another Locale with identical language, script, country,
1879      * variant and extensions, and unequal to all other objects.
1880      *
1881      * @return true if this Locale is equal to the specified object.
1882      */
1883     @Override
1884     public boolean equals(Object obj) {
1885         if (this == obj)                      // quick check
1886             return true;
1887         if (!(obj instanceof Locale))
1888             return false;
1889         BaseLocale otherBase = ((Locale)obj).baseLocale;
1890         if (!baseLocale.equals(otherBase)) {
1891             return false;
1892         }
1893         if (localeExtensions == null) {
1894             return ((Locale)obj).localeExtensions == null;
1895         }
1896         return localeExtensions.equals(((Locale)obj).localeExtensions);
1897     }
1898 
1899     // ================= privates =====================================
1900 
1901     private transient BaseLocale baseLocale;
1902     private transient LocaleExtensions localeExtensions;
1903 
1904     /**
1905      * Calculated hashcode
1906      */
1907     private transient volatile int hashCodeValue = 0;
1908 
1909     private volatile static Locale defaultLocale = initDefault();
1910     private volatile static Locale defaultDisplayLocale = null;
1911     private volatile static Locale defaultFormatLocale = null;
1912 
1913     /**
1914      * Return an array of the display names of the variant.
1915      * @param bundle the ResourceBundle to use to get the display names
1916      * @return an array of display names, possible of zero length.
1917      */
1918     private String[] getDisplayVariantArray(OpenListResourceBundle bundle, Locale inLocale) {
1919         // Split the variant name into tokens separated by '_'.
1920         StringTokenizer tokenizer = new StringTokenizer(baseLocale.getVariant(), "_");
1921         String[] names = new String[tokenizer.countTokens()];
1922 
1923         // For each variant token, lookup the display name.  If
1924         // not found, use the variant name itself.
1925         for (int i=0; i<names.length; ++i) {
1926             names[i] = getDisplayString(tokenizer.nextToken(),
1927                                 inLocale, DISPLAY_VARIANT);
1928         }
1929 
1930         return names;
1931     }
1932 
1933     /**
1934      * Format a list using given pattern strings.
1935      * If either of the patterns is null, then a the list is
1936      * formatted by concatenation with the delimiter ','.
1937      * @param stringList the list of strings to be formatted.
1938      * @param listPattern should create a MessageFormat taking 0-3 arguments
1939      * and formatting them into a list.
1940      * @param listCompositionPattern should take 2 arguments
1941      * and is used by composeList.
1942      * @return a string representing the list.
1943      */
1944     private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) {
1945         // If we have no list patterns, compose the list in a simple,
1946         // non-localized way.
1947         if (listPattern == null || listCompositionPattern == null) {
1948             StringBuffer result = new StringBuffer();
1949             for (int i=0; i<stringList.length; ++i) {
1950                 if (i>0) result.append(',');
1951                 result.append(stringList[i]);
1952             }
1953             return result.toString();
1954         }
1955 
1956         // Compose the list down to three elements if necessary
1957         if (stringList.length > 3) {
1958             MessageFormat format = new MessageFormat(listCompositionPattern);
1959             stringList = composeList(format, stringList);
1960         }
1961 
1962         // Rebuild the argument list with the list length as the first element
1963         Object[] args = new Object[stringList.length + 1];
1964         System.arraycopy(stringList, 0, args, 1, stringList.length);
1965         args[0] = new Integer(stringList.length);
1966 
1967         // Format it using the pattern in the resource
1968         MessageFormat format = new MessageFormat(listPattern);
1969         return format.format(args);
1970     }
1971 
1972     /**
1973      * Given a list of strings, return a list shortened to three elements.
1974      * Shorten it by applying the given format to the first two elements
1975      * recursively.
1976      * @param format a format which takes two arguments
1977      * @param list a list of strings
1978      * @return if the list is three elements or shorter, the same list;
1979      * otherwise, a new list of three elements.
1980      */
1981     private static String[] composeList(MessageFormat format, String[] list) {
1982         if (list.length <= 3) return list;
1983 
1984         // Use the given format to compose the first two elements into one
1985         String[] listItems = { list[0], list[1] };
1986         String newItem = format.format(listItems);
1987 
1988         // Form a new list one element shorter
1989         String[] newList = new String[list.length-1];
1990         System.arraycopy(list, 2, newList, 1, newList.length-1);
1991         newList[0] = newItem;
1992 
1993         // Recurse
1994         return composeList(format, newList);
1995     }
1996 
1997     /**
1998      * @serialField language    String
1999      *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
2000      * @serialField country     String
2001      *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
2002      * @serialField variant     String
2003      *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
2004      * @serialField hashcode    int
2005      *      deprecated, for forward compatibility only
2006      * @serialField script      String
2007      *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
2008      * @serialField extensions  String
2009      *      canonical representation of extensions, that is,
2010      *      BCP47 extensions in alphabetical order followed by
2011      *      BCP47 private use subtags, all in lower case letters
2012      *      separated by HYPHEN-MINUS characters.
2013      *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
2014      *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
2015      */
2016     private static final ObjectStreamField[] serialPersistentFields = {
2017         new ObjectStreamField("language", String.class),
2018         new ObjectStreamField("country", String.class),
2019         new ObjectStreamField("variant", String.class),
2020         new ObjectStreamField("hashcode", int.class),
2021         new ObjectStreamField("script", String.class),
2022         new ObjectStreamField("extensions", String.class),
2023     };
2024 
2025     /**
2026      * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
2027      * @param out the <code>ObjectOutputStream</code> to write
2028      * @throws IOException
2029      * @since 1.7
2030      */
2031     private void writeObject(ObjectOutputStream out) throws IOException {
2032         ObjectOutputStream.PutField fields = out.putFields();
2033         fields.put("language", baseLocale.getLanguage());
2034         fields.put("script", baseLocale.getScript());
2035         fields.put("country", baseLocale.getRegion());
2036         fields.put("variant", baseLocale.getVariant());
2037         fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID());
2038         fields.put("hashcode", -1); // place holder just for backward support
2039         out.writeFields();
2040     }
2041 
2042     /**
2043      * Deserializes this <code>Locale</code>.
2044      * @param in the <code>ObjectInputStream</code> to read
2045      * @throws IOException
2046      * @throws ClassNotFoundException
2047      * @throws IllformdLocaleException
2048      * @since 1.7
2049      */
2050     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
2051         ObjectInputStream.GetField fields = in.readFields();
2052         String language = (String)fields.get("language", "");
2053         String script = (String)fields.get("script", "");
2054         String country = (String)fields.get("country", "");
2055         String variant = (String)fields.get("variant", "");
2056         String extStr = (String)fields.get("extensions", "");
2057         baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
2058         if (extStr.length() > 0) {
2059             try {
2060                 InternalLocaleBuilder bldr = new InternalLocaleBuilder();
2061                 bldr.setExtensions(extStr);
2062                 localeExtensions = bldr.getLocaleExtensions();
2063             } catch (LocaleSyntaxException e) {
2064                 throw new IllformedLocaleException(e.getMessage());
2065             }
2066         } else {
2067             localeExtensions = null;
2068         }
2069     }
2070 
2071     /**
2072      * Returns a cached <code>Locale</code> instance equivalent to
2073      * the deserialized <code>Locale</code>. When serialized
2074      * language, country and variant fields read from the object data stream
2075      * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
2076      * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
2077      * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
2078      * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a>
2079      * for more information.
2080      *
2081      * @return an instance of <code>Locale</code> equivalent to
2082      * the deserialized <code>Locale</code>.
2083      * @throws java.io.ObjectStreamException
2084      */
2085     private Object readResolve() throws java.io.ObjectStreamException {
2086         return getInstance(baseLocale.getLanguage(), baseLocale.getScript(),
2087                 baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
2088     }
2089 
2090     private static volatile String[] isoLanguages = null;
2091 
2092     private static volatile String[] isoCountries = null;
2093 
2094     private static String convertOldISOCodes(String language) {
2095         // we accept both the old and the new ISO codes for the languages whose ISO
2096         // codes have changed, but we always store the OLD code, for backward compatibility
2097         language = LocaleUtils.toLowerString(language).intern();
2098         if (language == "he") {
2099             return "iw";
2100         } else if (language == "yi") {
2101             return "ji";
2102         } else if (language == "id") {
2103             return "in";
2104         } else {
2105             return language;
2106         }
2107     }
2108 
2109     private static LocaleExtensions getCompatibilityExtensions(String language,
2110                                                                String script,
2111                                                                String country,
2112                                                                String variant) {
2113         LocaleExtensions extensions = null;
2114         // Special cases for backward compatibility support
2115         if (LocaleUtils.caseIgnoreMatch(language, "ja")
2116                 && script.length() == 0
2117                 && LocaleUtils.caseIgnoreMatch(country, "jp")
2118                 && "JP".equals(variant)) {
2119             // ja_JP_JP -> u-ca-japanese (calendar = japanese)
2120             extensions = LocaleExtensions.CALENDAR_JAPANESE;
2121         } else if (LocaleUtils.caseIgnoreMatch(language, "th")
2122                 && script.length() == 0
2123                 && LocaleUtils.caseIgnoreMatch(country, "th")
2124                 && "TH".equals(variant)) {
2125             // th_TH_TH -> u-nu-thai (numbersystem = thai)
2126             extensions = LocaleExtensions.NUMBER_THAI;
2127         }
2128         return extensions;
2129     }
2130 
2131     /**
2132      * Obtains a localized locale names from a LocaleNameProvider
2133      * implementation.
2134      */
2135     private static class LocaleNameGetter
2136         implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> {
2137         private static final LocaleNameGetter INSTANCE = new LocaleNameGetter();
2138 
2139         public String getObject(LocaleNameProvider localeNameProvider,
2140                                 Locale locale,
2141                                 String key,
2142                                 Object... params) {
2143             assert params.length == 2;
2144             int type = (Integer)params[0];
2145             String code = (String)params[1];
2146 
2147             switch(type) {
2148             case DISPLAY_LANGUAGE:
2149                 return localeNameProvider.getDisplayLanguage(code, locale);
2150             case DISPLAY_COUNTRY:
2151                 return localeNameProvider.getDisplayCountry(code, locale);
2152             case DISPLAY_VARIANT:
2153                 return localeNameProvider.getDisplayVariant(code, locale);
2154             case DISPLAY_SCRIPT:
2155                 return localeNameProvider.getDisplayScript(code, locale);
2156             default:
2157                 assert false; // shouldn't happen
2158             }
2159 
2160             return null;
2161         }
2162     }
2163 
2164     /**
2165      * Enum for locale categories.  These locale categories are used to get/set
2166      * the default locale for the specific functionality represented by the
2167      * category.
2168      *
2169      * @see #getDefault(Locale.Category)
2170      * @see #setDefault(Locale.Category, Locale)
2171      * @since 1.7
2172      */
2173     public enum Category {
2174 
2175         /**
2176          * Category used to represent the default locale for
2177          * displaying user interfaces.
2178          */
2179         DISPLAY("user.language.display",
2180                 "user.script.display",
2181                 "user.country.display",
2182                 "user.variant.display"),
2183 
2184         /**
2185          * Category used to represent the default locale for
2186          * formatting dates, numbers, and/or currencies.
2187          */
2188         FORMAT("user.language.format",
2189                "user.script.format",
2190                "user.country.format",
2191                "user.variant.format");
2192 
2193         Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
2194             this.languageKey = languageKey;
2195             this.scriptKey = scriptKey;
2196             this.countryKey = countryKey;
2197             this.variantKey = variantKey;
2198         }
2199 
2200         final String languageKey;
2201         final String scriptKey;
2202         final String countryKey;
2203         final String variantKey;
2204     }
2205 
2206     /**
2207      * <code>Builder</code> is used to build instances of <code>Locale</code>
2208      * from values configured by the setters.  Unlike the <code>Locale</code>
2209      * constructors, the <code>Builder</code> checks if a value configured by a
2210      * setter satisfies the syntax requirements defined by the <code>Locale</code>
2211      * class.  A <code>Locale</code> object created by a <code>Builder</code> is
2212      * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
2213      * without losing information.
2214      *
2215      * <p><b>Note:</b> The <code>Locale</code> class does not provide any
2216      * syntactic restrictions on variant, while BCP 47 requires each variant
2217      * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
2218      * alphanumerics.  The method <code>setVariant</code> throws
2219      * <code>IllformedLocaleException</code> for a variant that does not satisfy
2220      * this restriction. If it is necessary to support such a variant, use a
2221      * Locale constructor.  However, keep in mind that a <code>Locale</code>
2222      * object created this way might lose the variant information when
2223      * transformed to a BCP 47 language tag.
2224      *
2225      * <p>The following example shows how to create a <code>Locale</code> object
2226      * with the <code>Builder</code>.
2227      * <blockquote>
2228      * <pre>
2229      *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
2230      * </pre>
2231      * </blockquote>
2232      *
2233      * <p>Builders can be reused; <code>clear()</code> resets all
2234      * fields to their default values.
2235      *
2236      * @see Locale#forLanguageTag
2237      * @since 1.7
2238      */
2239     public static final class Builder {
2240         private final InternalLocaleBuilder localeBuilder;
2241 
2242         /**
2243          * Constructs an empty Builder. The default value of all
2244          * fields, extensions, and private use information is the
2245          * empty string.
2246          */
2247         public Builder() {
2248             localeBuilder = new InternalLocaleBuilder();
2249         }
2250 
2251         /**
2252          * Resets the <code>Builder</code> to match the provided
2253          * <code>locale</code>.  Existing state is discarded.
2254          *
2255          * <p>All fields of the locale must be well-formed, see {@link Locale}.
2256          *
2257          * <p>Locales with any ill-formed fields cause
2258          * <code>IllformedLocaleException</code> to be thrown, except for the
2259          * following three cases which are accepted for compatibility
2260          * reasons:<ul>
2261          * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
2262          * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
2263          * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
2264          *
2265          * @param locale the locale
2266          * @return This builder.
2267          * @throws IllformedLocaleException if <code>locale</code> has
2268          * any ill-formed fields.
2269          * @throws NullPointerException if <code>locale</code> is null.
2270          */
2271         public Builder setLocale(Locale locale) {
2272             try {
2273                 localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions);
2274             } catch (LocaleSyntaxException e) {
2275                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2276             }
2277             return this;
2278         }
2279 
2280         /**
2281          * Resets the Builder to match the provided IETF BCP 47
2282          * language tag.  Discards the existing state.  Null and the
2283          * empty string cause the builder to be reset, like {@link
2284          * #clear}.  Grandfathered tags (see {@link
2285          * Locale#forLanguageTag}) are converted to their canonical
2286          * form before being processed.  Otherwise, the language tag
2287          * must be well-formed (see {@link Locale}) or an exception is
2288          * thrown (unlike <code>Locale.forLanguageTag</code>, which
2289          * just discards ill-formed and following portions of the
2290          * tag).
2291          *
2292          * @param languageTag the language tag
2293          * @return This builder.
2294          * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
2295          * @see Locale#forLanguageTag(String)
2296          */
2297         public Builder setLanguageTag(String languageTag) {
2298             ParseStatus sts = new ParseStatus();
2299             LanguageTag tag = LanguageTag.parse(languageTag, sts);
2300             if (sts.isError()) {
2301                 throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
2302             }
2303             localeBuilder.setLanguageTag(tag);
2304             return this;
2305         }
2306 
2307         /**
2308          * Sets the language.  If <code>language</code> is the empty string or
2309          * null, the language in this <code>Builder</code> is removed.  Otherwise,
2310          * the language must be <a href="./Locale.html#def_language">well-formed</a>
2311          * or an exception is thrown.
2312          *
2313          * <p>The typical language value is a two or three-letter language
2314          * code as defined in ISO639.
2315          *
2316          * @param language the language
2317          * @return This builder.
2318          * @throws IllformedLocaleException if <code>language</code> is ill-formed
2319          */
2320         public Builder setLanguage(String language) {
2321             try {
2322                 localeBuilder.setLanguage(language);
2323             } catch (LocaleSyntaxException e) {
2324                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2325             }
2326             return this;
2327         }
2328 
2329         /**
2330          * Sets the script. If <code>script</code> is null or the empty string,
2331          * the script in this <code>Builder</code> is removed.
2332          * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
2333          * exception is thrown.
2334          *
2335          * <p>The typical script value is a four-letter script code as defined by ISO 15924.
2336          *
2337          * @param script the script
2338          * @return This builder.
2339          * @throws IllformedLocaleException if <code>script</code> is ill-formed
2340          */
2341         public Builder setScript(String script) {
2342             try {
2343                 localeBuilder.setScript(script);
2344             } catch (LocaleSyntaxException e) {
2345                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2346             }
2347             return this;
2348         }
2349 
2350         /**
2351          * Sets the region.  If region is null or the empty string, the region
2352          * in this <code>Builder</code> is removed.  Otherwise,
2353          * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
2354          * exception is thrown.
2355          *
2356          * <p>The typical region value is a two-letter ISO 3166 code or a
2357          * three-digit UN M.49 area code.
2358          *
2359          * <p>The country value in the <code>Locale</code> created by the
2360          * <code>Builder</code> is always normalized to upper case.
2361          *
2362          * @param region the region
2363          * @return This builder.
2364          * @throws IllformedLocaleException if <code>region</code> is ill-formed
2365          */
2366         public Builder setRegion(String region) {
2367             try {
2368                 localeBuilder.setRegion(region);
2369             } catch (LocaleSyntaxException e) {
2370                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2371             }
2372             return this;
2373         }
2374 
2375         /**
2376          * Sets the variant.  If variant is null or the empty string, the
2377          * variant in this <code>Builder</code> is removed.  Otherwise, it
2378          * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
2379          * subtags, or an exception is thrown.
2380          *
2381          * <p><b>Note:</b> This method checks if <code>variant</code>
2382          * satisfies the IETF BCP 47 variant subtag's syntax requirements,
2383          * and normalizes the value to lowercase letters.  However,
2384          * the <code>Locale</code> class does not impose any syntactic
2385          * restriction on variant, and the variant value in
2386          * <code>Locale</code> is case sensitive.  To set such a variant,
2387          * use a Locale constructor.
2388          *
2389          * @param variant the variant
2390          * @return This builder.
2391          * @throws IllformedLocaleException if <code>variant</code> is ill-formed
2392          */
2393         public Builder setVariant(String variant) {
2394             try {
2395                 localeBuilder.setVariant(variant);
2396             } catch (LocaleSyntaxException e) {
2397                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2398             }
2399             return this;
2400         }
2401 
2402         /**
2403          * Sets the extension for the given key. If the value is null or the
2404          * empty string, the extension is removed.  Otherwise, the extension
2405          * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
2406          * is thrown.
2407          *
2408          * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
2409          * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
2410          * Setting a value for this key replaces any existing Unicode locale key/type
2411          * pairs with those defined in the extension.
2412          *
2413          * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
2414          * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
2415          * well-formed, the value for this key needs only to have subtags of one to
2416          * eight alphanumeric characters, not two to eight as in the general case.
2417          *
2418          * @param key the extension key
2419          * @param value the extension value
2420          * @return This builder.
2421          * @throws IllformedLocaleException if <code>key</code> is illegal
2422          * or <code>value</code> is ill-formed
2423          * @see #setUnicodeLocaleKeyword(String, String)
2424          */
2425         public Builder setExtension(char key, String value) {
2426             try {
2427                 localeBuilder.setExtension(key, value);
2428             } catch (LocaleSyntaxException e) {
2429                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2430             }
2431             return this;
2432         }
2433 
2434         /**
2435          * Sets the Unicode locale keyword type for the given key.  If the type
2436          * is null, the Unicode keyword is removed.  Otherwise, the key must be
2437          * non-null and both key and type must be <a
2438          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2439          * is thrown.
2440          *
2441          * <p>Keys and types are converted to lower case.
2442          *
2443          * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
2444          * replaces all Unicode locale keywords with those defined in the
2445          * extension.
2446          *
2447          * @param key the Unicode locale key
2448          * @param type the Unicode locale type
2449          * @return This builder.
2450          * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
2451          * is ill-formed
2452          * @throws NullPointerException if <code>key</code> is null
2453          * @see #setExtension(char, String)
2454          */
2455         public Builder setUnicodeLocaleKeyword(String key, String type) {
2456             try {
2457                 localeBuilder.setUnicodeLocaleKeyword(key, type);
2458             } catch (LocaleSyntaxException e) {
2459                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2460             }
2461             return this;
2462         }
2463 
2464         /**
2465          * Adds a unicode locale attribute, if not already present, otherwise
2466          * has no effect.  The attribute must not be null and must be <a
2467          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2468          * is thrown.
2469          *
2470          * @param attribute the attribute
2471          * @return This builder.
2472          * @throws NullPointerException if <code>attribute</code> is null
2473          * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2474          * @see #setExtension(char, String)
2475          */
2476         public Builder addUnicodeLocaleAttribute(String attribute) {
2477             try {
2478                 localeBuilder.addUnicodeLocaleAttribute(attribute);
2479             } catch (LocaleSyntaxException e) {
2480                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2481             }
2482             return this;
2483         }
2484 
2485         /**
2486          * Removes a unicode locale attribute, if present, otherwise has no
2487          * effect.  The attribute must not be null and must be <a
2488          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2489          * is thrown.
2490          *
2491          * <p>Attribute comparision for removal is case-insensitive.
2492          *
2493          * @param attribute the attribute
2494          * @return This builder.
2495          * @throws NullPointerException if <code>attribute</code> is null
2496          * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2497          * @see #setExtension(char, String)
2498          */
2499         public Builder removeUnicodeLocaleAttribute(String attribute) {
2500             try {
2501                 localeBuilder.removeUnicodeLocaleAttribute(attribute);
2502             } catch (LocaleSyntaxException e) {
2503                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2504             }
2505             return this;
2506         }
2507 
2508         /**
2509          * Resets the builder to its initial, empty state.
2510          *
2511          * @return This builder.
2512          */
2513         public Builder clear() {
2514             localeBuilder.clear();
2515             return this;
2516         }
2517 
2518         /**
2519          * Resets the extensions to their initial, empty state.
2520          * Language, script, region and variant are unchanged.
2521          *
2522          * @return This builder.
2523          * @see #setExtension(char, String)
2524          */
2525         public Builder clearExtensions() {
2526             localeBuilder.clearExtensions();
2527             return this;
2528         }
2529 
2530         /**
2531          * Returns an instance of <code>Locale</code> created from the fields set
2532          * on this builder.
2533          *
2534          * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
2535          * when constructing a Locale. (Grandfathered tags are handled in
2536          * {@link #setLanguageTag}.)
2537          *
2538          * @return A Locale.
2539          */
2540         public Locale build() {
2541             BaseLocale baseloc = localeBuilder.getBaseLocale();
2542             LocaleExtensions extensions = localeBuilder.getLocaleExtensions();
2543             if (extensions == null && baseloc.getVariant().length() > 0) {
2544                 extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(),
2545                         baseloc.getRegion(), baseloc.getVariant());
2546             }
2547             return Locale.getInstance(baseloc, extensions);
2548         }
2549     }
2550 }