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

The following examples show how to use java.util.Locale#forLanguageTag() . 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 openjdk-8 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: ExtenderUtils.java    From wisdom with Apache License 2.0 6 votes vote down vote up
public static Locale getLocaleFromResourceName(String name) {
    final int index = name.indexOf('_');
    if (index != -1) {
        String locale = name.substring(index + 1);
        // Remove the extension  (.properties)
        if (locale.lastIndexOf('.') != -1) {
            int lastDot = locale.lastIndexOf('.');
            locale = locale.substring(0, lastDot)
                    // Replace _ (Java syntax) by - to create locale name
                    .replace("_", "-");
        }
        return Locale.forLanguageTag(locale);
    } else {
        return InternationalizationService.DEFAULT_LOCALE;
    }

}
 
Example 3
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void testGetExtension() {
    // forLanguageTag does NOT normalize to hyphen
    Locale locale = Locale.forLanguageTag("und-a-some_ex-tension");
    assertEquals("some_ex-tension", null, locale.getExtension('a'));

    // regular extension
    locale = new Builder().setExtension('a', "some-ex-tension").build();
    assertEquals("builder", "some-ex-tension", locale.getExtension('a'));

    // returns null if extension is not present
    assertEquals("empty b", null, locale.getExtension('b'));

    // throws exception if extension tag is illegal
    new ExpectIAE() { public void call() { Locale.forLanguageTag("").getExtension('\uD800'); }};

    // 'x' is not an extension, it's a private use tag, but it's accessed through this API
    locale = Locale.forLanguageTag("x-y-z-blork");
    assertEquals("x", "y-z-blork", locale.getExtension('x'));
}
 
Example 4
Source File: Date.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Vertex printDate(Vertex source, Vertex date, Vertex format, Vertex timezone, Vertex locale) {
	String text = format.getDataValue();
	Locale localeValue = Locale.US;
	Calendar calendar = Calendar.getInstance();
	calendar.setTime((java.util.Date)date.getData());
	if (timezone != null && !timezone.is(Primitive.NULL)) {
		calendar.setTimeZone(TimeZone.getTimeZone("GMT" + timezone.printString()));
	}
	if (locale != null && !locale.is(Primitive.NULL)) {
		localeValue = Locale.forLanguageTag(locale.printString());
	}
	SimpleDateFormat formater = new SimpleDateFormat(text, localeValue);
	text = formater.format(Utils.parseTimestamp(
			calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE) + " "
			+ calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND)));
	return source.getNetwork().createVertex(text);
}
 
Example 5
Source File: JapanEraNameCompatTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name="JavaTime")
Object[][] dataJavaTime() {
    return new Object[][] {
        // locale, full, short
        { JAPAN, CJName, CJName },
        { KOREAN, KoreanName, KoreanName },
        { CHINA, CJName, CJName },
        { TAIWAN, CJName, CJName },
        { new Locale("ar"), ArabicName, ArabicName },
        { new Locale("th"), ThaiName, ThaiName },
        { new Locale("hi", "IN"), HindiName, HindiName },
        { new Locale("ru"), RussianName, RussianName },
        { new Locale("sr"), SerbianName, SerbianName },
        { Locale.forLanguageTag("sr-Latn"), SerbLatinName, SerbLatinName },
        { new Locale("hr"), EngName, EngName },
        { new Locale("in"), EngName, EngName },
        { new Locale("lt"), EngName, EngName },
        { new Locale("nl"), EngName, EngName },
        { new Locale("no"), EngName, "R" },
        { new Locale("sv"), EngName, EngName },
        // el fallback to root
        { new Locale("el"), EngName, EngName }
    };
}
 
Example 6
Source File: LocaleEnhanceTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void testGetUnicodeLocaleType() {
    Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai");
    assertEquals("collation", "japanese", locale.getUnicodeLocaleType("co"));
    assertEquals("numbers", "thai", locale.getUnicodeLocaleType("nu"));

    // Unicode locale extension key is case insensitive
    assertEquals("key case", "japanese", locale.getUnicodeLocaleType("Co"));

    // if keyword is not present, returns null
    assertEquals("locale keyword not present", null, locale.getUnicodeLocaleType("xx"));

    // if no locale extension is set, returns null
    locale = Locale.forLanguageTag("und");
    assertEquals("locale extension not present", null, locale.getUnicodeLocaleType("co"));

    // typeless keyword
    locale = Locale.forLanguageTag("und-u-kn");
    assertEquals("typeless keyword", "", locale.getUnicodeLocaleType("kn"));

    // invalid keys throw exception
    new ExpectIAE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType("q"); }};
    new ExpectIAE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType("abcdefghi"); }};

    // null argument throws exception
    new ExpectNPE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType(null); }};
}
 
