Java Code Examples for java.util.Locale#toLanguageTag()

The following examples show how to use java.util.Locale#toLanguageTag() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Ensure that all current locale ids parse.  Use DateFormat as a proxy
 * for all current locale ids.
 */
public void testCurrentLocales() {
    Locale[] locales = java.text.DateFormat.getAvailableLocales();
    Builder builder = new Builder();

    for (Locale target : locales) {
        String tag = target.toLanguageTag();

        // the tag recreates the original locale,
        // except no_NO_NY
        Locale tagResult = Locale.forLanguageTag(tag);
        if (!target.getVariant().equals("NY")) {
            assertEquals("tagResult", target, tagResult);
        }

        // the builder also recreates the original locale,
        // except ja_JP_JP, th_TH_TH and no_NO_NY
        Locale builderResult = builder.setLocale(target).build();
        if (target.getVariant().length() != 2) {
            assertEquals("builderResult", target, builderResult);
        }
    }
}
 
Example 2
Source File: I18nExtension.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
    String messageKey = (String) args.get("key");

    Locale locale = context.getLocale();
    String requestLang = locale.toLanguageTag();

    List<Object> messageArgs = new ArrayList<>();
    for (int i = 1; i <= 5; i++) {
        if (args.containsKey("arg" + i)) {
            Object object = args.get("arg" + i);
            messageArgs.add(object);
        }
    }

    String messageValue = messages.get(messageKey, requestLang, messageArgs.toArray());

    return new SafeString(messageValue);
}
 
Example 3
Source File: LocaleEnhanceTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Ensure that all current locale ids parse.  Use DateFormat as a proxy
 * for all current locale ids.
 */
public void testCurrentLocales() {
    Locale[] locales = java.text.DateFormat.getAvailableLocales();
    Builder builder = new Builder();

    for (Locale target : locales) {
        String tag = target.toLanguageTag();

        // the tag recreates the original locale,
        // except no_NO_NY
        Locale tagResult = Locale.forLanguageTag(tag);
        if (!target.getVariant().equals("NY")) {
            assertEquals("tagResult", target, tagResult);
        }

        // the builder also recreates the original locale,
        // except ja_JP_JP, th_TH_TH and no_NO_NY
        Locale builderResult = builder.setLocale(target).build();
        if (target.getVariant().length() != 2) {
            assertEquals("builderResult", target, builderResult);
        }
    }
}
 
Example 4
Source File: LocaleEnhanceTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Ensure that all current locale ids parse.  Use DateFormat as a proxy
 * for all current locale ids.
 */
public void testCurrentLocales() {
    Locale[] locales = java.text.DateFormat.getAvailableLocales();
    Builder builder = new Builder();

    for (Locale target : locales) {
        String tag = target.toLanguageTag();

        // the tag recreates the original locale,
        // except no_NO_NY
        Locale tagResult = Locale.forLanguageTag(tag);
        if (!target.getVariant().equals("NY")) {
            assertEquals("tagResult", target, tagResult);
        }

        // the builder also recreates the original locale,
        // except ja_JP_JP, th_TH_TH and no_NO_NY
        Locale builderResult = builder.setLocale(target).build();
        if (target.getVariant().length() != 2) {
            assertEquals("builderResult", target, builderResult);
        }
    }
}
 
Example 5
Source File: SettingsController.java    From TerasologyLauncher with Apache License 2.0 6 votes vote down vote up
private void populateLanguageValues() {
    languageBox.getItems().clear();
    for (Locale locale : Languages.SUPPORTED_LOCALES) {
        String item = locale.toLanguageTag() + " : " + BundleUtils.getLabel(locale, Languages.SETTINGS_LABEL_KEYS.get(locale));
        if (!locale.equals(Languages.getCurrentLocale())) {
            item += " (" + BundleUtils.getLabel(Languages.SETTINGS_LABEL_KEYS.get(locale)) + ")";
        }
        languageBox.getItems().add(item);

        if (Languages.getCurrentLocale().equals(locale)) {
            languageBox.getSelectionModel().select(item);
        }
    }
    Collator coll = Collator.getInstance();
    languageBox.getItems().sort(coll);
}
 
