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