Example 7
Source File: TestJapaneseChronoImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_dayOfYearVsCalendar() {
    Locale locale = Locale.forLanguageTag("ja-JP-u-ca-japanese");
    Calendar cal = java.util.Calendar.getInstance(locale);

    for (JapaneseEra era : JapaneseEra.values()) {
        for (int year : new int[] {6, 7}) {
            JapaneseDate jd = JapaneseChronology.INSTANCE.dateYearDay(era, year, 1);
            OffsetDateTime jodt = OffsetDateTime.of(LocalDate.from(jd), LocalTime.MIN, ZoneOffset.UTC);
            long millis = jodt.toInstant().toEpochMilli();
            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.setTimeInMillis(millis);

            assertEquals(jd.get(ChronoField.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_YEAR),
                    "different DAY_OF_YEAR values in " + era + ", year: " + year);
            assertEquals(jd.range(ChronoField.DAY_OF_YEAR).getMaximum(), cal.getActualMaximum(Calendar.DAY_OF_YEAR),
                    "different maximum for DAY_OF_YEAR in " + era + ", year: " + year);
            assertEquals(jd.range(ChronoField.DAY_OF_YEAR).getMinimum(), cal.getActualMinimum(Calendar.DAY_OF_YEAR),
                    "different minimum for DAY_OF_YEAR in " + era + ",  year: " + year);
        }
    }

}
 
Example 8
Source File: JapanEraNameCompatTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name="JavaTime")
Object[][] dataJavaTime() {
    return new Object[][] {
        // locale, full, short
        { JAPAN, CJName, CJName },
        { KOREAN, KoreanName, KoreanName },
        { CHINA, CJName, CJName },
        { TAIWAN, CJName, CJName },
        { new Locale("ar"), ArabicName, ArabicName },
        { new Locale("th"), ThaiName, ThaiName },
        { new Locale("hi", "IN"), HindiName, HindiName },
        { new Locale("ru"), RussianName, RussianName },
        { new Locale("sr"), SerbianName, SerbianName },
        { Locale.forLanguageTag("sr-Latn"), SerbLatinName, SerbLatinName },
        { new Locale("hr"), EngName, EngName },
        { new Locale("in"), EngName, EngName },
        { new Locale("lt"), EngName, EngName },
        { new Locale("nl"), EngName, EngName },
        { new Locale("no"), EngName, "R" },
        { new Locale("sv"), EngName, EngName },
        // el fallback to root
        { new Locale("el"), EngName, EngName }
    };
}
 
Example 9
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void testGetExtension() {
    // forLanguageTag does NOT normalize to hyphen
    Locale locale = Locale.forLanguageTag("und-a-some_ex-tension");
    assertEquals("some_ex-tension", null, locale.getExtension('a'));

    // regular extension
    locale = new Builder().setExtension('a', "some-ex-tension").build();
    assertEquals("builder", "some-ex-tension", locale.getExtension('a'));

    // returns null if extension is not present
    assertEquals("empty b", null, locale.getExtension('b'));

    // throws exception if extension tag is illegal
    new ExpectIAE() { public void call() { Locale.forLanguageTag("").getExtension('\uD800'); }};

    // 'x' is not an extension, it's a private use tag, but it's accessed through this API
    locale = Locale.forLanguageTag("x-y-z-blork");
    assertEquals("x", "y-z-blork", locale.getExtension('x'));
}
 
Example 10
Source File: MailService.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process(templateName, context);
    String subject = messageSource.getMessage(titleKey, null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);

}
 
Example 11
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testGetUnicodeLocaleAttributes() {
    Locale locale = Locale.forLanguageTag("en-US-u-abc-def");
    Set<String> attributes = locale.getUnicodeLocaleAttributes();
    assertEquals("number of attributes", 2, attributes.size());
    assertTrue("attribute abc", attributes.contains("abc"));
    assertTrue("attribute def", attributes.contains("def"));

    locale = Locale.forLanguageTag("en-US-u-ca-gregory");
    attributes = locale.getUnicodeLocaleAttributes();
    assertTrue("empty attributes", attributes.isEmpty());
}
 
