|
toLanguageTag
* and <code>forLanguageTag will round-trip.
*
* @param languageTag the language tag
* @return The locale that best represents the language tag.
* @throws NullPointerException if <code>languageTag is null
* @see #toLanguageTag()
* @see java.util.Locale.Builder#setLanguageTag(String)
* @since 1.7
*/
public static Locale forLanguageTag(String languageTag) {
LanguageTag tag = LanguageTag.parse(languageTag, null);
InternalLocaleBuilder bldr = new InternalLocaleBuilder();
bldr.setLanguageTag(tag);
BaseLocale base = bldr.getBaseLocale();
LocaleExtensions exts = bldr.getLocaleExtensions();
if (exts == null && base.getVariant().length() > 0) {
exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(),
base.getRegion(), base.getVariant());
}
return getInstance(base, exts);
}
/**
* Returns a three-letter abbreviation of this locale's language.
* If the language matches an ISO 639-1 two-letter code, the
* corresponding ISO 639-2/T three-letter lowercase code is
* returned. The ISO 639-2 language codes can be found on-line,
* see "Codes for the Representation of Names of Languages Part 2:
* Alpha-3 Code". If the locale specifies a three-letter
* language, the language is returned as is. If the locale does
* not specify a language the empty string is returned.
*
* @return A three-letter abbreviation of this locale's language.
* @exception MissingResourceException Throws MissingResourceException if
* three-letter language abbreviation is not available for this locale.
*/
public String getISO3Language() throws MissingResourceException {
String lang = baseLocale.getLanguage();
if (lang.length() == 3) {
return lang;
}
String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
if (language3 == null) {
throw new MissingResourceException("Couldn't find 3-letter language code for "
+ lang, "FormatData_" + toString(), "ShortLanguage");
}
return language3;
}
/**
* Returns a three-letter abbreviation for this locale's country.
* If the country matches an ISO 3166-1 alpha-2 code, the
* corresponding ISO 3166-1 alpha-3 uppercase code is returned.
* If the locale doesn't specify a country, this will be the empty
* string.
*
* <p>The ISO 3166-1 codes can be found on-line.
*
* @return A three-letter abbreviation of this locale's country.
* @exception MissingResourceException Throws MissingResourceException if the
* three-letter country abbreviation is not available for this locale.
*/
public String getISO3Country() throws MissingResourceException {
String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable);
if (country3 == null) {
throw new MissingResourceException("Couldn't find 3-letter country code for "
+ baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
}
return country3;
}
private static String getISO3Code(String iso2Code, String table) {
int codeLength = iso2Code.length();
if (codeLength == 0) {
return "";
}
int tableLength = table.length();
int index = tableLength;
if (codeLength == 2) {
char c1 = iso2Code.charAt(0);
char c2 = iso2Code.charAt(1);
for (index = 0; index < tableLength; index += 5) {
if (table.charAt(index) == c1
&& table.charAt(index + 1) == c2) {
break;
}
}
}
return index < tableLength ? table.substring(index + 2, index + 5) : null;
}
/**
* Returns a name for the locale's language that is appropriate for display to the
* user.
* If possible, the name returned will be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale.
* For example, if the locale is fr_FR and the default
* {@link Locale.Category#DISPLAY DISPLAY} locale
* is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
* the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR,
* getDisplayLanguage() will return "anglais".
* If the name returned cannot be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale,
* (say, we don't have a Japanese name for Croatian),
* this function falls back on the English name, and uses the ISO code as a last-resort
* value. If the locale doesn't specify a language, this function returns the empty string.
*
* @return The name of the display language.
*/
public final String getDisplayLanguage() {
return getDisplayLanguage(getDefault(Category.DISPLAY));
}
/**
* Returns a name for the locale's language that is appropriate for display to the
* user.
* If possible, the name returned will be localized according to inLocale.
* For example, if the locale is fr_FR and inLocale
* is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
* inLocale is fr_FR, getDisplayLanguage() will return "anglais".
* If the name returned cannot be localized according to inLocale,
* (say, we don't have a Japanese name for Croatian),
* this function falls back on the English name, and finally
* on the ISO code as a last-resort value. If the locale doesn't specify a language,
* this function returns the empty string.
*
* @param inLocale The locale for which to retrieve the display language.
* @return The name of the display language appropriate to the given locale.
* @exception NullPointerException if <code>inLocale is null
*/
public String getDisplayLanguage(Locale inLocale) {
return getDisplayString(baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE);
}
/**
* Returns a name for the the locale's script that is appropriate for display to
* the user. If possible, the name will be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale. Returns
* the empty string if this locale doesn't specify a script code.
*
* @return the display name of the script code for the current default
* {@link Locale.Category#DISPLAY DISPLAY} locale
* @since 1.7
*/
public String getDisplayScript() {
return getDisplayScript(getDefault(Category.DISPLAY));
}
/**
* Returns a name for the locale's script that is appropriate
* for display to the user. If possible, the name will be
* localized for the given locale. Returns the empty string if
* this locale doesn't specify a script code.
*
* @param inLocale The locale for which to retrieve the display script.
* @return the display name of the script code for the current default
* {@link Locale.Category#DISPLAY DISPLAY} locale
* @throws NullPointerException if <code>inLocale is null
* @since 1.7
*/
public String getDisplayScript(Locale inLocale) {
return getDisplayString(baseLocale.getScript(), inLocale, DISPLAY_SCRIPT);
}
/**
* Returns a name for the locale's country that is appropriate for display to the
* user.
* If possible, the name returned will be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale.
* For example, if the locale is fr_FR and the default
* {@link Locale.Category#DISPLAY DISPLAY} locale
* is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
* the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR,
* getDisplayCountry() will return "Etats-Unis".
* If the name returned cannot be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale,
* (say, we don't have a Japanese name for Croatia),
* this function falls back on the English name, and uses the ISO code as a last-resort
* value. If the locale doesn't specify a country, this function returns the empty string.
*
* @return The name of the country appropriate to the locale.
*/
public final String getDisplayCountry() {
return getDisplayCountry(getDefault(Category.DISPLAY));
}
/**
* Returns a name for the locale's country that is appropriate for display to the
* user.
* If possible, the name returned will be localized according to inLocale.
* For example, if the locale is fr_FR and inLocale
* is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
* inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis".
* If the name returned cannot be localized according to inLocale.
* (say, we don't have a Japanese name for Croatia),
* this function falls back on the English name, and finally
* on the ISO code as a last-resort value. If the locale doesn't specify a country,
* this function returns the empty string.
*
* @param inLocale The locale for which to retrieve the display country.
* @return The name of the country appropriate to the given locale.
* @exception NullPointerException if <code>inLocale is null
*/
public String getDisplayCountry(Locale inLocale) {
return getDisplayString(baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY);
}
private String getDisplayString(String code, Locale inLocale, int type) {
if (code.length() == 0) {
return "";
}
if (inLocale == null) {
throw new NullPointerException();
}
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(LocaleNameProvider.class);
String key = (type == DISPLAY_VARIANT ? "%%"+code : code);
String result = pool.getLocalizedObject(
LocaleNameGetter.INSTANCE,
inLocale, key, type, code);
if (result != null) {
return result;
}
return code;
}
/**
* Returns a name for the locale's variant code that is appropriate for display to the
* user. If possible, the name will be localized for the default
* {@link Locale.Category#DISPLAY DISPLAY} locale. If the locale
* doesn't specify a variant code, this function returns the empty string.
*
* @return The name of the display variant code appropriate to the locale.
*/
public final String getDisplayVariant() {
return getDisplayVariant(getDefault(Category.DISPLAY));
}
/**
* Returns a name for the locale's variant code that is appropriate for display to the
* user. If possible, the name will be localized for inLocale. If the locale
* doesn't specify a variant code, this function returns the empty string.
*
* @param inLocale The locale for which to retrieve the display variant code.
* @return The name of the display variant code appropriate to the given locale.
* @exception NullPointerException if <code>inLocale is null
*/
public String getDisplayVariant(Locale inLocale) {
if (baseLocale.getVariant().length() == 0)
return "";
LocaleResources lr = LocaleProviderAdapter.forJRE().getLocaleResources(inLocale);
String names[] = getDisplayVariantArray(inLocale);
// Get the localized patterns for formatting a list, and use
// them to format the list.
return formatList(names,
lr.getLocaleName("ListPattern"),
lr.getLocaleName("ListCompositionPattern"));
}
/**
* Returns a name for the locale that is appropriate for display to the
* user. This will be the values returned by getDisplayLanguage(),
* getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
* into a single string. The the non-empty values are used in order,
* with the second and subsequent names in parentheses. For example:
* <blockquote>
* language (script, country, variant)<br>
* language (country)<br>
* language (variant)<br>
* script (country)<br>
* country<br>
* </blockquote>
* depending on which fields are specified in the locale. If the
* language, script, country, and variant fields are all empty,
* this function returns the empty string.
*
* @return The name of the locale appropriate to display.
*/
public final String getDisplayName() {
return getDisplayName(getDefault(Category.DISPLAY));
}
/**
* Returns a name for the locale that is appropriate for display
* to the user. This will be the values returned by
* getDisplayLanguage(), getDisplayScript(),getDisplayCountry(),
* and getDisplayVariant() assembled into a single string.
* The non-empty values are used in order,
* with the second and subsequent names in parentheses. For example:
* <blockquote>
* language (script, country, variant)<br>
* language (country)<br>
* language (variant)<br>
* script (country)<br>
* country<br>
* </blockquote>
* depending on which fields are specified in the locale. If the
* language, script, country, and variant fields are all empty,
* this function returns the empty string.
*
* @param inLocale The locale for which to retrieve the display name.
* @return The name of the locale appropriate to display.
* @throws NullPointerException if <code>inLocale is null
*/
public String getDisplayName(Locale inLocale) {
LocaleResources lr = LocaleProviderAdapter.forJRE().getLocaleResources(inLocale);
String languageName = getDisplayLanguage(inLocale);
String scriptName = getDisplayScript(inLocale);
String countryName = getDisplayCountry(inLocale);
String[] variantNames = getDisplayVariantArray(inLocale);
// Get the localized patterns for formatting a display name.
String displayNamePattern = lr.getLocaleName("DisplayNamePattern");
String listPattern = lr.getLocaleName("ListPattern");
String listCompositionPattern = lr.getLocaleName("ListCompositionPattern");
// The display name consists of a main name, followed by qualifiers.
// Typically, the format is "MainName (Qualifier, Qualifier)" but this
// depends on what pattern is stored in the display locale.
String mainName = null;
String[] qualifierNames = null;
// The main name is the language, or if there is no language, the script,
// then if no script, the country. If there is no language/script/country
// (an anomalous situation) then the display name is simply the variant's
// display name.
if (languageName.length() == 0 && scriptName.length() == 0 && countryName.length() == 0) {
if (variantNames.length == 0) {
return "";
} else {
return formatList(variantNames, listPattern, listCompositionPattern);
}
}
ArrayList<String> names = new ArrayList<>(4);
if (languageName.length() != 0) {
names.add(languageName);
}
if (scriptName.length() != 0) {
names.add(scriptName);
}
if (countryName.length() != 0) {
names.add(countryName);
}
if (variantNames.length != 0) {
names.addAll(Arrays.asList(variantNames));
}
// The first one in the main name
mainName = names.get(0);
// Others are qualifiers
int numNames = names.size();
qualifierNames = (numNames > 1) ?
names.subList(1, numNames).toArray(new String[numNames - 1]) : new String[0];
// Create an array whose first element is the number of remaining
// elements. This serves as a selector into a ChoiceFormat pattern from
// the resource. The second and third elements are the main name and
// the qualifier; if there are no qualifiers, the third element is
// unused by the format pattern.
Object[] displayNames = {
new Integer(qualifierNames.length != 0 ? 2 : 1),
mainName,
// We could also just call formatList() and have it handle the empty
// list case, but this is more efficient, and we want it to be
// efficient since all the language-only locales will not have any
// qualifiers.
qualifierNames.length != 0 ? formatList(qualifierNames, listPattern, listCompositionPattern) : null
};
if (displayNamePattern != null) {
return new MessageFormat(displayNamePattern).format(displayNames);
}
else {
// If we cannot get the message format pattern, then we use a simple
// hard-coded pattern. This should not occur in practice unless the
// installation is missing some core files (FormatData etc.).
StringBuilder result = new StringBuilder();
result.append((String)displayNames[1]);
if (displayNames.length > 2) {
result.append(" (");
result.append((String)displayNames[2]);
result.append(')');
}
return result.toString();
}
}
/**
* Overrides Cloneable.
*/
@Override
public Object clone()
{
try {
Locale that = (Locale)super.clone();
return that;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* Override hashCode.
* Since Locales are often used in hashtables, caches the value
* for speed.
*/
@Override
public int hashCode() {
int hc = hashCodeValue;
if (hc == 0) {
hc = baseLocale.hashCode();
if (localeExtensions != null) {
hc ^= localeExtensions.hashCode();
}
hashCodeValue = hc;
}
return hc;
}
// Overrides
/**
* Returns true if this Locale is equal to another object. A Locale is
* deemed equal to another Locale with identical language, script, country,
* variant and extensions, and unequal to all other objects.
*
* @return true if this Locale is equal to the specified object.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) // quick check
return true;
if (!(obj instanceof Locale))
return false;
BaseLocale otherBase = ((Locale)obj).baseLocale;
if (!baseLocale.equals(otherBase)) {
return false;
}
if (localeExtensions == null) {
return ((Locale)obj).localeExtensions == null;
}
return localeExtensions.equals(((Locale)obj).localeExtensions);
}
// ================= privates =====================================
private transient BaseLocale baseLocale;
private transient LocaleExtensions localeExtensions;
/**
* Calculated hashcode
*/
private transient volatile int hashCodeValue = 0;
private volatile static Locale defaultLocale = initDefault();
private volatile static Locale defaultDisplayLocale = null;
private volatile static Locale defaultFormatLocale = null;
private transient volatile String languageTag;
/**
* Return an array of the display names of the variant.
* @param bundle the ResourceBundle to use to get the display names
* @return an array of display names, possible of zero length.
*/
private String[] getDisplayVariantArray(Locale inLocale) {
// Split the variant name into tokens separated by '_'.
StringTokenizer tokenizer = new StringTokenizer(baseLocale.getVariant(), "_");
String[] names = new String[tokenizer.countTokens()];
// For each variant token, lookup the display name. If
// not found, use the variant name itself.
for (int i=0; i<names.length; ++i) {
names[i] = getDisplayString(tokenizer.nextToken(),
inLocale, DISPLAY_VARIANT);
}
return names;
}
/**
* Format a list using given pattern strings.
* If either of the patterns is null, then a the list is
* formatted by concatenation with the delimiter ','.
* @param stringList the list of strings to be formatted.
* @param listPattern should create a MessageFormat taking 0-3 arguments
* and formatting them into a list.
* @param listCompositionPattern should take 2 arguments
* and is used by composeList.
* @return a string representing the list.
*/
private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) {
// If we have no list patterns, compose the list in a simple,
// non-localized way.
if (listPattern == null || listCompositionPattern == null) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < stringList.length; ++i) {
if (i > 0) {
result.append(',');
}
result.append(stringList[i]);
}
return result.toString();
}
// Compose the list down to three elements if necessary
if (stringList.length > 3) {
MessageFormat format = new MessageFormat(listCompositionPattern);
stringList = composeList(format, stringList);
}
// Rebuild the argument list with the list length as the first element
Object[] args = new Object[stringList.length + 1];
System.arraycopy(stringList, 0, args, 1, stringList.length);
args[0] = new Integer(stringList.length);
// Format it using the pattern in the resource
MessageFormat format = new MessageFormat(listPattern);
return format.format(args);
}
/**
* Given a list of strings, return a list shortened to three elements.
* Shorten it by applying the given format to the first two elements
* recursively.
* @param format a format which takes two arguments
* @param list a list of strings
* @return if the list is three elements or shorter, the same list;
* otherwise, a new list of three elements.
*/
private static String[] composeList(MessageFormat format, String[] list) {
if (list.length <= 3) return list;
// Use the given format to compose the first two elements into one
String[] listItems = { list[0], list[1] };
String newItem = format.format(listItems);
// Form a new list one element shorter
String[] newList = new String[list.length-1];
System.arraycopy(list, 2, newList, 1, newList.length-1);
newList[0] = newItem;
// Recurse
return composeList(format, newList);
}
// Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to
// avoid its class loading.
private static boolean isUnicodeExtensionKey(String s) {
// 2alphanum
return (s.length() == 2) && LocaleUtils.isAlphaNumericString(s);
}
/**
* @serialField language String
* language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage())
* @serialField country String
* country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry())
* @serialField variant String
* variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant())
* @serialField hashcode int
* deprecated, for forward compatibility only
* @serialField script String
* script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript())
* @serialField extensions String
* canonical representation of extensions, that is,
* BCP47 extensions in alphabetical order followed by
* BCP47 private use subtags, all in lower case letters
* separated by HYPHEN-MINUS characters.
* (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys(),
* <a href="java/util/Locale.html#getExtension(char)">getExtension(char))
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("language", String.class),
new ObjectStreamField("country", String.class),
new ObjectStreamField("variant", String.class),
new ObjectStreamField("hashcode", int.class),
new ObjectStreamField("script", String.class),
new ObjectStreamField("extensions", String.class),
};
/**
* Serializes this <code>Locale to the specified ObjectOutputStream
.
* @param out the <code>ObjectOutputStream to write
* @throws IOException
* @since 1.7
*/
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectOutputStream.PutField fields = out.putFields();
fields.put("language", baseLocale.getLanguage());
fields.put("script", baseLocale.getScript());
fields.put("country", baseLocale.getRegion());
fields.put("variant", baseLocale.getVariant());
fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID());
fields.put("hashcode", -1); // place holder just for backward support
out.writeFields();
}
/**
* Deserializes this <code>Locale.
* @param in the <code>ObjectInputStream to read
* @throws IOException
* @throws ClassNotFoundException
* @throws IllformedLocaleException
* @since 1.7
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = in.readFields();
String language = (String)fields.get("language", "");
String script = (String)fields.get("script", "");
String country = (String)fields.get("country", "");
String variant = (String)fields.get("variant", "");
String extStr = (String)fields.get("extensions", "");
baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
if (extStr.length() > 0) {
try {
InternalLocaleBuilder bldr = new InternalLocaleBuilder();
bldr.setExtensions(extStr);
localeExtensions = bldr.getLocaleExtensions();
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage());
}
} else {
localeExtensions = null;
}
}
/**
* Returns a cached <code>Locale instance equivalent to
* the deserialized <code>Locale. When serialized
* language, country and variant fields read from the object data stream
* are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
* fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION
* "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
* type is "thai"). See <a href="Locale.html#special_cases_constructor">Special Cases
* for more information.
*
* @return an instance of <code>Locale equivalent to
* the deserialized <code>Locale.
* @throws java.io.ObjectStreamException
*/
private Object readResolve() throws java.io.ObjectStreamException {
return getInstance(baseLocale.getLanguage(), baseLocale.getScript(),
baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
}
private static volatile String[] isoLanguages = null;
private static volatile String[] isoCountries = null;
private static String convertOldISOCodes(String language) {
// we accept both the old and the new ISO codes for the languages whose ISO
// codes have changed, but we always store the OLD code, for backward compatibility
language = LocaleUtils.toLowerString(language).intern();
if (language == "he") {
return "iw";
} else if (language == "yi") {
return "ji";
} else if (language == "id") {
return "in";
} else {
return language;
}
}
private static LocaleExtensions getCompatibilityExtensions(String language,
String script,
String country,
String variant) {
LocaleExtensions extensions = null;
// Special cases for backward compatibility support
if (LocaleUtils.caseIgnoreMatch(language, "ja")
&& script.length() == 0
&& LocaleUtils.caseIgnoreMatch(country, "jp")
&& "JP".equals(variant)) {
// ja_JP_JP -> u-ca-japanese (calendar = japanese)
extensions = LocaleExtensions.CALENDAR_JAPANESE;
} else if (LocaleUtils.caseIgnoreMatch(language, "th")
&& script.length() == 0
&& LocaleUtils.caseIgnoreMatch(country, "th")
&& "TH".equals(variant)) {
// th_TH_TH -> u-nu-thai (numbersystem = thai)
extensions = LocaleExtensions.NUMBER_THAI;
}
return extensions;
}
/**
* Obtains a localized locale names from a LocaleNameProvider
* implementation.
*/
private static class LocaleNameGetter
implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> {
private static final LocaleNameGetter INSTANCE = new LocaleNameGetter();
@Override
public String getObject(LocaleNameProvider localeNameProvider,
Locale locale,
String key,
Object... params) {
assert params.length == 2;
int type = (Integer)params[0];
String code = (String)params[1];
switch(type) {
case DISPLAY_LANGUAGE:
return localeNameProvider.getDisplayLanguage(code, locale);
case DISPLAY_COUNTRY:
return localeNameProvider.getDisplayCountry(code, locale);
case DISPLAY_VARIANT:
return localeNameProvider.getDisplayVariant(code, locale);
case DISPLAY_SCRIPT:
return localeNameProvider.getDisplayScript(code, locale);
default:
assert false; // shouldn't happen
}
return null;
}
}
/**
* Enum for locale categories. These locale categories are used to get/set
* the default locale for the specific functionality represented by the
* category.
*
* @see #getDefault(Locale.Category)
* @see #setDefault(Locale.Category, Locale)
* @since 1.7
*/
public enum Category {
/**
* Category used to represent the default locale for
* displaying user interfaces.
*/
DISPLAY("user.language.display",
"user.script.display",
"user.country.display",
"user.variant.display"),
/**
* Category used to represent the default locale for
* formatting dates, numbers, and/or currencies.
*/
FORMAT("user.language.format",
"user.script.format",
"user.country.format",
"user.variant.format");
Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
this.languageKey = languageKey;
this.scriptKey = scriptKey;
this.countryKey = countryKey;
this.variantKey = variantKey;
}
final String languageKey;
final String scriptKey;
final String countryKey;
final String variantKey;
}
/**
* <code>Builder is used to build instances of Locale
* from values configured by the setters. Unlike the <code>Locale
* constructors, the <code>Builder checks if a value configured by a
* setter satisfies the syntax requirements defined by the <code>Locale
* class. A <code>Locale object created by a Builder
is
* well-formed and can be transformed to a well-formed IETF BCP 47 language tag
* without losing information.
*
* <p>Note: The Locale
class does not provide any
* syntactic restrictions on variant, while BCP 47 requires each variant
* subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
* alphanumerics. The method <code>setVariant throws
* <code>IllformedLocaleException for a variant that does not satisfy
* this restriction. If it is necessary to support such a variant, use a
* Locale constructor. However, keep in mind that a <code>Locale
* object created this way might lose the variant information when
* transformed to a BCP 47 language tag.
*
* <p>The following example shows how to create a Locale
object
* with the <code>Builder.
* <blockquote>
* <pre>
* Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
* </pre>
* </blockquote>
*
* <p>Builders can be reused; clear()
resets all
* fields to their default values.
*
* @see Locale#forLanguageTag
* @since 1.7
*/
public static final class Builder {
private final InternalLocaleBuilder localeBuilder;
/**
* Constructs an empty Builder. The default value of all
* fields, extensions, and private use information is the
* empty string.
*/
public Builder() {
localeBuilder = new InternalLocaleBuilder();
}
/**
* Resets the <code>Builder to match the provided
* <code>locale. Existing state is discarded.
*
* <p>All fields of the locale must be well-formed, see {@link Locale}.
*
* <p>Locales with any ill-formed fields cause
* <code>IllformedLocaleException to be thrown, except for the
* following three cases which are accepted for compatibility
* reasons:<ul>
* <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
* <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
* <li>Locale("no", "NO", "NY") is treated as "nn-NO"
*
* @param locale the locale
* @return This builder.
* @throws IllformedLocaleException if <code>locale has
* any ill-formed fields.
* @throws NullPointerException if <code>locale is null.
*/
public Builder setLocale(Locale locale) {
try {
localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Resets the Builder to match the provided IETF BCP 47
* language tag. Discards the existing state. Null and the
* empty string cause the builder to be reset, like {@link
* #clear}. Grandfathered tags (see {@link
* Locale#forLanguageTag}) are converted to their canonical
* form before being processed. Otherwise, the language tag
* must be well-formed (see {@link Locale}) or an exception is
* thrown (unlike <code>Locale.forLanguageTag, which
* just discards ill-formed and following portions of the
* tag).
*
* @param languageTag the language tag
* @return This builder.
* @throws IllformedLocaleException if <code>languageTag is ill-formed
* @see Locale#forLanguageTag(String)
*/
public Builder setLanguageTag(String languageTag) {
ParseStatus sts = new ParseStatus();
LanguageTag tag = LanguageTag.parse(languageTag, sts);
if (sts.isError()) {
throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
}
localeBuilder.setLanguageTag(tag);
return this;
}
/**
* Sets the language. If <code>language is the empty string or
* null, the language in this <code>Builder is removed. Otherwise,
* the language must be <a href="./Locale.html#def_language">well-formed
* or an exception is thrown.
*
* <p>The typical language value is a two or three-letter language
* code as defined in ISO639.
*
* @param language the language
* @return This builder.
* @throws IllformedLocaleException if <code>language is ill-formed
*/
public Builder setLanguage(String language) {
try {
localeBuilder.setLanguage(language);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Sets the script. If <code>script is null or the empty string,
* the script in this <code>Builder is removed.
* Otherwise, the script must be <a href="./Locale.html#def_script">well-formed or an
* exception is thrown.
*
* <p>The typical script value is a four-letter script code as defined by ISO 15924.
*
* @param script the script
* @return This builder.
* @throws IllformedLocaleException if <code>script is ill-formed
*/
public Builder setScript(String script) {
try {
localeBuilder.setScript(script);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Sets the region. If region is null or the empty string, the region
* in this <code>Builder is removed. Otherwise,
* the region must be <a href="./Locale.html#def_region">well-formed or an
* exception is thrown.
*
* <p>The typical region value is a two-letter ISO 3166 code or a
* three-digit UN M.49 area code.
*
* <p>The country value in the Locale
created by the
* <code>Builder is always normalized to upper case.
*
* @param region the region
* @return This builder.
* @throws IllformedLocaleException if <code>region is ill-formed
*/
public Builder setRegion(String region) {
try {
localeBuilder.setRegion(region);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Sets the variant. If variant is null or the empty string, the
* variant in this <code>Builder is removed. Otherwise, it
* must consist of one or more <a href="./Locale.html#def_variant">well-formed
* subtags, or an exception is thrown.
*
* <p>Note: This method checks if variant
* satisfies the IETF BCP 47 variant subtag's syntax requirements,
* and normalizes the value to lowercase letters. However,
* the <code>Locale class does not impose any syntactic
* restriction on variant, and the variant value in
* <code>Locale is case sensitive. To set such a variant,
* use a Locale constructor.
*
* @param variant the variant
* @return This builder.
* @throws IllformedLocaleException if <code>variant is ill-formed
*/
public Builder setVariant(String variant) {
try {
localeBuilder.setVariant(variant);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Sets the extension for the given key. If the value is null or the
* empty string, the extension is removed. Otherwise, the extension
* must be <a href="./Locale.html#def_extensions">well-formed or an exception
* is thrown.
*
* <p>Note: The key {@link Locale#UNICODE_LOCALE_EXTENSION
* UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
* Setting a value for this key replaces any existing Unicode locale key/type
* pairs with those defined in the extension.
*
* <p>Note: The key {@link Locale#PRIVATE_USE_EXTENSION
* PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
* well-formed, the value for this key needs only to have subtags of one to
* eight alphanumeric characters, not two to eight as in the general case.
*
* @param key the extension key
* @param value the extension value
* @return This builder.
* @throws IllformedLocaleException if <code>key is illegal
* or <code>value is ill-formed
* @see #setUnicodeLocaleKeyword(String, String)
*/
public Builder setExtension(char key, String value) {
try {
localeBuilder.setExtension(key, value);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Sets the Unicode locale keyword type for the given key. If the type
* is null, the Unicode keyword is removed. Otherwise, the key must be
* non-null and both key and type must be <a
* href="./Locale.html#def_locale_extension">well-formed</a> or an exception
* is thrown.
*
* <p>Keys and types are converted to lower case.
*
* <p>Note:Setting the 'u' extension via {@link #setExtension}
* replaces all Unicode locale keywords with those defined in the
* extension.
*
* @param key the Unicode locale key
* @param type the Unicode locale type
* @return This builder.
* @throws IllformedLocaleException if <code>key or type
* is ill-formed
* @throws NullPointerException if <code>key is null
* @see #setExtension(char, String)
*/
public Builder setUnicodeLocaleKeyword(String key, String type) {
try {
localeBuilder.setUnicodeLocaleKeyword(key, type);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Adds a unicode locale attribute, if not already present, otherwise
* has no effect. The attribute must not be null and must be <a
* href="./Locale.html#def_locale_extension">well-formed</a> or an exception
* is thrown.
*
* @param attribute the attribute
* @return This builder.
* @throws NullPointerException if <code>attribute is null
* @throws IllformedLocaleException if <code>attribute is ill-formed
* @see #setExtension(char, String)
*/
public Builder addUnicodeLocaleAttribute(String attribute) {
try {
localeBuilder.addUnicodeLocaleAttribute(attribute);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Removes a unicode locale attribute, if present, otherwise has no
* effect. The attribute must not be null and must be <a
* href="./Locale.html#def_locale_extension">well-formed</a> or an exception
* is thrown.
*
* <p>Attribute comparision for removal is case-insensitive.
*
* @param attribute the attribute
* @return This builder.
* @throws NullPointerException if <code>attribute is null
* @throws IllformedLocaleException if <code>attribute is ill-formed
* @see #setExtension(char, String)
*/
public Builder removeUnicodeLocaleAttribute(String attribute) {
try {
localeBuilder.removeUnicodeLocaleAttribute(attribute);
} catch (LocaleSyntaxException e) {
throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
}
return this;
}
/**
* Resets the builder to its initial, empty state.
*
* @return This builder.
*/
public Builder clear() {
localeBuilder.clear();
return this;
}
/**
* Resets the extensions to their initial, empty state.
* Language, script, region and variant are unchanged.
*
* @return This builder.
* @see #setExtension(char, String)
*/
public Builder clearExtensions() {
localeBuilder.clearExtensions();
return this;
}
/**
* Returns an instance of <code>Locale created from the fields set
* on this builder.
*
* <p>This applies the conversions listed in {@link Locale#forLanguageTag}
* when constructing a Locale. (Grandfathered tags are handled in
* {@link #setLanguageTag}.)
*
* @return A Locale.
*/
public Locale build() {
BaseLocale baseloc = localeBuilder.getBaseLocale();
LocaleExtensions extensions = localeBuilder.getLocaleExtensions();
if (extensions == null && baseloc.getVariant().length() > 0) {
extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(),
baseloc.getRegion(), baseloc.getVariant());
}
return Locale.getInstance(baseloc, extensions);
}
}
/**
* This enum provides constants to select a filtering mode for locale
* matching. Refer to <a href="http://tools.ietf.org/html/rfc4647">RFC 4647
* Matching of Language Tags</a> for details.
*
* <p>As an example, think of two Language Priority Lists each of which
* includes only one language range and a set of following language tags:
*
* <pre>
* de (German)
* de-DE (German, Germany)
* de-Deva (German, in Devanagari script)
* de-Deva-DE (German, in Devanagari script, Germany)
* de-DE-1996 (German, Germany, orthography of 1996)
* de-Latn-DE (German, in Latin script, Germany)
* de-Latn-DE-1996 (German, in Latin script, Germany, orthography of 1996)
* </pre>
*
* The filtering method will behave as follows:
*
* <table cellpadding=2 summary="Filtering method behavior">
* <tr>
* <th>Filtering Mode
* <th>Language Priority List: {@code "de-DE"}
* <th>Language Priority List: {@code "de-*-DE"}
* </tr>
* <tr>
* <td valign=top>
* {@link FilteringMode#AUTOSELECT_FILTERING AUTOSELECT_FILTERING}
* </td>
* <td valign=top>
* Performs <em>basic filtering and returns {@code "de-DE"} and
* {@code "de-DE-1996"}.
* </td>
* <td valign=top>
* Performs <em>extended filtering and returns {@code "de-DE"},
* {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and
* {@code "de-Latn-DE-1996"}.
* </td>
* </tr>
* <tr>
* <td valign=top>
* {@link FilteringMode#EXTENDED_FILTERING EXTENDED_FILTERING}
* </td>
* <td valign=top>
* Performs <em>extended filtering and returns {@code "de-DE"},
* {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and
* {@code "de-Latn-DE-1996"}.
* </td>
* <td valign=top>Same as above.
* </tr>
* <tr>
* <td valign=top>
* {@link FilteringMode#IGNORE_EXTENDED_RANGES IGNORE_EXTENDED_RANGES}
* </td>
* <td valign=top>
* Performs <em>basic filtering and returns {@code "de-DE"} and
* {@code "de-DE-1996"}.
* </td>
* <td valign=top>
* Performs <em>basic filtering and returns {@code null} because
* nothing matches.
* </td>
* </tr>
* <tr>
* <td valign=top>
* {@link FilteringMode#MAP_EXTENDED_RANGES MAP_EXTENDED_RANGES}
* </td>
* <td valign=top>Same as above.
* <td valign=top>
* Performs <em>basic filtering and returns {@code "de-DE"} and
* {@code "de-DE-1996"} because {@code "de-*-DE"} is mapped to
* {@code "de-DE"}.
* </td>
* </tr>
* <tr>
* <td valign=top>
* {@link FilteringMode#REJECT_EXTENDED_RANGES REJECT_EXTENDED_RANGES}
* </td>
* <td valign=top>Same as above.
* <td valign=top>
* Throws {@link IllegalArgumentException} because {@code "de-*-DE"} is
* not a valid basic language range.
* </td>
* </tr>
* </table>
*
* @see #filter(List, Collection, FilteringMode)
* @see #filterTags(List, Collection, FilteringMode)
*
* @since 1.8
*/
public static enum FilteringMode {
/**
* Specifies automatic filtering mode based on the given Language
* Priority List consisting of language ranges. If all of the ranges
* are basic, basic filtering is selected. Otherwise, extended
* filtering is selected.
*/
AUTOSELECT_FILTERING,
/**
* Specifies extended filtering.
*/
EXTENDED_FILTERING,
/**
* Specifies basic filtering: Note that any extended language ranges
* included in the given Language Priority List are ignored.
*/
IGNORE_EXTENDED_RANGES,
/**
* Specifies basic filtering: If any extended language ranges are
* included in the given Language Priority List, they are mapped to the
* basic language range. Specifically, a language range starting with a
* subtag {@code "*"} is treated as a language range {@code "*"}. For
* example, {@code "*-US"} is treated as {@code "*"}. If {@code "*"} is
* not the first subtag, {@code "*"} and extra {@code "-"} are removed.
* For example, {@code "ja-*-JP"} is mapped to {@code "ja-JP"}.
*/
MAP_EXTENDED_RANGES,
/**
* Specifies basic filtering: If any extended language ranges are
* included in the given Language Priority List, the list is rejected
* and the filtering method throws {@link IllegalArgumentException}.
*/
REJECT_EXTENDED_RANGES
};
/**
* This class expresses a <em>Language Range defined in
* <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 Matching of
* Language Tags</a>. A language range is an identifier which is used to
* select language tag(s) meeting specific requirements by using the
* mechanisms described in <a href="Locale.html#LocaleMatching">Locale
* Matching</a>. A list which represents a user's preferences and consists
* of language ranges is called a <em>Language Priority List.
*
* <p>There are two types of language ranges: basic and extended. In RFC
* 4647, the syntax of language ranges is expressed in
* <a href="http://tools.ietf.org/html/rfc4234">ABNF as follows:
* <blockquote>
* <pre>
* basic-language-range = (1*8ALPHA *("-" 1*8alphanum)) / "*"
* extended-language-range = (1*8ALPHA / "*")
* *("-" (1*8alphanum / "*"))
* alphanum = ALPHA / DIGIT
* </pre>
* </blockquote>
* For example, {@code "en"} (English), {@code "ja-JP"} (Japanese, Japan),
* {@code "*"} (special language range which matches any language tag) are
* basic language ranges, whereas {@code "*-CH"} (any languages,
* Switzerland), {@code "es-*"} (Spanish, any regions), and
* {@code "zh-Hant-*"} (Traditional Chinese, any regions) are extended
* language ranges.
*
* @see #filter
* @see #filterTags
* @see #lookup
* @see #lookupTag
*
* @since 1.8
*/
public static final class LanguageRange {
/**
* A constant holding the maximum value of weight, 1.0, which indicates
* that the language range is a good fit for the user.
*/
public static final double MAX_WEIGHT = 1.0;
/**
* A constant holding the minimum value of weight, 0.0, which indicates
* that the language range is not a good fit for the user.
*/
public static final double MIN_WEIGHT = 0.0;
private final String range;
private final double weight;
private volatile int hash = 0;
/**
* Constructs a {@code LanguageRange} using the given {@code range}.
* Note that no validation is done against the IANA Language Subtag
* Registry at time of construction.
*
* <p>This is equivalent to {@code LanguageRange(range, MAX_WEIGHT)}.
*
* @param range a language range
* @throws NullPointerException if the given {@code range} is
* {@code null}
*/
public LanguageRange(String range) {
this(range, MAX_WEIGHT);
}
/**
* Constructs a {@code LanguageRange} using the given {@code range} and
* {@code weight}. Note that no validation is done against the IANA
* Language Subtag Registry at time of construction.
*
* @param range a language range
* @param weight a weight value between {@code MIN_WEIGHT} and
* {@code MAX_WEIGHT}
* @throws NullPointerException if the given {@code range} is
* {@code null}
* @throws IllegalArgumentException if the given {@code weight} is less
* than {@code MIN_WEIGHT} or greater than {@code MAX_WEIGHT}
*/
public LanguageRange(String range, double weight) {
if (range == null) {
throw new NullPointerException();
}
if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) {
throw new IllegalArgumentException("weight=" + weight);
}
range = range.toLowerCase();
// Do syntax check.
boolean isIllFormed = false;
String[] subtags = range.split("-");
if (isSubtagIllFormed(subtags[0], true)
|| range.endsWith("-")) {
isIllFormed = true;
} else {
for (int i = 1; i < subtags.length; i++) {
if (isSubtagIllFormed(subtags[i], false)) {
isIllFormed = true;
}
break;
}
}
if (isIllFormed) {
throw new IllegalArgumentException("range=" + range);
}
this.range = range;
this.weight = weight;
}
private static boolean isSubtagIllFormed(String subtag,
boolean isFirstSubtag) {
if (subtag.equals("") || subtag.length() > 8) {
return true;
} else if (subtag.equals("*")) {
return false;
}
char[] charArray = subtag.toCharArray();
if (isFirstSubtag) { // ALPHA
for (char c : charArray) {
if (c < 'a' || c > 'z') {
return true;
}
}
} else { // ALPHA / DIGIT
for (char c : charArray) {
if (c < '0' || (c > '9' && c < 'a') || c > 'z') {
return true;
}
}
}
return false;
}
/**
* Returns the language range of this {@code LanguageRange}.
*
* @return the language range.
*/
public String getRange() {
return range;
}
/**
* Returns the weight of this {@code LanguageRange}.
*
* @return the weight value.
*/
public double getWeight() {
return weight;
}
/**
* Parses the given {@code ranges} to generate a Language Priority List.
*
* <p>This method performs a syntactic check for each language range in
* the given {@code ranges} but doesn't do validation using the IANA
* Language Subtag Registry.
*
* <p>The {@code ranges} to be given can take one of the following
* forms:
*
* <pre>
* "Accept-Language: ja,en;q=0.4" (weighted list with Accept-Language prefix)
* "ja,en;q=0.4" (weighted list)
* "ja,en" (prioritized list)
* </pre>
*
* In a weighted list, each language range is given a weight value.
* The weight value is identical to the "quality value" in
* <a href="http://tools.ietf.org/html/rfc2616">RFC 2616, and it
* expresses how much the user prefers the language. A weight value is
* specified after a corresponding language range followed by
* {@code ";q="}, and the default weight value is {@code MAX_WEIGHT}
* when it is omitted.
*
* <p>Unlike a weighted list, language ranges in a prioritized list
* are sorted in the descending order based on its priority. The first
* language range has the highest priority and meets the user's
* preference most.
*
* <p>In either case, language ranges are sorted in descending order in
* the Language Priority List based on priority or weight. If a
* language range appears in the given {@code ranges} more than once,
* only the first one is included on the Language Priority List.
*
* <p>The returned list consists of language ranges from the given
* {@code ranges} and their equivalents found in the IANA Language
* Subtag Registry. For example, if the given {@code ranges} is
* {@code "Accept-Language: iw,en-us;q=0.7,en;q=0.3"}, the elements in
* the list to be returned are:
*
* <pre>
* <b>RangeWeight
* "iw" (older tag for Hebrew) 1.0
* "he" (new preferred code for Hebrew) 1.0
* "en-us" (English, United States) 0.7
* "en" (English) 0.3
* </pre>
*
* Two language ranges, {@code "iw"} and {@code "he"}, have the same
* highest priority in the list. By adding {@code "he"} to the user's
* Language Priority List, locale-matching method can find Hebrew as a
* matching locale (or language tag) even if the application or system
* offers only {@code "he"} as a supported locale (or language tag).
*
* @param ranges a list of comma-separated language ranges or a list of
* language ranges in the form of the "Accept-Language" header
* defined in <a href="http://tools.ietf.org/html/rfc2616">RFC
* 2616</a>
* @return a Language Priority List consisting of language ranges
* included in the given {@code ranges} and their equivalent
* language ranges if available. The list is modifiable.
* @throws NullPointerException if {@code ranges} is null
* @throws IllegalArgumentException if a language range or a weight
* found in the given {@code ranges} is ill-formed
*/
public static List<LanguageRange> parse(String ranges) {
return LocaleMatcher.parse(ranges);
}
/**
* Parses the given {@code ranges} to generate a Language Priority
* List, and then customizes the list using the given {@code map}.
* This method is equivalent to
* {@code mapEquivalents(parse(ranges), map)}.
*
* @param ranges a list of comma-separated language ranges or a list
* of language ranges in the form of the "Accept-Language" header
* defined in <a href="http://tools.ietf.org/html/rfc2616">RFC
* 2616</a>
* @param map a map containing information to customize language ranges
* @return a Language Priority List with customization. The list is
* @throws NullPointerException if {@code ranges} is null
* @throws IllegalArgumentException if a language range or a weight
* found in the given {@code ranges} is ill-formed
* @see #parse(String)
* @see #mapEquivalents
*/
public static List<LanguageRange> parse(String ranges,
Map<String, ListHere is a short list of links related to this Java Locale.java source code file:
Java example source code file (Locale.java)
The Locale.java Java example source code/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; import java.security.AccessController; import java.text.MessageFormat; import java.util.spi.LocaleNameProvider; import sun.security.action.GetPropertyAction; import sun.util.locale.BaseLocale; import sun.util.locale.InternalLocaleBuilder; import sun.util.locale.LanguageTag; import sun.util.locale.LocaleExtensions; import sun.util.locale.LocaleMatcher; import sun.util.locale.LocaleObjectCache; import sun.util.locale.LocaleSyntaxException; import sun.util.locale.LocaleUtils; import sun.util.locale.ParseStatus; import sun.util.locale.provider.LocaleProviderAdapter; import sun.util.locale.provider.LocaleResources; import sun.util.locale.provider.LocaleServiceProviderPool; import sun.util.locale.provider.ResourceBundleBasedAdapter; /** * A <code>Locale object represents a specific geographical, political, * or cultural region. An operation that requires a <code>Locale to perform * its task is called <em>locale-sensitive and uses the
Locale has a language, country, or
* variant that does not satisfy the IETF BCP 47 language tag
* syntax requirements, this method handles these fields as
* described below:
*
* <p>Language: If language is empty, or not (for example "a" or
* "e2"), it will be emitted as "und" (Undetermined).
*
* <p>Country: If country is not (for example "12" or "USA"),
* it will be omitted.
*
* <p>Variant: If variant is , each sub-segment
* (delimited by '-' or '_') is emitted as a subtag. Otherwise:
* <ul>
*
* <li>if all sub-segments match [0-9a-zA-Z]{1,8}
* (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
* ill-formed sub-segment and all following will be appended to
* the private use subtag. The first appended subtag will be
* "lvariant", followed by the sub-segments in order, separated by
* hyphen. For example, "x-lvariant-WIN",
* "Oracle-x-lvariant-JDK-Standard-Edition".
*
* <li>if any sub-segment does not match
* <code>[0-9a-zA-Z]{1,8}, the variant will be truncated
* and the problematic sub-segment and all following sub-segments
* will be omitted. If the remainder is non-empty, it will be
* emitted as a private use subtag as above (even if the remainder
* turns out to be well-formed). For example,
* "Solaris_isjustthecoolestthing" is emitted as
* "x-lvariant-Solaris", not as "solaris".</li>
*
* <p>Special Conversions: Java supports some old locale
* representations, including deprecated ISO language codes,
* for compatibility. This method performs the following
* conversions:
* <ul>
*
* <li>Deprecated ISO language codes "iw", "ji", and "in" are
* converted to "he", "yi", and "id", respectively.
*
* <li>A locale with language "no", country "NO", and variant
* "NY", representing Norwegian Nynorsk (Norway), is converted
* to a language tag "nn-NO".</li>
*
* <p>Note: Although the language tag created by this
* method is well-formed (satisfies the syntax requirements
* defined by the IETF BCP 47 specification), it is not
* necessarily a valid BCP 47 language tag. For example,
* <pre>
* new Locale("xx", "YY").toLanguageTag();</pre>
*
* will return "xx-YY", but the language subtag "xx" and the
* region subtag "YY" are invalid because they are not registered
* in the IANA Language Subtag Registry.
*
* @return a BCP47 language tag representing the locale
* @see #forLanguageTag(String)
* @since 1.7
*/
public String toLanguageTag() {
if (languageTag != null) {
return languageTag;
}
LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions);
StringBuilder buf = new StringBuilder();
String subtag = tag.getLanguage();
if (subtag.length() > 0) {
buf.append(LanguageTag.canonicalizeLanguage(subtag));
}
subtag = tag.getScript();
if (subtag.length() > 0) {
buf.append(LanguageTag.SEP);
buf.append(LanguageTag.canonicalizeScript(subtag));
}
subtag = tag.getRegion();
if (subtag.length() > 0) {
buf.append(LanguageTag.SEP);
buf.append(LanguageTag.canonicalizeRegion(subtag));
}
List<String>subtags = tag.getVariants();
for (String s : subtags) {
buf.append(LanguageTag.SEP);
// preserve casing
buf.append(s);
}
subtags = tag.getExtensions();
for (String s : subtags) {
buf.append(LanguageTag.SEP);
buf.append(LanguageTag.canonicalizeExtension(s));
}
subtag = tag.getPrivateuse();
if (subtag.length() > 0) {
if (buf.length() > 0) {
buf.append(LanguageTag.SEP);
}
buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
// preserve casing
buf.append(subtag);
}
String langTag = buf.toString();
synchronized (this) {
if (languageTag == null) {
languageTag = langTag;
}
}
return languageTag;
}
/**
* Returns a locale for the specified IETF BCP 47 language tag string.
*
* <p>If the specified language tag contains any ill-formed subtags,
* the first such subtag and all following subtags are ignored. Compare
* to {@link Locale.Builder#setLanguageTag} which throws an exception
* in this case.
*
* <p>The following conversions are performed:
| grandfathered tag | modern replacement | ||
---|---|---|---|---|
art-lojban | jbo | |||
i-ami | ami | |||
i-bnn | bnn | |||
i-hak | hak | |||
i-klingon | tlh | |||
i-lux | lb | |||
i-navajo | nv | |||
i-pwn | pwn | |||
i-tao | tao | |||
i-tay | tay | |||
i-tsu | tsu | |||
no-bok | nb | |||
no-nyn | nn | |||
sgn-BE-FR | sfb | |||
sgn-BE-NL | vgt | |||
sgn-CH-DE | sgg | |||
zh-guoyu | cmn | |||
zh-hakka | hak | |||
zh-min-nan | nan | |||
zh-xiang | hsn | |||
grandfathered tag | converts to | |||
cel-gaulish | xtg-x-cel-gaulish | |||
en-GB-oed | en-GB-x-oed | |||
i-default | en-x-i-default | |||
i-enochian | und-x-i-enochian | |||
i-mingo | see-x-i-mingo | |||
zh-min | nan-x-zh-min |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.