Example 6
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    int errors = 0;
    for (String loctag : args) {
        Locale locale = Locale.forLanguageTag(loctag);
        if (locale.equals(Locale.ROOT)) {
            continue;
        }
        ResourceBundle rb = ResourceBundle.getBundle("jdk.test.resources.MyResources",
                                                     locale);
        String tag = locale.toLanguageTag(); // normalized
        String value = rb.getString("key");
        System.out.println("locale = " + tag + ", value = " + value);
        if (!value.startsWith(tag + ':')) {
            System.out.println("ERROR: " + value + " expected: " + tag);
            errors++;
        }
    }
    if (errors > 0) {
        throw new RuntimeException(errors + " errors");
    }
}
 
Example 7
Source File: Bug8035133.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkLookup(String ranges, String tags,
        String expectedLocale) {

    List<Locale.LanguageRange> priorityList = Locale.LanguageRange
            .parse(ranges);
    List<Locale> localeList = generateLocales(tags);
    Locale loc = Locale.lookup(priorityList, localeList);
    String actualLocale
            = loc.toLanguageTag();

    if (!actualLocale.equals(expectedLocale)) {
        System.err.println("Locale.lookup failed with ranges: " + ranges
                + " Expected: " + expectedLocale
                + " Actual: " + actualLocale);
        err = true;
    }

}
 
Example 8
Source File: LocaleEnhanceTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Ensure that all current locale ids parse.  Use DateFormat as a proxy
 * for all current locale ids.
 */
public void testCurrentLocales() {
    Locale[] locales = java.text.DateFormat.getAvailableLocales();
    Builder builder = new Builder();

    for (Locale target : locales) {
        String tag = target.toLanguageTag();

        // the tag recreates the original locale,
        // except no_NO_NY
        Locale tagResult = Locale.forLanguageTag(tag);
        if (!target.getVariant().equals("NY")) {
            assertEquals("tagResult", target, tagResult);
        }

        // the builder also recreates the original locale,
        // except ja_JP_JP, th_TH_TH and no_NO_NY
        Locale builderResult = builder.setLocale(target).build();
        if (target.getVariant().length() != 2) {
            assertEquals("builderResult", target, builderResult);
        }
    }
}
 
Example 9
Source File: ChatListener.java    From AntiBot with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onChat(final ChatEvent event) {
	final Connection sender = event.getSender();

	if (!event.isCancelled() && sender instanceof ProxiedPlayer) {
		final WhitelistModule whitelistModule = moduleManager.getWhitelistModule();
		final ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender;

		if (!whitelistModule.check(proxiedPlayer)) {
			final RegisterModule registerModule = moduleManager.getRegisterModule();
			final FastChatModule fastChatModule = moduleManager.getFastChatModule();
			final String message = event.getMessage();
			final Locale locale = proxiedPlayer.getLocale();
			final int currentPPS = moduleManager.getCurrentPPS(), currentCPS = moduleManager.getCurrentCPS(),
					currentJPS = moduleManager.getCurrentJPS();

			if (locale == null) {
				if (fastChatModule.meet(currentPPS, currentCPS, currentJPS)) {
					new Punish(plugin, moduleManager, "en", fastChatModule, proxiedPlayer, event);

					moduleManager.getBlacklistModule().setBlacklisted(proxiedPlayer.getAddress().getHostString(),
							true);
				}
			} else {
				final String lang = locale.toLanguageTag();

				if (fastChatModule.meet(currentPPS, currentCPS, currentJPS)
						&& fastChatModule.check(proxiedPlayer)) {
					new Punish(plugin, moduleManager, lang, fastChatModule, proxiedPlayer, event);
				} else if (registerModule.meet(currentPPS, currentCPS, currentJPS)
						&& registerModule.check(proxiedPlayer, message)) {
					new Punish(plugin, moduleManager, lang, registerModule, proxiedPlayer, event);
				} else {
					registerModule.setLastRegisterCommand(proxiedPlayer.getAddress().getHostString(), message);
				}
			}
		}
	}
}
 