Example 12
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testGetDisplayScriptWithLocale() {
    Locale latnLocale = Locale.forLanguageTag("und-latn");
    Locale hansLocale = Locale.forLanguageTag("und-hans");

    assertEquals("latn US", "Latin", latnLocale.getDisplayScript(Locale.US));
    assertEquals("hans US", "Simplified Han", hansLocale.getDisplayScript(Locale.US));

    assertEquals("latn DE", "Lateinisch", latnLocale.getDisplayScript(Locale.GERMANY));
    assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript(Locale.GERMANY));
}
 
Example 13
Source File: FormatStringsRegistryImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public FormatStrings getFormatStrings(Locale locale) {
    if (useLocaleLanguageOnly)
        locale = Locale.forLanguageTag(locale.getLanguage());
    return formatStringsMap.get(locale);
}
 
Example 14
Source File: LocaleEnhanceTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testGetUnicodeLocaleKeys() {
    Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai");
    Set<String> result = locale.getUnicodeLocaleKeys();
    assertEquals("two keys", 2, result.size());
    assertTrue("co and nu", result.contains("co") && result.contains("nu"));

    // result is not modifiable
    try {
        result.add("frobozz");
        errln("expected exception when add to locale key set");
    }
    catch (UnsupportedOperationException e) {
        // ok
    }
}
 
Example 15
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 16
Source File: LocaleTextImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void setLang(String lang) {
   this.locale = Locale.forLanguageTag(lang);
}
 
Example 17
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public void testGetDisplayName() {
    final Locale[] testLocales = {
            Locale.ROOT,
            new Locale("en"),
            new Locale("en", "US"),
            new Locale("", "US"),
            new Locale("no", "NO", "NY"),
            new Locale("", "", "NY"),
            Locale.forLanguageTag("zh-Hans"),
            Locale.forLanguageTag("zh-Hant"),
            Locale.forLanguageTag("zh-Hans-CN"),
            Locale.forLanguageTag("und-Hans"),
    };

    final String[] displayNameEnglish = {
            "",
            "English",
            "English (United States)",
            "United States",
            "Norwegian (Norway,Nynorsk)",
            "Nynorsk",
            "Chinese (Simplified Han)",
            "Chinese (Traditional Han)",
            "Chinese (Simplified Han,China)",
            "Simplified Han",
    };

    final String[] displayNameSimplifiedChinese = {
            "",
            "\u82f1\u6587",
            "\u82f1\u6587 (\u7f8e\u56fd)",
            "\u7f8e\u56fd",
            "\u632a\u5a01\u6587 (\u632a\u5a01,Nynorsk)",
            "Nynorsk",
            "\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587)",
            "\u4e2d\u6587 (\u7e41\u4f53\u4e2d\u6587)",
            "\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587,\u4e2d\u56fd)",
            "\u7b80\u4f53\u4e2d\u6587",
    };

    for (int i = 0; i < testLocales.length; i++) {
        Locale loc = testLocales[i];
        assertEquals("English display name for " + loc.toLanguageTag(),
                displayNameEnglish[i], loc.getDisplayName(Locale.ENGLISH));
        assertEquals("Simplified Chinese display name for " + loc.toLanguageTag(),
                displayNameSimplifiedChinese[i], loc.getDisplayName(Locale.CHINA));
    }
}
 
Example 18
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public void testBuilderSetLocale() {
    Builder builder = new Builder();
    Builder lenientBuilder = new Builder();

    String languageTag = "en-Latn-US-NewYork-a-bb-ccc-u-co-japanese-x-y-z";
    String target = "en-Latn-US-NewYork-a-bb-ccc-u-co-japanese-x-y-z";

    Locale locale = Locale.forLanguageTag(languageTag);
    Locale result = lenientBuilder
        .setLocale(locale)
        .build();
    assertEquals("long tag", target, result.toLanguageTag());
    assertEquals("long tag", locale, result);

    // null is illegal
    new BuilderNPE("locale") {
        public void call() { b.setLocale(null); }
    };

    // builder canonicalizes the three legacy locales:
    // ja_JP_JP, th_TH_TH, no_NY_NO.
    locale = builder.setLocale(new Locale("ja", "JP", "JP")).build();
    assertEquals("ja_JP_JP languagetag", "ja-JP-u-ca-japanese", locale.toLanguageTag());
    assertEquals("ja_JP_JP variant", "", locale.getVariant());

    locale = builder.setLocale(new Locale("th", "TH", "TH")).build();
    assertEquals("th_TH_TH languagetag", "th-TH-u-nu-thai", locale.toLanguageTag());
    assertEquals("th_TH_TH variant", "", locale.getVariant());

    locale = builder.setLocale(new Locale("no", "NO", "NY")).build();
    assertEquals("no_NO_NY languagetag", "nn-NO", locale.toLanguageTag());
    assertEquals("no_NO_NY language", "nn", locale.getLanguage());
    assertEquals("no_NO_NY variant", "", locale.getVariant());

    // non-canonical, non-legacy locales are invalid
    new BuilderILE("123_4567_89") {
        public void call() {
            b.setLocale(new Locale("123", "4567", "89"));
        }
    };
}
 