Example 10
Source File: LocaleData.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
    String key = baseName + '-' + locale.toLanguageTag();
    List<Locale> candidates = CANDIDATES_MAP.get(key);
    if (candidates == null) {
        LocaleProviderAdapter.Type type = baseName.contains(DOTCLDR) ? CLDR : JRE;
        LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
        candidates = adapter instanceof ResourceBundleBasedAdapter ?
            ((ResourceBundleBasedAdapter)adapter).getCandidateLocales(baseName, locale) :
            defaultControl.getCandidateLocales(baseName, locale);

        // Weed out Locales which are known to have no resource bundles
        int lastDot = baseName.lastIndexOf('.');
        String category = (lastDot >= 0) ? baseName.substring(lastDot + 1) : baseName;
        Set<String> langtags = ((JRELocaleProviderAdapter)adapter).getLanguageTagSet(category);
        if (!langtags.isEmpty()) {
            for (Iterator<Locale> itr = candidates.iterator(); itr.hasNext();) {
                if (!adapter.isSupportedProviderLocale(itr.next(), langtags)) {
                    itr.remove();
                }
            }
        }
        // Force fallback to Locale.ENGLISH for CLDR time zone names support
        if (locale.getLanguage() != "en"
                && type == CLDR && category.equals("TimeZoneNames")) {
            candidates.add(candidates.size() - 1, Locale.ENGLISH);
        }
        CANDIDATES_MAP.putIfAbsent(key, candidates);
    }
    return candidates;
}
 
Example 11
Source File: Response.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Called explicitly by user to set the Content-Language and the default
 * encoding.
 *
 * @param locale The locale to use for this response
 */
public void setLocale(Locale locale) {

    if (locale == null) {
        return;  // throw an exception?
    }

    // Save the locale for use by getLocale()
    this.locale = locale;

    // Set the contentLanguage for header output
    contentLanguage = locale.toLanguageTag();
}
 
Example 12
Source File: OneComponentService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
private String getFallbackLocale(String productName, String version,
		String inputLocale) throws L3APIException {
	List<String> supportedLocaleList = productService
			.getSupportedLocaleList(productName, version);
	List<Locale> supportedLocales = new ArrayList<Locale>();
	for (String supportedLocale : supportedLocaleList) {
		supportedLocale = supportedLocale.replace("_", "-");
		supportedLocales.add(Locale.forLanguageTag(supportedLocale));
	}
	String requestLocale = inputLocale.replace("_", "-");
	Locale fallbackLocale = LocaleUtility.pickupLocaleFromListNoDefault(
			supportedLocales, Locale.forLanguageTag(requestLocale));
	return fallbackLocale.toLanguageTag();
}
 
Example 13
Source File: LocaleTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private String getLocale(DataFetchingEnvironment env) {
  Locale locale = env.getLocale();
  if (locale == null)
    return null;
  return locale.toLanguageTag();
}
 
Example 14
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public void testBug7002320() {
    // forLanguageTag() and Builder.setLanguageTag(String)
    // should add a location extension for following two cases.
    //
    // 1. language/country are "ja"/"JP" and the resolved variant (x-lvariant-*)
    //    is exactly "JP" and no BCP 47 extensions are available, then add
    //    a Unicode locale extension "ca-japanese".
    // 2. language/country are "th"/"TH" and the resolved variant is exactly
    //    "TH" and no BCP 47 extensions are available, then add a Unicode locale
    //    extension "nu-thai".
    //
    String[][] testdata = {
        {"ja-JP-x-lvariant-JP", "ja-JP-u-ca-japanese-x-lvariant-JP"},   // special case 1
        {"ja-JP-x-lvariant-JP-XXX"},
        {"ja-JP-u-ca-japanese-x-lvariant-JP"},
        {"ja-JP-u-ca-gregory-x-lvariant-JP"},
        {"ja-JP-u-cu-jpy-x-lvariant-JP"},
        {"ja-x-lvariant-JP"},
        {"th-TH-x-lvariant-TH", "th-TH-u-nu-thai-x-lvariant-TH"},   // special case 2
        {"th-TH-u-nu-thai-x-lvariant-TH"},
        {"en-US-x-lvariant-JP"},
    };

    Builder bldr = new Builder();

    for (String[] data : testdata) {
        String in = data[0];
        String expected = (data.length == 1) ? data[0] : data[1];

        // forLanguageTag
        Locale loc = Locale.forLanguageTag(in);
        String out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by forLanguageTag with input: " + in, expected, out);

        // setLanguageTag
        bldr.clear();
        bldr.setLanguageTag(in);
        loc = bldr.build();
        out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by Builder.setLanguageTag with input: " + in, expected, out);
    }
}
 
Example 15
Source File: LocaleEnhanceTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void testBug7002320() {
    // forLanguageTag() and Builder.setLanguageTag(String)
    // should add a location extension for following two cases.
    //
    // 1. language/country are "ja"/"JP" and the resolved variant (x-lvariant-*)
    //    is exactly "JP" and no BCP 47 extensions are available, then add
    //    a Unicode locale extension "ca-japanese".
    // 2. language/country are "th"/"TH" and the resolved variant is exactly
    //    "TH" and no BCP 47 extensions are available, then add a Unicode locale
    //    extension "nu-thai".
    //
    String[][] testdata = {
        {"ja-JP-x-lvariant-JP", "ja-JP-u-ca-japanese-x-lvariant-JP"},   // special case 1
        {"ja-JP-x-lvariant-JP-XXX"},
        {"ja-JP-u-ca-japanese-x-lvariant-JP"},
        {"ja-JP-u-ca-gregory-x-lvariant-JP"},
        {"ja-JP-u-cu-jpy-x-lvariant-JP"},
        {"ja-x-lvariant-JP"},
        {"th-TH-x-lvariant-TH", "th-TH-u-nu-thai-x-lvariant-TH"},   // special case 2
        {"th-TH-u-nu-thai-x-lvariant-TH"},
        {"en-US-x-lvariant-JP"},
    };

    Builder bldr = new Builder();

    for (String[] data : testdata) {
        String in = data[0];
        String expected = (data.length == 1) ? data[0] : data[1];

        // forLanguageTag
        Locale loc = Locale.forLanguageTag(in);
        String out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by forLanguageTag with input: " + in, expected, out);

        // setLanguageTag
        bldr.clear();
        bldr.setLanguageTag(in);
        loc = bldr.build();
        out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by Builder.setLanguageTag with input: " + in, expected, out);
    }
}
 
Example 16
Source File: LocaleEnhanceTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void testBug7002320() {
    // forLanguageTag() and Builder.setLanguageTag(String)
    // should add a location extension for following two cases.
    //
    // 1. language/country are "ja"/"JP" and the resolved variant (x-lvariant-*)
    //    is exactly "JP" and no BCP 47 extensions are available, then add
    //    a Unicode locale extension "ca-japanese".
    // 2. language/country are "th"/"TH" and the resolved variant is exactly
    //    "TH" and no BCP 47 extensions are available, then add a Unicode locale
    //    extension "nu-thai".
    //
    String[][] testdata = {
        {"ja-JP-x-lvariant-JP", "ja-JP-u-ca-japanese-x-lvariant-JP"},   // special case 1
        {"ja-JP-x-lvariant-JP-XXX"},
        {"ja-JP-u-ca-japanese-x-lvariant-JP"},
        {"ja-JP-u-ca-gregory-x-lvariant-JP"},
        {"ja-JP-u-cu-jpy-x-lvariant-JP"},
        {"ja-x-lvariant-JP"},
        {"th-TH-x-lvariant-TH", "th-TH-u-nu-thai-x-lvariant-TH"},   // special case 2
        {"th-TH-u-nu-thai-x-lvariant-TH"},
        {"en-US-x-lvariant-JP"},
    };

    Builder bldr = new Builder();

    for (String[] data : testdata) {
        String in = data[0];
        String expected = (data.length == 1) ? data[0] : data[1];

        // forLanguageTag
        Locale loc = Locale.forLanguageTag(in);
        String out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by forLanguageTag with input: " + in, expected, out);

        // setLanguageTag
        bldr.clear();
        bldr.setLanguageTag(in);
        loc = bldr.build();
        out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by Builder.setLanguageTag with input: " + in, expected, out);
    }
}
 