Example 19
Source File: LocaleEnhanceTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public void testSerialize() {
    final Locale[] testLocales = {
        Locale.ROOT,
        new Locale("en"),
        new Locale("en", "US"),
        new Locale("en", "US", "Win"),
        new Locale("en", "US", "Win_XP"),
        new Locale("ja", "JP"),
        new Locale("ja", "JP", "JP"),
        new Locale("th", "TH"),
        new Locale("th", "TH", "TH"),
        new Locale("no", "NO"),
        new Locale("nb", "NO"),
        new Locale("nn", "NO"),
        new Locale("no", "NO", "NY"),
        new Locale("nn", "NO", "NY"),
        new Locale("he", "IL"),
        new Locale("he", "IL", "var"),
        new Locale("Language", "Country", "Variant"),
        new Locale("", "US"),
        new Locale("", "", "Java"),
        Locale.forLanguageTag("en-Latn-US"),
        Locale.forLanguageTag("zh-Hans"),
        Locale.forLanguageTag("zh-Hant-TW"),
        Locale.forLanguageTag("ja-JP-u-ca-japanese"),
        Locale.forLanguageTag("und-Hant"),
        Locale.forLanguageTag("und-a-123-456"),
        Locale.forLanguageTag("en-x-java"),
        Locale.forLanguageTag("th-TH-u-ca-buddist-nu-thai-x-lvariant-TH"),
    };

    for (Locale locale : testLocales) {
        try {
            // write
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(locale);

            // read
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            Object o = ois.readObject();

            assertEquals("roundtrip " + locale, locale, o);
        } catch (Exception e) {
            errln(locale + " encountered exception:" + e.getLocalizedMessage());
        }
    }
}
 
Example 20
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void testGetDisplayName() {
    final Locale[] testLocales = {
            Locale.ROOT,
            new Locale("en"),
            new Locale("en", "US"),
            new Locale("", "US"),
            new Locale("no", "NO", "NY"),
            new Locale("", "", "NY"),
            Locale.forLanguageTag("zh-Hans"),
            Locale.forLanguageTag("zh-Hant"),
            Locale.forLanguageTag("zh-Hans-CN"),
            Locale.forLanguageTag("und-Hans"),
    };

    final String[] displayNameEnglish = {
            "",
            "English",
            "English (United States)",
            "United States",
            "Norwegian (Norway,Nynorsk)",
            "Nynorsk",
            "Chinese (Simplified Han)",
            "Chinese (Traditional Han)",
            "Chinese (Simplified Han,China)",
            "Simplified Han",
    };

    final String[] displayNameSimplifiedChinese = {
            "",
            "\u82f1\u6587",
            "\u82f1\u6587 (\u7f8e\u56fd)",
            "\u7f8e\u56fd",
            "\u632a\u5a01\u6587 (\u632a\u5a01,Nynorsk)",
            "Nynorsk",
            "\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587)",
            "\u4e2d\u6587 (\u7e41\u4f53\u4e2d\u6587)",
            "\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587,\u4e2d\u56fd)",
            "\u7b80\u4f53\u4e2d\u6587",
    };

    for (int i = 0; i < testLocales.length; i++) {
        Locale loc = testLocales[i];
        assertEquals("English display name for " + loc.toLanguageTag(),
                displayNameEnglish[i], loc.getDisplayName(Locale.ENGLISH));
        assertEquals("Simplified Chinese display name for " + loc.toLanguageTag(),
                displayNameSimplifiedChinese[i], loc.getDisplayName(Locale.CHINA));
    }
}