Example 17
Source File: LocaleEnhanceTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public void testBug7002320() {
    // forLanguageTag() and Builder.setLanguageTag(String)
    // should add a location extension for following two cases.
    //
    // 1. language/country are "ja"/"JP" and the resolved variant (x-lvariant-*)
    //    is exactly "JP" and no BCP 47 extensions are available, then add
    //    a Unicode locale extension "ca-japanese".
    // 2. language/country are "th"/"TH" and the resolved variant is exactly
    //    "TH" and no BCP 47 extensions are available, then add a Unicode locale
    //    extension "nu-thai".
    //
    String[][] testdata = {
        {"ja-JP-x-lvariant-JP", "ja-JP-u-ca-japanese-x-lvariant-JP"},   // special case 1
        {"ja-JP-x-lvariant-JP-XXX"},
        {"ja-JP-u-ca-japanese-x-lvariant-JP"},
        {"ja-JP-u-ca-gregory-x-lvariant-JP"},
        {"ja-JP-u-cu-jpy-x-lvariant-JP"},
        {"ja-x-lvariant-JP"},
        {"th-TH-x-lvariant-TH", "th-TH-u-nu-thai-x-lvariant-TH"},   // special case 2
        {"th-TH-u-nu-thai-x-lvariant-TH"},
        {"en-US-x-lvariant-JP"},
    };

    Builder bldr = new Builder();

    for (String[] data : testdata) {
        String in = data[0];
        String expected = (data.length == 1) ? data[0] : data[1];

        // forLanguageTag
        Locale loc = Locale.forLanguageTag(in);
        String out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by forLanguageTag with input: " + in, expected, out);

        // setLanguageTag
        bldr.clear();
        bldr.setLanguageTag(in);
        loc = bldr.build();
        out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by Builder.setLanguageTag with input: " + in, expected, out);
    }
}
 
Example 18
Source File: LocaleEnhanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void testBug7002320() {
    // forLanguageTag() and Builder.setLanguageTag(String)
    // should add a location extension for following two cases.
    //
    // 1. language/country are "ja"/"JP" and the resolved variant (x-lvariant-*)
    //    is exactly "JP" and no BCP 47 extensions are available, then add
    //    a Unicode locale extension "ca-japanese".
    // 2. language/country are "th"/"TH" and the resolved variant is exactly
    //    "TH" and no BCP 47 extensions are available, then add a Unicode locale
    //    extension "nu-thai".
    //
    String[][] testdata = {
        {"ja-JP-x-lvariant-JP", "ja-JP-u-ca-japanese-x-lvariant-JP"},   // special case 1
        {"ja-JP-x-lvariant-JP-XXX"},
        {"ja-JP-u-ca-japanese-x-lvariant-JP"},
        {"ja-JP-u-ca-gregory-x-lvariant-JP"},
        {"ja-JP-u-cu-jpy-x-lvariant-JP"},
        {"ja-x-lvariant-JP"},
        {"th-TH-x-lvariant-TH", "th-TH-u-nu-thai-x-lvariant-TH"},   // special case 2
        {"th-TH-u-nu-thai-x-lvariant-TH"},
        {"en-US-x-lvariant-JP"},
    };

    Builder bldr = new Builder();

    for (String[] data : testdata) {
        String in = data[0];
        String expected = (data.length == 1) ? data[0] : data[1];

        // forLanguageTag
        Locale loc = Locale.forLanguageTag(in);
        String out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by forLanguageTag with input: " + in, expected, out);

        // setLanguageTag
        bldr.clear();
        bldr.setLanguageTag(in);
        loc = bldr.build();
        out = loc.toLanguageTag();
        assertEquals("Language tag roundtrip by Builder.setLanguageTag with input: " + in, expected, out);
    }
}
 
Example 19
Source File: Util.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
@TargetApi(21)
private static String getLocaleLanguageTagV21(Locale locale) {
  return locale.toLanguageTag();
}
 
Example 20
Source File: CookieLocaleResolver.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Render the given locale as a text value for inclusion in a cookie.
 * <p>The default implementation calls {@link Locale#toString()}
 * or JDK 7's {@link Locale#toLanguageTag()}, depending on the
 * {@link #setLanguageTagCompliant "languageTagCompliant"} configuration property.
 * @param locale the locale to stringify
 * @return a String representation for the given locale
 * @since 4.3
 */
@UsesJava7
protected String toLocaleValue(Locale locale) {
	return (isLanguageTagCompliant() ? locale.toLanguageTag() : locale.toString());
}