java.util.Locale

Here are the examples of the java api class java.util.Locale taken from open source projects.

1. LocaleTest#test_toString()

Project: j2objc
File: LocaleTest.java
/**
	 * @tests java.util.Locale#toString()
	 */
public void test_toString() {
    // Test for method java.lang.String java.util.Locale.toString()
    assertEquals("Returned incorrect string representation", "en_CA_WIN32", testLocale.toString());
    Locale l = new Locale("en", "");
    assertEquals("Wrong representation 1", "en", l.toString());
    l = new Locale("", "CA");
    assertEquals("Wrong representation 2", "_CA", l.toString());
    // Non-bug difference for HARMONY-5442
    l = new Locale("", "CA", "var");
    assertEquals("Wrong representation 2.5", "_CA_var", l.toString());
    l = new Locale("en", "", "WIN");
    assertEquals("Wrong representation 4", "en__WIN", l.toString());
    l = new Locale("en", "CA");
    assertEquals("Wrong representation 6", "en_CA", l.toString());
    l = new Locale("en", "CA", "VAR");
    assertEquals("Wrong representation 7", "en_CA_VAR", l.toString());
    l = new Locale("", "", "var");
    assertEquals("Wrong representation 8", "", l.toString());
}

2. LocaleTest#TestChangedISO639Codes()

Project: openjdk
File: LocaleTest.java
/**
     * @bug 4052404 4778440
     */
public void TestChangedISO639Codes() {
    Locale hebrewOld = new Locale("iw", "IL", "");
    Locale hebrewNew = new Locale("he", "IL", "");
    Locale yiddishOld = new Locale("ji", "IL", "");
    Locale yiddishNew = new Locale("yi", "IL", "");
    Locale indonesianOld = new Locale("in", "", "");
    Locale indonesianNew = new Locale("id", "", "");
    if (!hebrewNew.getLanguage().equals("iw"))
        errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + hebrewNew.getLanguage() + "\"");
    if (!yiddishNew.getLanguage().equals("ji"))
        errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + yiddishNew.getLanguage() + "\"");
    if (!indonesianNew.getLanguage().equals("in"))
        errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + indonesianNew.getLanguage() + "\"");
}

3. Lang#findLocaleDescription()

Project: opensearchserver
File: Lang.java
public static final Locale findLocaleDescription(String language) {
    if (StringUtils.isEmpty(language))
        return null;
    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) if (locale.getLanguage().equalsIgnoreCase(language))
        return locale;
    for (Locale locale : locales) if (locale.getDisplayName(Locale.ENGLISH).equalsIgnoreCase(language))
        return locale;
    for (Locale locale : locales) if (locale.getDisplayLanguage(Locale.ENGLISH).equalsIgnoreCase(language))
        return locale;
    for (Locale locale : locales) if (locale.getDisplayName().equalsIgnoreCase(language))
        return locale;
    for (Locale locale : locales) if (locale.getDisplayLanguage().equalsIgnoreCase(language))
        return locale;
    return null;
}

4. LocaleTest#TestChangedISO639Codes()

Project: jdk7u-jdk
File: LocaleTest.java
/**
     * @bug 4052404 4778440
     */
public void TestChangedISO639Codes() {
    Locale hebrewOld = new Locale("iw", "IL", "");
    Locale hebrewNew = new Locale("he", "IL", "");
    Locale yiddishOld = new Locale("ji", "IL", "");
    Locale yiddishNew = new Locale("yi", "IL", "");
    Locale indonesianOld = new Locale("in", "", "");
    Locale indonesianNew = new Locale("id", "", "");
    if (!hebrewNew.getLanguage().equals("iw"))
        errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + hebrewNew.getLanguage() + "\"");
    if (!yiddishNew.getLanguage().equals("ji"))
        errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + yiddishNew.getLanguage() + "\"");
    if (!indonesianNew.getLanguage().equals("in"))
        errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + indonesianNew.getLanguage() + "\"");
}

5. LocaleTest#TestSimpleObjectStuff()

Project: jdk7u-jdk
File: LocaleTest.java
public void TestSimpleObjectStuff() {
    Locale test1 = new Locale("aa", "AA");
    Locale test2 = new Locale("aa", "AA");
    Locale test3 = (Locale) test1.clone();
    Locale test4 = new Locale("zz", "ZZ");
    if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3)
        errln("Some of the test variables point to the same locale!");
    if (test3 == null)
        errln("clone() failed to produce a valid object!");
    if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3))
        errln("clone() or equals() failed: objects that should compare equal don't");
    if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4))
        errln("equals() failed: objects that shouldn't compare equal do");
    int hash1 = test1.hashCode();
    int hash2 = test2.hashCode();
    int hash3 = test3.hashCode();
    if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3)
        errln("hashCode() failed: objects that should have the same hash code don't");
}

6. LocaleTest#TestSimpleObjectStuff()

Project: openjdk
File: LocaleTest.java
public void TestSimpleObjectStuff() {
    Locale test1 = new Locale("aa", "AA");
    Locale test2 = new Locale("aa", "AA");
    Locale test3 = (Locale) test1.clone();
    Locale test4 = new Locale("zz", "ZZ");
    if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3)
        errln("Some of the test variables point to the same locale!");
    if (test3 == null)
        errln("clone() failed to produce a valid object!");
    if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3))
        errln("clone() or equals() failed: objects that should compare equal don't");
    if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4))
        errln("equals() failed: objects that shouldn't compare equal do");
    int hash1 = test1.hashCode();
    int hash2 = test2.hashCode();
    int hash3 = test3.hashCode();
    if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3)
        errln("hashCode() failed: objects that should have the same hash code don't");
}

7. TimeSpanConverterTest#testSpanish()

Project: twitter4j
File: TimeSpanConverterTest.java
public void testSpanish() throws Exception {
    Locale[] locales = Locale.getAvailableLocales();
    Locale locale = null;
    for (Locale loc : locales) {
        if ("es".equals(loc.getLanguage())) {
            locale = loc;
        }
    }
    converter = new TimeSpanConverter(locale);
    assertTimeSpanString("Ahora", System.currentTimeMillis() - second);
    assertTimeSpanString("hace 4 segundos", System.currentTimeMillis() - second * 4);
    assertTimeSpanString("hace 1 minuto", System.currentTimeMillis() - second * 61);
    assertTimeSpanString("hace 3 minutos", System.currentTimeMillis() - minute * 3);
    assertTimeSpanString("hace 1 hora", System.currentTimeMillis() - hour);
    assertTimeSpanString("hace 3 horas", System.currentTimeMillis() - hour * 3);
    assertTimeSpanString("18 dic 09", getSpecificLocalDateInMillis(2009, 11, 18));
}

8. LocaleTest#countryNamesProvided()

Project: teavm
File: LocaleTest.java
@Test
public void countryNamesProvided() {
    Locale usEnglish = new Locale("en", "US");
    Locale gbEnglish = new Locale("en", "GB");
    Locale russian = new Locale("ru", "RU");
    assertEquals("United Kingdom", gbEnglish.getDisplayCountry(usEnglish));
    assertEquals("United States", usEnglish.getDisplayCountry(usEnglish));
    assertEquals("Russia", russian.getDisplayCountry(usEnglish));
    // JVM gives here name that differs to the name provided by CLDR
    //assertEquals("??????????? ???????????", gbEnglish.getDisplayCountry(russian));
    assertEquals("??????????? ?????", usEnglish.getDisplayCountry(russian));
    assertEquals("??????", russian.getDisplayCountry(russian));
}

9. LocaleTest#languageNamesProvided()

Project: teavm
File: LocaleTest.java
@Test
public void languageNamesProvided() {
    Locale english = new Locale("en", "");
    Locale usEnglish = new Locale("en", "US");
    Locale russian = new Locale("ru", "RU");
    assertEquals("English", english.getDisplayLanguage(english));
    assertEquals("English", english.getDisplayLanguage(usEnglish));
    assertEquals("Russian", russian.getDisplayLanguage(english));
    assertEquals("English", english.getDisplayLanguage(usEnglish));
    assertEquals("Russian", russian.getDisplayLanguage(usEnglish));
    assertEquals("??????????", english.getDisplayLanguage(russian));
    assertEquals("???????", russian.getDisplayLanguage(russian));
}

10. ContentFilterLanguagesMapTest#testISOCodeConvertions()

Project: community-edition
File: ContentFilterLanguagesMapTest.java
public void testISOCodeConvertions() throws Exception {
    // New ISO code list
    String[] newCode = { "he", "id", "yi" };
    String[] oldCode = { "iw", "in", "ji" };
    Locale loc0 = new Locale(newCode[0]);
    Locale loc1 = new Locale(newCode[1]);
    Locale loc2 = new Locale(newCode[2]);
    // Ensure that java.util.Locale has converted the new ISO code into new iso code
    assertEquals("java.util.Locale Convertion not correct for " + newCode[0], oldCode[0], loc0.getLanguage());
    assertEquals("java.util.Locale Convertion not correct for " + newCode[1], oldCode[1], loc1.getLanguage());
    assertEquals("java.util.Locale Convertion not correct for " + newCode[2], oldCode[2], loc2.getLanguage());
    // Ensure that the convertion is correcte
    assertEquals("Convertion of new ISO codes not correct for " + newCode[0], oldCode[0], contentFilterLanguagesService.convertToOldISOCode(newCode[0]));
    assertEquals("Convertion of new ISO codes not correct for " + newCode[1], oldCode[1], contentFilterLanguagesService.convertToOldISOCode(newCode[1]));
    assertEquals("Convertion of new ISO codes not correct for " + newCode[2], oldCode[2], contentFilterLanguagesService.convertToOldISOCode(newCode[2]));
    assertEquals("Convertion of old ISO codes not correct for " + oldCode[0], newCode[0], contentFilterLanguagesService.convertToNewISOCode(oldCode[0]));
    assertEquals("Convertion of old ISO codes not correct for " + oldCode[1], newCode[1], contentFilterLanguagesService.convertToNewISOCode(oldCode[1]));
    assertEquals("Convertion of old ISO codes not correct for " + oldCode[2], newCode[2], contentFilterLanguagesService.convertToNewISOCode(oldCode[2]));
}

11. GenericListAdapterFactoryTest#test_i18n_titles()

Project: acs-aem-commons
File: GenericListAdapterFactoryTest.java
@Test
public void test_i18n_titles() {
    Locale french = new Locale("fr");
    Locale swissFrench = new Locale("fr", "ch");
    Locale franceFrench = new Locale("fr", "fr");
    GenericList list = adapterFactory.getAdapter(listPage, GenericList.class);
    assertNotNull(list);
    List<Item> items = list.getItems();
    assertNotNull(items);
    assertEquals(2, items.size());
    assertEquals("titleone", items.get(0).getTitle(french));
    assertEquals("titleone", items.get(0).getTitle(swissFrench));
    assertEquals("titleone", items.get(0).getTitle(franceFrench));
    assertEquals("french_title", items.get(1).getTitle(french));
    assertEquals("swiss_french_title", items.get(1).getTitle(swissFrench));
    assertEquals("french_title", items.get(1).getTitle(franceFrench));
}

12. LocaleEnhanceTest#testGetDisplayScript()

Project: jdk7u-jdk
File: LocaleEnhanceTest.java
public void testGetDisplayScript() {
    Locale latnLocale = Locale.forLanguageTag("und-latn");
    Locale hansLocale = Locale.forLanguageTag("und-hans");
    Locale oldLocale = Locale.getDefault();
    Locale.setDefault(Locale.US);
    assertEquals("latn US", "Latin", latnLocale.getDisplayScript());
    assertEquals("hans US", "Simplified Han", hansLocale.getDisplayScript());
    Locale.setDefault(Locale.GERMANY);
    assertEquals("latn DE", "Lateinisch", latnLocale.getDisplayScript());
    assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript());
    Locale.setDefault(oldLocale);
}

13. InterpretConsoleCommandExtension#pickLanguage()

Project: smarthome
File: InterpretConsoleCommandExtension.java
/**
     * Picks the best fit from a set of available languages (given by {@link Locale}s).
     * Matching happens in the following priority order:
     * 1st: system's default {@link Locale} (e.g. "de-DE"), if contained in {@link locales}
     * 2nd: first item in {@link locales} matching system default language (e.g. "de" matches "de-CH")
     * 3rd: first language in {@link locales}
     * 4th: English, if {@link locales} is null or empty
     *
     * @param locales set of supported {@link Locale}s to pick from
     * @return {@link Locale} of the best fitting language
     */
private Locale pickLanguage(Set<Locale> locales) {
    if (locales == null || locales.size() == 0) {
        return Locale.ENGLISH;
    }
    Locale locale = Locale.getDefault();
    if (locales.contains(locale)) {
        return locale;
    }
    String language = locale.getLanguage();
    Locale first = null;
    for (Locale l : locales) {
        if (first == null) {
            first = l;
        }
        if (language.equals(l.getLanguage())) {
            return l;
        }
    }
    return first;
}

14. NumberUtil#isLanguageSupported()

Project: opennlp
File: NumberUtil.java
/**
   * Checks if the language is supported.
   *
   * @param languageCode language code, e.g. "en", "pt"
   * @return true if the language is supported
   */
public static boolean isLanguageSupported(String languageCode) {
    Locale locale = new Locale(languageCode);
    Locale possibleLocales[] = NumberFormat.getAvailableLocales();
    boolean isLocaleSupported = false;
    for (Locale possibleLocale : possibleLocales) {
        // search if local is contained
        if (possibleLocale.equals(locale)) {
            isLocaleSupported = true;
            break;
        }
    }
    return isLocaleSupported;
}

15. LocaleEnhanceTest#testGetDisplayScript()

Project: openjdk
File: LocaleEnhanceTest.java
public void testGetDisplayScript() {
    Locale latnLocale = Locale.forLanguageTag("und-latn");
    Locale hansLocale = Locale.forLanguageTag("und-hans");
    Locale oldLocale = Locale.getDefault();
    Locale.setDefault(Locale.US);
    assertEquals("latn US", "Latin", latnLocale.getDisplayScript());
    assertEquals("hans US", "Simplified Han", hansLocale.getDisplayScript());
    Locale.setDefault(Locale.GERMANY);
    assertEquals("latn DE", "Lateinisch", latnLocale.getDisplayScript());
    assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript());
    Locale.setDefault(oldLocale);
}

16. ISO8601GregorianCalendarConverter17Test#testCanLoadTimeWithDefaultDifferentLocaleForFormat()

Project: xstream
File: ISO8601GregorianCalendarConverter17Test.java
public void testCanLoadTimeWithDefaultDifferentLocaleForFormat() {
    final ISO8601GregorianCalendarConverter converter = new ISO8601GregorianCalendarConverter();
    Locale defaultLocale = Locale.getDefault();
    Locale defaultLocaleForFormat = Locale.getDefault(Locale.Category.FORMAT);
    try {
        Locale.setDefault(Locale.US);
        Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);
        Calendar in = new GregorianCalendar(2013, Calendar.JUNE, 17, 16, 0, 0);
        String converterXML = converter.toString(in);
        Calendar out = (Calendar) converter.fromString(converterXML);
        assertEquals(in, out);
    } finally {
        Locale.setDefault(defaultLocale);
        Locale.setDefault(defaultLocaleForFormat);
    }
}

17. OnChangeAjaxBehaviorPage#getValue()

Project: wicket
File: OnChangeAjaxBehaviorPage.java
private String getValue(String input) {
    if (Strings.isEmpty(input)) {
        return "";
    }
    StringBuilder buffer = new StringBuilder();
    Locale[] locales = Locale.getAvailableLocales();
    for (final Locale locale : locales) {
        final String country = locale.getDisplayCountry();
        if (country.toUpperCase().startsWith(input.toUpperCase())) {
            buffer.append(country);
            buffer.append(' ');
        }
    }
    return buffer.toString();
}

18. PackageResourceReferenceTest#userAttributesPreference()

Project: wicket
File: PackageResourceReferenceTest.java
/**
	 * Assert preference for specified locale and style over session ones
	 */
@Test
public void userAttributesPreference() {
    tester.getSession().setLocale(new Locale("en"));
    tester.getSession().setStyle("style");
    Locale[] userLocales = { null, new Locale("pt"), new Locale("pt", "BR") };
    String userStyle = "style2";
    for (Locale userLocale : userLocales) {
        for (String variation : variations) {
            ResourceReference reference = new PackageResourceReference(scope, "resource.txt", userLocale, userStyle, variation);
            UrlAttributes urlAttributes = reference.getUrlAttributes();
            assertEquals(userLocale, urlAttributes.getLocale());
            assertEquals(userStyle, urlAttributes.getStyle());
            assertEquals(variation, urlAttributes.getVariation());
        }
    }
}

19. UserLocaleHelper#getCurrentUserLocale()

Project: uPortal
File: UserLocaleHelper.java
/**
	 * Return the current user's locale.
	 * 
	 * @param request
	 * @return
	 */
public Locale getCurrentUserLocale(PortletRequest request) {
    final HttpServletRequest originalPortalRequest = this.portalRequestUtils.getPortletHttpRequest(request);
    IUserInstance ui = userInstanceManager.getUserInstance(originalPortalRequest);
    IUserPreferencesManager upm = ui.getPreferencesManager();
    final IUserProfile userProfile = upm.getUserProfile();
    LocaleManager localeManager = userProfile.getLocaleManager();
    // first check the session locales
    Locale[] sessionLocales = localeManager.getSessionLocales();
    if (sessionLocales != null && sessionLocales.length > 0) {
        return sessionLocales[0];
    }
    // if no session locales were found, check the user locales
    Locale[] userLocales = localeManager.getUserLocales();
    if (userLocales != null && userLocales.length > 0) {
        return userLocales[0];
    }
    // just return null
    return null;
}

20. UserLocaleHelper#getLocales()

Project: uPortal
File: UserLocaleHelper.java
/**
	 * Return a list of LocaleBeans matching the currently available locales
	 * for the portal.
	 * 
	 * @param currentLocale
	 * @return
	 */
public List<LocaleBean> getLocales(Locale currentLocale) {
    List<LocaleBean> locales = new ArrayList<LocaleBean>();
    // get the array of locales available from the portal
    Locale[] portalLocales = getPortalLocales();
    for (Locale locale : portalLocales) {
        if (currentLocale != null) {
            // if a current locale is available, display language names
            // using the current locale
            locales.add(new LocaleBean(locale, currentLocale));
        } else {
            locales.add(new LocaleBean(locale));
        }
    }
    return locales;
}

21. LocaleUtilTest#testGetParentLocale()

Project: tiles-request
File: LocaleUtilTest.java
/**
     * Test method for {@link LocaleUtil#getParentLocale(Locale)}.
     */
public void testGetParentLocale() {
    assertNull("The parent locale of NULL_LOCALE is not correct", LocaleUtil.getParentLocale(Locale.ROOT));
    assertEquals("The parent locale of 'en' is not correct", Locale.ROOT, LocaleUtil.getParentLocale(Locale.ENGLISH));
    assertEquals("The parent locale of 'en_US' is not correct", Locale.ENGLISH, LocaleUtil.getParentLocale(Locale.US));
    Locale locale = new Locale("es", "ES", "Traditional_WIN");
    Locale parentLocale = new Locale("es", "ES");
    assertEquals("The parent locale of 'es_ES_Traditional_WIN' is not correct", parentLocale, LocaleUtil.getParentLocale(locale));
}

22. PostfixedApplicationResource#validateLocale()

Project: tiles-request
File: PostfixedApplicationResource.java
private static Locale validateLocale(Locale locale) {
    Locale withoutVariant = locale.getVariant().isEmpty() ? locale : new Locale(locale.getLanguage(), locale.getCountry());
    Locale result = locale;
    if (!availableLocales.contains(withoutVariant)) {
        if (!result.getCountry().isEmpty()) {
            result = new Locale(result.getLanguage());
        }
        if (!availableLocales.contains(result)) {
            result = Locale.ROOT;
        }
    }
    return result;
}

23. ResolvingLocaleUrlDefinitionDAOTest#setupUrl()

Project: tiles
File: ResolvingLocaleUrlDefinitionDAOTest.java
private ApplicationResource setupUrl(String filename, Locale... locales) throws IOException {
    ApplicationResource url = new URLApplicationResource("org/apache/tiles/config/" + filename + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + ".xml"));
    assertNotNull("Could not load " + filename + " file.", url);
    expect(applicationContext.getResource(url.getLocalePath())).andReturn(url).anyTimes();
    expect(applicationContext.getResource(url, Locale.ROOT)).andReturn(url).anyTimes();
    Map<Locale, ApplicationResource> localeResources = new HashMap<Locale, ApplicationResource>();
    for (Locale locale : locales) {
        ApplicationResource urlLocale = new URLApplicationResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml"));
        assertNotNull("Could not load " + filename + "_" + locale.toString() + " file.", urlLocale);
        localeResources.put(locale, urlLocale);
    }
    for (Locale locale : new Locale[] { Locale.CANADA_FRENCH, Locale.FRENCH, Locale.US, Locale.ENGLISH, Locale.CHINA, Locale.CHINESE, Locale.ITALY, Locale.ITALIAN, new Locale("es", "CO"), new Locale("es", "CA") }) {
        ApplicationResource urlLocale = localeResources.get(locale);
        expect(applicationContext.getResource(url, locale)).andReturn(urlLocale).anyTimes();
    }
    return url;
}

24. LocaleUrlDefinitionDAOTest#setupUrl()

Project: tiles
File: LocaleUrlDefinitionDAOTest.java
private ApplicationResource setupUrl(String filename, Locale... locales) throws IOException {
    ApplicationResource url = new URLApplicationResource("org/apache/tiles/config/" + filename + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + ".xml"));
    assertNotNull("Could not load " + filename + " file.", url);
    expect(applicationContext.getResource(url.getLocalePath())).andReturn(url).anyTimes();
    expect(applicationContext.getResource(url, Locale.ROOT)).andReturn(url).anyTimes();
    Map<Locale, ApplicationResource> localeResources = new HashMap<Locale, ApplicationResource>();
    for (Locale locale : locales) {
        ApplicationResource urlLocale = new URLApplicationResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml"));
        assertNotNull("Could not load " + filename + "_" + locale.toString() + " file.", urlLocale);
        localeResources.put(locale, urlLocale);
    }
    for (Locale locale : new Locale[] { Locale.CANADA_FRENCH, Locale.FRENCH, Locale.US, Locale.ENGLISH, Locale.CHINA, Locale.CHINESE }) {
        ApplicationResource urlLocale = localeResources.get(locale);
        expect(applicationContext.getResource(url, locale)).andReturn(urlLocale).anyTimes();
    }
    return url;
}

25. CachingLocaleUrlDefinitionDAOTest#setupUrl()

Project: tiles
File: CachingLocaleUrlDefinitionDAOTest.java
private ApplicationResource setupUrl(String filename, Locale... locales) throws IOException {
    ApplicationResource url = new URLApplicationResource("org/apache/tiles/config/" + filename + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + ".xml"));
    assertNotNull("Could not load " + filename + " file.", url);
    expect(applicationContext.getResource(url.getLocalePath())).andReturn(url).anyTimes();
    expect(applicationContext.getResource(url, Locale.ROOT)).andReturn(url).anyTimes();
    Map<Locale, ApplicationResource> localeResources = new HashMap<Locale, ApplicationResource>();
    for (Locale locale : locales) {
        ApplicationResource urlLocale = new URLApplicationResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml", this.getClass().getClassLoader().getResource("org/apache/tiles/config/" + filename + "_" + locale.toString() + ".xml"));
        assertNotNull("Could not load " + filename + "_" + locale.toString() + " file.", urlLocale);
        localeResources.put(locale, urlLocale);
    }
    for (Locale locale : new Locale[] { Locale.CANADA_FRENCH, Locale.FRENCH, Locale.US, Locale.ENGLISH, Locale.CHINA, Locale.CHINESE, Locale.ITALY, Locale.ITALIAN }) {
        ApplicationResource urlLocale = localeResources.get(locale);
        expect(applicationContext.getResource(url, locale)).andReturn(urlLocale).anyTimes();
    }
    return url;
}

26. CurrencyTest#getsSymbol()

Project: teavm
File: CurrencyTest.java
@Test
@SkipJVM
public void getsSymbol() {
    Locale russian = new Locale("ru");
    Locale english = new Locale("en");
    Currency currency = Currency.getInstance("USD");
    assertEquals("$", currency.getSymbol(english));
    assertEquals("$", currency.getSymbol(russian));
    currency = Currency.getInstance("RUB");
    assertEquals("RUB", currency.getSymbol(english));
    assertEquals("???.", currency.getSymbol(russian));
}

27. CurrencyTest#getsDisplayName()

Project: teavm
File: CurrencyTest.java
@Test
@SkipJVM
public void getsDisplayName() {
    Locale russian = new Locale("ru");
    Locale english = new Locale("en");
    Currency currency = Currency.getInstance("USD");
    assertEquals("US Dollar", currency.getDisplayName(english));
    assertEquals("?????? ???", currency.getDisplayName(russian));
    currency = Currency.getInstance("RUB");
    assertEquals("Russian Ruble", currency.getDisplayName(english));
    assertEquals("?????????? ?????", currency.getDisplayName(russian));
    assertEquals("CHF", Currency.getInstance("CHF").getDisplayName(new Locale("xx", "YY")));
}

28. Admin#doGetLocales()

Project: railo
File: Admin.java
/**
     * @throws PageException
     * 
     */
private void doGetLocales() throws PageException {
    Struct sct = new StructImpl(StructImpl.TYPE_LINKED);
    //Array arr=new ArrayImpl();
    String strLocale = getString("locale", "english (united kingdom)");
    Locale locale = LocaleFactory.getLocale(strLocale);
    pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
    Map locales = LocaleFactory.getLocales();
    Iterator it = locales.keySet().iterator();
    String key;
    Locale l;
    while (it.hasNext()) {
        key = (String) it.next();
        l = (Locale) locales.get(key);
        sct.setEL(l.toString(), l.getDisplayName(locale));
    //arr.append(locale.getDisplayName());
    }
//arr.sort("textnocase","asc");
}

29. CmsXmlContainerPage#writeContainerPage()

Project: opencms-core
File: CmsXmlContainerPage.java
/**
     * Saves a container page in in-memory XML structure.<p>
     *
     * @param cms the current CMS context
     * @param cntPage the container page bean to save
     *
     * @throws CmsException if something goes wrong
     */
public void writeContainerPage(CmsObject cms, CmsContainerPageBean cntPage) throws CmsException {
    // keep unused containers
    CmsContainerPageBean savePage = cleanupContainersContainers(cms, cntPage);
    savePage = removeEmptyContainers(cntPage);
    // Replace existing locales with master locale
    for (Locale locale : getLocales()) {
        removeLocale(locale);
    }
    Locale masterLocale = CmsLocaleManager.MASTER_LOCALE;
    addLocale(cms, masterLocale);
    // add the nodes to the raw XML structure
    Element parent = getLocaleNode(masterLocale);
    saveContainerPage(cms, parent, savePage);
    initDocument(m_document, m_encoding, m_contentDefinition);
}

30. CmsXmlContainerPage#getContainerPage()

Project: opencms-core
File: CmsXmlContainerPage.java
/**
     * Gets the container page content as a bean.<p>
     *
     * @param cms the current CMS context
     * @return the bean containing the container page data
     */
public CmsContainerPageBean getContainerPage(CmsObject cms) {
    Locale masterLocale = CmsLocaleManager.MASTER_LOCALE;
    Locale localeToLoad = null;
    // this is important for 'legacy' container pages which were created before container pages became locale independent
    if (m_cntPages.containsKey(masterLocale)) {
        localeToLoad = masterLocale;
    } else if (!m_cntPages.isEmpty()) {
        localeToLoad = m_cntPages.keySet().iterator().next();
    }
    if (localeToLoad == null) {
        return null;
    } else {
        return m_cntPages.get(localeToLoad);
    }
}

31. CmsDynamicFunctionParser#getLocaleToUse()

Project: opencms-core
File: CmsDynamicFunctionParser.java
/**
     * Gets the locale to use for parsing the dynamic function.<p>
     *
     * @param cms the current CMS context
     * @param xmlContent the xml content from which the dynamic function should be read
     *
     * @return the locale from which the dynamic function should be read
     */
protected Locale getLocaleToUse(CmsObject cms, CmsXmlContent xmlContent) {
    Locale contextLocale = cms.getRequestContext().getLocale();
    if (xmlContent.hasLocale(contextLocale)) {
        return contextLocale;
    }
    Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
    if (xmlContent.hasLocale(defaultLocale)) {
        return defaultLocale;
    }
    if (!xmlContent.getLocales().isEmpty()) {
        return xmlContent.getLocales().get(0);
    } else {
        return defaultLocale;
    }
}

32. CmsVfsBundleManager#addPropertyBundle()

Project: opencms-core
File: CmsVfsBundleManager.java
/**
     * Adds a resource bundle based on a properties file in the VFS.<p>
     *
     * @param bundleResource the properties file
     */
private void addPropertyBundle(CmsResource bundleResource) {
    NameAndLocale nameAndLocale = getNameAndLocale(bundleResource);
    Locale locale = nameAndLocale.getLocale();
    String baseName = nameAndLocale.getName();
    m_bundleBaseNames.add(baseName);
    LOG.info(String.format("Adding property VFS bundle (path=%s, name=%s, locale=%s)", bundleResource.getRootPath(), baseName, "" + locale));
    Locale paramLocale = locale != null ? locale : CmsLocaleManager.getDefaultLocale();
    CmsVfsBundleParameters params = new CmsVfsBundleParameters(nameAndLocale.getName(), bundleResource.getRootPath(), paramLocale, locale == null, CmsVfsResourceBundle.TYPE_PROPERTIES);
    CmsVfsResourceBundle bundle = new CmsVfsResourceBundle(params);
    addBundle(baseName, locale, bundle);
}

33. CmsVfsSitemapService#ensureSingleLocale()

Project: opencms-core
File: CmsVfsSitemapService.java
/**
     * Removes unnecessary locales from a container page.<p>
     *
     * @param containerPage the container page which should be changed
     * @param localeRes the resource used to determine the locale
     *
     * @throws CmsException if something goes wrong
     */
void ensureSingleLocale(CmsXmlContainerPage containerPage, CmsResource localeRes) throws CmsException {
    CmsObject cms = getCmsObject();
    Locale mainLocale = CmsLocaleManager.getMainLocale(cms, localeRes);
    OpenCms.getLocaleManager();
    Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
    if (containerPage.hasLocale(mainLocale)) {
        removeAllLocalesExcept(containerPage, mainLocale);
    // remove other locales
    } else if (containerPage.hasLocale(defaultLocale)) {
        containerPage.copyLocale(defaultLocale, mainLocale);
        removeAllLocalesExcept(containerPage, mainLocale);
    } else if (containerPage.getLocales().size() > 0) {
        containerPage.copyLocale(containerPage.getLocales().get(0), mainLocale);
        removeAllLocalesExcept(containerPage, mainLocale);
    } else {
        containerPage.addLocale(cms, mainLocale);
    }
}

34. AboutLocale#localizedOutputOfDates()

Project: PortlandStateJavaSummer2016
File: AboutLocale.java
@Koan
public void localizedOutputOfDates() {
    Calendar cal = Calendar.getInstance();
    cal.set(2011, 3, 3);
    Date date = cal.getTime();
    // portuguese, Brazil
    Locale localeBR = new Locale("pt", "BR");
    DateFormat dateformatBR = DateFormat.getDateInstance(DateFormat.FULL, localeBR);
    assertEquals(dateformatBR.format(date), __);
    // German
    Locale localeJA = new Locale("de");
    DateFormat dateformatJA = DateFormat.getDateInstance(DateFormat.FULL, localeJA);
    // Well if you don't know how to type these characters, try "de", "it" or "us" ;-)
    assertEquals(dateformatJA.format(date), __);
}

35. PortletApplicationDefinition362ImplTest#testAddLocaleEncodingMapping()

Project: portals-pluto
File: PortletApplicationDefinition362ImplTest.java
/**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addLocaleEncodingMapping(java.util.Locale, java.lang.String)}.
    */
@Test
public void testAddLocaleEncodingMapping() {
    ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[] { Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
    String[] testencs = { "UTF-8", "Shift_JIS" };
    for (Locale loc : testlocs) {
        int ind = testlocs.indexOf(loc);
        cut.addLocaleEncodingMapping(loc, testencs[ind]);
    }
    Map<Locale, String> localemap = cut.getLocaleEncodingMappings();
    assertEquals(2, localemap.size());
    for (Locale loc : localemap.keySet()) {
        assertTrue(testlocs.contains(loc));
        int ind = testlocs.indexOf(loc);
        assertEquals(testencs[ind], localemap.get(loc));
    }
}

36. MergePortletAppTest#testAddLocaleEncodingMapping()

Project: portals-pluto
File: MergePortletAppTest.java
/**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addLocaleEncodingMapping(java.util.Locale, java.lang.String)}.
    */
@Test
public void testAddLocaleEncodingMapping() {
    ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[] { Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
    String[] testencs = { "UTF-8", "Shift_JIS" };
    for (Locale loc : testlocs) {
        int ind = testlocs.indexOf(loc);
        cut.addLocaleEncodingMapping(loc, testencs[ind]);
    }
    Map<Locale, String> localemap = cut.getLocaleEncodingMappings();
    assertEquals(2, localemap.size());
    for (Locale loc : localemap.keySet()) {
        assertTrue(testlocs.contains(loc));
        int ind = testlocs.indexOf(loc);
        assertEquals(testencs[ind], localemap.get(loc));
    }
}

37. JSR362PortletAppAnnotationTest#testAddLocaleEncodingMapping()

Project: portals-pluto
File: JSR362PortletAppAnnotationTest.java
/**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addLocaleEncodingMapping(java.util.Locale, java.lang.String)}.
    */
@Test
public void testAddLocaleEncodingMapping() {
    ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[] { Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
    String[] testencs = { "UTF-8", "Shift_JIS" };
    for (Locale loc : testlocs) {
        int ind = testlocs.indexOf(loc);
        cut.addLocaleEncodingMapping(loc, testencs[ind]);
    }
    Map<Locale, String> localemap = cut.getLocaleEncodingMappings();
    assertEquals(2, localemap.size());
    for (Locale loc : localemap.keySet()) {
        assertTrue(testlocs.contains(loc));
        int ind = testlocs.indexOf(loc);
        assertEquals(testencs[ind], localemap.get(loc));
    }
}

38. PortletApplicationDefinition286ImplTest#testAddLocaleEncodingMapping()

Project: portals-pluto
File: PortletApplicationDefinition286ImplTest.java
/**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addLocaleEncodingMapping(java.util.Locale, java.lang.String)}.
    */
@Test
public void testAddLocaleEncodingMapping() {
    ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[] { Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
    String[] testencs = { "UTF-8", "Shift_JIS" };
    for (Locale loc : testlocs) {
        int ind = testlocs.indexOf(loc);
        cut.addLocaleEncodingMapping(loc, testencs[ind]);
    }
    Map<Locale, String> localemap = cut.getLocaleEncodingMappings();
    assertEquals(2, localemap.size());
    for (Locale loc : localemap.keySet()) {
        assertTrue(testlocs.contains(loc));
        int ind = testlocs.indexOf(loc);
        assertEquals(testencs[ind], localemap.get(loc));
    }
}

39. DateUtils#toDate()

Project: PlutusAndroid
File: DateUtils.java
/**
     * Formats a date using the locale date format
     *
     * @param date The date that will be formatted
     * @return if the locale is US a date of the format 'EEEE MMMM d, yyyy' will be returned, otherwise a date of the format 'EEEE d MMMM yyyy' will be returned
     */
public static String toDate(Date date) {
    SimpleDateFormat format;
    Locale locale = Locale.getDefault();
    if (locale.equals(Locale.US))
        format = new SimpleDateFormat("EEEE MMMM d, yyyy", Locale.US);
    else
        format = new SimpleDateFormat("EEEE d MMMM yyyy", Locale.getDefault());
    return format.format(date);
}

40. Lang#findLocaleISO639()

Project: opensearchserver
File: Lang.java
public static Locale findLocaleISO639(String lang) {
    if (lang == null)
        return null;
    int l = lang.indexOf('-');
    if (l != -1)
        lang = lang.substring(0, l);
    lang = new Locale(lang).getLanguage();
    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) if (locale.getLanguage().equalsIgnoreCase(lang))
        return locale;
    return null;
}

41. ConceptTest#getName_shouldReturnExactNameLocaleMatchGivenExactEqualsTrue()

Project: openmrs-core
File: ConceptTest.java
/**
	 * @see Concept#getName(Locale,null)
	 */
@Test
@Verifies(value = "should return exact name locale match given exact equals true", method = "getName(Locale,null)")
public void getName_shouldReturnExactNameLocaleMatchGivenExactEqualsTrue() throws Exception {
    Locale definedNameLocale = new Locale("en", "US");
    Locale localeToSearch = new Locale("en", "US");
    Concept concept = new Concept();
    ConceptName fullySpecifiedName = new ConceptName("some name", definedNameLocale);
    fullySpecifiedName.setConceptNameId(1);
    fullySpecifiedName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED);
    fullySpecifiedName.setLocalePreferred(false);
    concept.addName(fullySpecifiedName);
    Assert.assertNotNull(concept.getName(localeToSearch, true));
    Assert.assertEquals("some name", concept.getName(localeToSearch, true).getName());
}

42. Bug4429024#getLanguage()

Project: openjdk
File: Bug4429024.java
static int getLanguage(String inLang, String localizedName) {
    Locale fiLocale = new Locale("fi", "FI");
    Locale inLocale = new Locale(inLang, "");
    if (!inLocale.getDisplayLanguage(fiLocale).equals(localizedName)) {
        System.out.println("Language " + inLang + " should be \"" + localizedName + "\", not \"" + inLocale.getDisplayLanguage(fiLocale) + "\"");
        return 1;
    } else {
        return 0;
    }
}

43. Bug4429024#getCountry()

Project: openjdk
File: Bug4429024.java
static int getCountry(String inCountry, String localizedName) {
    Locale fiLocale = new Locale("fi", "FI");
    Locale inLocale = new Locale("", inCountry);
    if (!inLocale.getDisplayCountry(fiLocale).equals(localizedName)) {
        System.out.println("Country " + inCountry + " should be \"" + localizedName + "\", not \"" + inLocale.getDisplayCountry(fiLocale) + "\"");
        return 1;
    } else {
        return 0;
    }
}

44. CmsContainerpageService#saveInheritanceGroup()

Project: opencms-core
File: CmsContainerpageService.java
/**
     * Saves the inheritance group.<p>
     *
     * @param resource the inheritance group resource
     * @param inheritanceContainer the inherited group container data
     *
     * @throws CmsException if something goes wrong
     */
private void saveInheritanceGroup(CmsResource resource, CmsInheritanceContainer inheritanceContainer) throws CmsException {
    CmsObject cms = getCmsObject();
    CmsFile file = cms.readFile(resource);
    CmsXmlContent document = CmsXmlContentFactory.unmarshal(cms, file);
    for (Locale docLocale : document.getLocales()) {
        document.removeLocale(docLocale);
    }
    Locale locale = Locale.ENGLISH;
    document.addLocale(cms, locale);
    document.getValue("Title", locale).setStringValue(cms, inheritanceContainer.getTitle());
    document.getValue("Description", locale).setStringValue(cms, inheritanceContainer.getDescription());
    document.getValue("ConfigName", locale).setStringValue(cms, inheritanceContainer.getName());
    byte[] content = document.marshal();
    file.setContents(content);
    cms.writeFile(file);
}

45. ComparableVersionTest#testLocaleIndependent()

Project: maven
File: ComparableVersionTest.java
public void testLocaleIndependent() {
    Locale orig = Locale.getDefault();
    Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
    try {
        for (Locale locale : locales) {
            Locale.setDefault(locale);
            checkVersionsEqual("1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        }
    } finally {
        Locale.setDefault(orig);
    }
}

46. StringUtilTestCase#testFormatBytes()

Project: libresonic
File: StringUtilTestCase.java
public void testFormatBytes() throws Exception {
    Locale locale = Locale.ENGLISH;
    assertEquals("Error in formatBytes().", "918 B", StringUtil.formatBytes(918, locale));
    assertEquals("Error in formatBytes().", "1023 B", StringUtil.formatBytes(1023, locale));
    assertEquals("Error in formatBytes().", "1 KB", StringUtil.formatBytes(1024, locale));
    assertEquals("Error in formatBytes().", "96 KB", StringUtil.formatBytes(98765, locale));
    assertEquals("Error in formatBytes().", "1024 KB", StringUtil.formatBytes(1048575, locale));
    assertEquals("Error in formatBytes().", "1.2 MB", StringUtil.formatBytes(1238476, locale));
    assertEquals("Error in formatBytes().", "3.50 GB", StringUtil.formatBytes(3758096384L, locale));
    locale = new Locale("no", "", "");
    assertEquals("Error in formatBytes().", "918 B", StringUtil.formatBytes(918, locale));
    assertEquals("Error in formatBytes().", "1023 B", StringUtil.formatBytes(1023, locale));
    assertEquals("Error in formatBytes().", "1 KB", StringUtil.formatBytes(1024, locale));
    assertEquals("Error in formatBytes().", "96 KB", StringUtil.formatBytes(98765, locale));
    assertEquals("Error in formatBytes().", "1024 KB", StringUtil.formatBytes(1048575, locale));
    assertEquals("Error in formatBytes().", "1,2 MB", StringUtil.formatBytes(1238476, locale));
    assertEquals("Error in formatBytes().", "3,50 GB", StringUtil.formatBytes(3758096384L, locale));
}

47. LocaleUtilTest#testLocaleUtil()

Project: jodd
File: LocaleUtilTest.java
@Test
public void testLocaleUtil() {
    Locale locale1 = LocaleUtil.getLocale("fr", "FR");
    Locale locale2 = LocaleUtil.getLocale("fr_FR");
    assertSame(locale1, locale2);
    DateFormatSymbolsEx dfs = LocaleUtil.getDateFormatSymbols(locale2);
    DateFormatSymbols dfsJava = new DateFormatSymbols(locale2);
    assertEquals(dfs.getMonth(0), dfsJava.getMonths()[0]);
    assertEquals(dfs.getWeekday(1), dfsJava.getWeekdays()[1]);
    assertEquals(dfs.getShortMonth(2), dfsJava.getShortMonths()[2]);
    locale1 = LocaleUtil.getLocale("en");
    locale2 = LocaleUtil.getLocale("en_EN");
    assertNotSame(locale1, locale2);
    dfs = LocaleUtil.getDateFormatSymbols(locale2);
    dfsJava = new DateFormatSymbols(locale2);
    assertEquals(dfs.getMonth(0), dfsJava.getMonths()[0]);
    assertEquals(dfs.getWeekday(1), dfsJava.getWeekdays()[1]);
    assertEquals(dfs.getShortMonth(2), dfsJava.getShortMonths()[2]);
}

48. CronTabDayOfWeekLocaleTest#parameters()

Project: Jenkins2
File: CronTabDayOfWeekLocaleTest.java
@Parameters
public static Collection<Object[]> parameters() {
    final Locale[] locales = Locale.getAvailableLocales();
    final Collection<Object[]> parameters = new ArrayList<Object[]>();
    for (final Locale locale : locales) {
        final Calendar cal = Calendar.getInstance(locale);
        if (GregorianCalendar.class.equals(cal.getClass())) {
            parameters.add(new Object[] { locale });
        }
    }
    return parameters;
}

49. LocaleTest#Test4147317()

Project: openjdk
File: LocaleTest.java
/**
     * @bug 4147317 4940539
     * java.util.Locale.getISO3Language() works wrong for non ISO-639 codes.
     * Should throw an exception for unknown locales, except they have three
     * letter language codes.
     */
public void Test4147317() {
    // Try a three letter language code, and check whether it is
    // returned as is.
    Locale locale = new Locale("aaa", "CCC");
    String result = locale.getISO3Language();
    if (!result.equals("aaa")) {
        errln("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than returning it as is");
    }
    // Try an invalid two letter language code, and check whether it
    // throws a MissingResourceException.
    locale = new Locale("zz", "CCC");
    try {
        result = locale.getISO3Language();
        errln("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than exception");
    } catch (MissingResourceException e) {
    }
}

50. LocaleTest#TestSerialization()

Project: openjdk
File: LocaleTest.java
/**
     * @bug 4110613
     */
public void TestSerialization() throws ClassNotFoundException, OptionalDataException, IOException, StreamCorruptedException {
    ObjectOutputStream ostream;
    ByteArrayOutputStream obstream;
    byte[] bytes = null;
    obstream = new ByteArrayOutputStream();
    ostream = new ObjectOutputStream(obstream);
    Locale test1 = new Locale("zh", "TW", "");
    // fill in the cached hash-code value
    int dummy = test1.hashCode();
    ostream.writeObject(test1);
    bytes = obstream.toByteArray();
    ObjectInputStream istream = new ObjectInputStream(new ByteArrayInputStream(bytes));
    Locale test2 = (Locale) (istream.readObject());
    if (!test1.equals(test2) || test1.hashCode() != test2.hashCode())
        errln("Locale failed to deserialize correctly.");
}

51. LocaleEnhanceTest#testCurrentLocales()

Project: openjdk
File: LocaleEnhanceTest.java
/**
     * 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);
        }
    }
}

52. FailoverTextToSpeech#onConfigurationChanged()

Project: talkback
File: FailoverTextToSpeech.java
/**
     * Handles updating the system locale.
     * <p>
     * Only used on API >= 15 to work around language issues with Google TTS.
     */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
private void onConfigurationChanged(Configuration newConfig) {
    final Locale newLocale = newConfig.locale;
    if (newLocale.equals(mSystemLocale)) {
        return;
    }
    mSystemLocale = newLocale;
    // The system locale changed, which may mean we need to override the
    // current TTS locale.
    ensureSupportedLocale();
}

53. SpringSecurityMessageSourceTests#germanSystemLocaleWithEnglishLocaleContextHolder()

Project: spring-security
File: SpringSecurityMessageSourceTests.java
// SEC-3013
@Test
public void germanSystemLocaleWithEnglishLocaleContextHolder() {
    Locale beforeSystem = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);
    Locale beforeHolder = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.US);
    MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
    assertThat("Access is denied").isEqualTo(msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));
    // Revert to original Locale
    Locale.setDefault(beforeSystem);
    LocaleContextHolder.setLocale(beforeHolder);
}

54. L10nWsTest#fail_when_java_formatted_language_tags()

Project: sonarqube
File: L10nWsTest.java
@Test
public void fail_when_java_formatted_language_tags() throws Exception {
    Locale locale = Locale.PRC;
    userSessionRule.setLocale(locale);
    Locale override = Locale.UK;
    String key1 = "key1";
    when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1));
    when(i18n.message(override, key1, key1)).thenReturn(key1);
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("'en_GB' cannot be parsed as a BCP47 language tag");
    new WsTester(new L10nWs(i18n, server, userSessionRule)).newGetRequest("api/l10n", "index").setParam("locale", "en_GB").execute();
}

55. L10nWsTest#support_BCP47_formatted_language_tags()

Project: sonarqube
File: L10nWsTest.java
@Test
public void support_BCP47_formatted_language_tags() throws Exception {
    Locale locale = Locale.PRC;
    userSessionRule.setLocale(locale);
    Locale override = Locale.UK;
    String key1 = "key1";
    when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1));
    when(i18n.message(override, key1, key1)).thenReturn(key1);
    Result result = new WsTester(new L10nWs(i18n, server, userSessionRule)).newGetRequest("api/l10n", "index").setParam("locale", "en-GB").execute();
    verify(i18n).getPropertyKeys();
    verify(i18n).message(override, key1, key1);
    result.assertJson("{\"key1\":\"key1\"}");
}

56. L10nWsTest#should_override_locale_when_locale_param_is_set()

Project: sonarqube
File: L10nWsTest.java
@Test
public void should_override_locale_when_locale_param_is_set() throws Exception {
    Locale locale = Locale.PRC;
    userSessionRule.setLocale(locale);
    Locale override = Locale.JAPANESE;
    String key1 = "key1";
    String key2 = "key2";
    String key3 = "key3";
    when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1, key2, key3));
    when(i18n.message(override, key1, key1)).thenReturn(key1);
    when(i18n.message(override, key2, key2)).thenReturn(key2);
    when(i18n.message(override, key3, key3)).thenReturn(key3);
    Result result = new WsTester(new L10nWs(i18n, server, userSessionRule)).newGetRequest("api/l10n", "index").setParam("locale", override.toString()).execute();
    verify(i18n).getPropertyKeys();
    verify(i18n).message(override, key1, key1);
    verify(i18n).message(override, key2, key2);
    verify(i18n).message(override, key3, key3);
    result.assertJson("{\"key1\":\"key1\",\"key2\":\"key2\",\"key3\":\"key3\"}");
}

57. Locales#getLanguages()

Project: sis
File: Locales.java
/**
     * Returns the languages of the given locales, without duplicated values.
     * The instances returned by this method have no {@linkplain Locale#getCountry() country}
     * and no {@linkplain Locale#getVariant() variant} information.
     *
     * @param  locales The locales from which to get the languages.
     * @return The languages, without country or variant information.
     */
private static Locale[] getLanguages(final Locale... locales) {
    final Set<String> codes = new LinkedHashSet<String>(hashMapCapacity(locales.length));
    for (final Locale locale : locales) {
        codes.add(locale.getLanguage());
    }
    int i = 0;
    final Locale[] languages = new Locale[codes.size()];
    for (final String code : codes) {
        languages[i++] = unique(new Locale(code));
    }
    return languages;
}

58. LocaleUtils#getLocale()

Project: shopizer
File: LocaleUtils.java
/**
	 * Creates a Locale object for currency format only with country code
	 * This method ignoes the language
	 * @param store
	 * @return
	 */
public static Locale getLocale(MerchantStore store) {
    Locale defaultLocale = com.salesmanager.core.constants.Constants.DEFAULT_LOCALE;
    Locale[] locales = Locale.getAvailableLocales();
    for (int i = 0; i < locales.length; i++) {
        Locale l = locales[i];
        try {
            if (l.getISO3Country().equals(store.getCurrency().getCode())) {
                defaultLocale = l;
                break;
            }
        } catch (Exception e) {
            LOGGER.error("An error occured while getting ISO code for locale " + l.toString());
        }
    }
    return defaultLocale;
}

59. SerenityPreferenceActivity#populateAvailableLocales()

Project: serenity-android
File: SerenityPreferenceActivity.java
protected void populateAvailableLocales() {
    Locale[] locales = Locale.getAvailableLocales();
    ListPreference preferenceLocales = (ListPreference) findPreference("preferred_subtitle_language");
    ArrayList<String> localNames = new ArrayList<String>();
    ArrayList<String> localCodes = new ArrayList<String>();
    for (Locale local : locales) {
        if (!localNames.contains(local.getDisplayLanguage())) {
            localNames.add(local.getDisplayLanguage());
            localCodes.add(local.getISO3Language());
        }
    }
    String entries[] = new String[localNames.size()];
    String values[] = new String[localCodes.size()];
    localNames.toArray(entries);
    localCodes.toArray(values);
    preferenceLocales.setEntries(entries);
    preferenceLocales.setEntryValues(values);
}

60. BasePortalHandler#addLocale()

Project: sakai
File: BasePortalHandler.java
protected void addLocale(PortalRenderContext rcontext, Site site, String userId) {
    Locale prevLocale = null;
    ResourceLoader rl = new ResourceLoader();
    if (userId != null) {
        prevLocale = rl.getLocale();
    }
    Locale locale = setSiteLanguage(site);
    if (log.isDebugEnabled()) {
        log.debug("Locale for site " + site.getId() + " = " + locale.toString());
    }
    String localeString = locale.getLanguage();
    String country = locale.getCountry();
    if (country.length() > 0)
        localeString += "-" + country;
    rcontext.put("locale", localeString);
    rcontext.put("dir", rl.getOrientation(locale));
    if (prevLocale != null && !prevLocale.equals(locale)) {
        // if the locale was changed, clear the date/time format which was cached in the previous locale
        timeService.clearLocalTimeZone(userId);
    }
}

61. MessageBundleTest#beforeTransaction()

Project: sakai
File: MessageBundleTest.java
@BeforeTransaction
public void beforeTransaction() {
    localeEn = new Locale("en");
    localeFr = new Locale("fr");
    baseName = "basename";
    moduleName = "modulename";
    messageBundleService = new MessageBundleServiceImpl();
    messageBundleService.setScheduleSaves(false);
    messageBundleService.setSessionFactory((SessionFactory) applicationContext.getBean("sessionFactory"));
    Assert.notNull(messageBundleService);
    resourceBundleEN = ResourceBundle.getBundle("org/sakaiproject/messagebundle/impl/test/bundle", localeEn);
    resourceBundleFr = ResourceBundle.getBundle("org/sakaiproject/messagebundle/impl/test/bundle", localeFr);
    messageBundleService.saveOrUpdate(baseName, moduleName, resourceBundleEN, localeEn);
    messageBundleService.saveOrUpdate(baseName, moduleName, resourceBundleFr, localeFr);
}

62. Solr4QueryParser#buildTextMLTextOrContentRange()

Project: community-edition
File: Solr4QueryParser.java
private Query buildTextMLTextOrContentRange(String field, String part1, String part2, boolean includeLower, boolean includeUpper, AnalysisMode analysisMode, String expandedFieldName, PropertyDefinition propertyDef, IndexTokenisationMode tokenisationMode) throws ParseException {
    BooleanQuery booleanQuery = new BooleanQuery();
    List<Locale> locales = searchParameters.getLocales();
    List<Locale> expandedLocales = new ArrayList<Locale>();
    for (Locale locale : (((locales == null) || (locales.size() == 0)) ? Collections.singletonList(I18NUtil.getLocale()) : locales)) {
        expandedLocales.addAll(MLAnalysisMode.getLocales(mlAnalysisMode, locale, false));
    }
    for (Locale locale : (((expandedLocales == null) || (expandedLocales.size() == 0)) ? Collections.singletonList(I18NUtil.getLocale()) : expandedLocales)) {
        try {
            addTextRange(field, propertyDef, part1, part2, includeLower, includeUpper, analysisMode, expandedFieldName, propertyDef, tokenisationMode, booleanQuery, locale);
        } catch (IOException e) {
            throw new ParseException("Failed to tokenise: <" + part1 + "> or <" + part2 + ">   for " + propertyDef.getName());
        }
    }
    return booleanQuery;
}

63. MultilingualContentServiceImpl#isPivotTranslation()

Project: community-edition
File: MultilingualContentServiceImpl.java
private boolean isPivotTranslation(NodeRef contentNodeRef) {
    Locale locale = (Locale) nodeService.getProperty(contentNodeRef, ContentModel.PROP_LOCALE);
    // Get the container
    NodeRef containerNodeRef = getOrCreateMLContainer(contentNodeRef, false);
    Locale containerLocale = (Locale) nodeService.getProperty(containerNodeRef, ContentModel.PROP_LOCALE);
    boolean isPivot = EqualsHelper.nullSafeEquals(locale, containerLocale);
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Node " + (isPivot ? "is" : "is not") + " pivot: " + contentNodeRef);
    }
    return isPivot;
}

64. CronTabDayOfWeekLocaleTest#parameters()

Project: hudson
File: CronTabDayOfWeekLocaleTest.java
@Parameters
public static Collection<Object[]> parameters() {
    final Locale[] locales = Locale.getAvailableLocales();
    final Collection<Object[]> parameters = new ArrayList<Object[]>();
    for (final Locale locale : locales) {
        final Calendar cal = Calendar.getInstance(locale);
        if (GregorianCalendar.class.equals(cal.getClass())) {
            parameters.add(new Object[] { locale });
        }
    }
    return parameters;
}

65. RawData#createCCodes()

Project: HiBench
File: RawData.java
public static void createCCodes(Path hdfs_ccode) throws IOException {
    Utils.checkHdfsPath(hdfs_ccode);
    FileSystem fs = hdfs_ccode.getFileSystem(new Configuration());
    FSDataOutputStream fout = fs.create(hdfs_ccode);
    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) {
        String country = null, language = null;
        try {
            country = locale.getISO3Country();
            language = locale.getLanguage().toUpperCase();
        } catch (Exception e) {
            continue;
        }
        if (!"".equals(country) && !"".equals(language)) {
            String ccode = country + "," + country + "-" + language + "\n";
            fout.write(ccode.getBytes("UTF-8"));
        }
    }
    fout.close();
}

66. BaseDateTimeTypeDstu3Test#beforeClass()

Project: hapi-fhir
File: BaseDateTimeTypeDstu3Test.java
@BeforeClass
public static void beforeClass() {
    /*
		 * We cache the default locale, but temporarily set it to a random value during this test. This helps ensure
		 * that there are no language specific dependencies in the test.
		 */
    ourDefaultLocale = Locale.getDefault();
    Locale[] available = { Locale.CANADA, Locale.GERMANY, Locale.TAIWAN };
    Locale newLocale = available[(int) (Math.random() * available.length)];
    Locale.setDefault(newLocale);
    ourLog.info("Tests are running in locale: " + newLocale.getDisplayName());
}

67. BaseDateTimeDtDstu2Test#beforeClass()

Project: hapi-fhir
File: BaseDateTimeDtDstu2Test.java
@BeforeClass
public static void beforeClass() {
    /*
		 * We cache the default locale, but temporarily set it to a random value during this test. This helps ensure that there are no language specific dependencies in the test.
		 */
    ourDefaultLocale = Locale.getDefault();
    Locale[] available = { Locale.CANADA, Locale.GERMANY, Locale.TAIWAN };
    Locale newLocale = available[(int) (Math.random() * available.length)];
    Locale.setDefault(newLocale);
    ourLog.info("Tests are running in locale: " + newLocale.getDisplayName());
}

68. Collations#eval()

Project: exist
File: Collations.java
/* (non-Javadoc)
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final ValueSequence result = new ValueSequence();
    final Locale[] locales = Collator.getAvailableLocales();
    for (Locale locale : locales) {
        String language = locale.getLanguage();
        if (locale.getCountry().length() > 0) {
            language += '-' + locale.getCountry();
        }
        result.add(new StringValue(language));
    }
    return result;
}

69. WebApplication#getContextLocale()

Project: empire-db
File: WebApplication.java
/**
     * returns the active locale for a given FacesContext
     */
public Locale getContextLocale(final FacesContext ctx) {
    UIViewRoot root;
    // Start out with the default locale
    Locale locale;
    Locale defaultLocale = Locale.getDefault();
    locale = defaultLocale;
    // See if this FacesContext has a ViewRoot
    if (null != (root = ctx.getViewRoot())) {
        // If so, ask it for its Locale
        if (null == (locale = root.getLocale())) {
            // If the ViewRoot has no Locale, fall back to the default.
            locale = defaultLocale;
        }
    }
    return locale;
}

70. LocaleSelectorControl#onLanguageChange()

Project: dbeaver
File: LocaleSelectorControl.java
private void onLanguageChange(String defCountry) {
    String language = getIsoCode(languageCombo.getText());
    Locale[] locales = Locale.getAvailableLocales();
    countryCombo.removeAll();
    Set<String> countries = new TreeSet<>();
    for (Locale locale : locales) {
        if (language.equals(locale.getLanguage()) && !CommonUtils.isEmpty(locale.getCountry())) {
            //$NON-NLS-1$
            countries.add(locale.getCountry() + " - " + locale.getDisplayCountry());
        }
    }
    for (String country : countries) {
        countryCombo.add(country);
        if (defCountry != null && defCountry.equals(getIsoCode(country))) {
            countryCombo.select(countryCombo.getItemCount() - 1);
        }
    }
    if (defCountry == null && countryCombo.getItemCount() > 0) {
        countryCombo.select(0);
    }
}

71. Bug4429024#getCountry()

Project: jdk7u-jdk
File: Bug4429024.java
static int getCountry(String inCountry, String localizedName) {
    Locale fiLocale = new Locale("fi", "FI");
    Locale inLocale = new Locale("", inCountry);
    if (!inLocale.getDisplayCountry(fiLocale).equals(localizedName)) {
        System.out.println("Country " + inCountry + " should be \"" + localizedName + "\", not \"" + inLocale.getDisplayCountry(fiLocale) + "\"");
        return 1;
    } else {
        return 0;
    }
}

72. Bug4429024#getLanguage()

Project: jdk7u-jdk
File: Bug4429024.java
static int getLanguage(String inLang, String localizedName) {
    Locale fiLocale = new Locale("fi", "FI");
    Locale inLocale = new Locale(inLang, "");
    if (!inLocale.getDisplayLanguage(fiLocale).equals(localizedName)) {
        System.out.println("Language " + inLang + " should be \"" + localizedName + "\", not \"" + inLocale.getDisplayLanguage(fiLocale) + "\"");
        return 1;
    } else {
        return 0;
    }
}

73. LocaleTest#Test4147317()

Project: jdk7u-jdk
File: LocaleTest.java
/**
     * @bug 4147317 4940539
     * java.util.Locale.getISO3Language() works wrong for non ISO-639 codes.
     * Should throw an exception for unknown locales, except they have three
     * letter language codes.
     */
public void Test4147317() {
    // Try a three letter language code, and check whether it is
    // returned as is.
    Locale locale = new Locale("aaa", "CCC");
    String result = locale.getISO3Language();
    if (!result.equals("aaa")) {
        errln("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than returning it as is");
    }
    // Try an invalid two letter language code, and check whether it
    // throws a MissingResourceException.
    locale = new Locale("zz", "CCC");
    try {
        result = locale.getISO3Language();
        errln("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than exception");
    } catch (MissingResourceException e) {
    }
}

74. LocaleTest#TestSerialization()

Project: jdk7u-jdk
File: LocaleTest.java
/**
     * @bug 4110613
     */
public void TestSerialization() throws ClassNotFoundException, OptionalDataException, IOException, StreamCorruptedException {
    ObjectOutputStream ostream;
    ByteArrayOutputStream obstream;
    byte[] bytes = null;
    obstream = new ByteArrayOutputStream();
    ostream = new ObjectOutputStream(obstream);
    Locale test1 = new Locale("zh", "TW", "");
    // fill in the cached hash-code value
    int dummy = test1.hashCode();
    ostream.writeObject(test1);
    bytes = obstream.toByteArray();
    ObjectInputStream istream = new ObjectInputStream(new ByteArrayInputStream(bytes));
    Locale test2 = (Locale) (istream.readObject());
    if (!test1.equals(test2) || test1.hashCode() != test2.hashCode())
        errln("Locale failed to deserialize correctly.");
}

75. LocaleEnhanceTest#testCurrentLocales()

Project: jdk7u-jdk
File: LocaleEnhanceTest.java
/**
     * 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);
        }
    }
}

76. AboutLocale#localizedOutputOfDates()

Project: java-koans
File: AboutLocale.java
@Koan
public void localizedOutputOfDates() {
    Calendar cal = Calendar.getInstance();
    cal.set(2011, 3, 3);
    Date date = cal.getTime();
    // portuguese, Brazil
    Locale localeBR = new Locale("pt", "BR");
    DateFormat dateformatBR = DateFormat.getDateInstance(DateFormat.FULL, localeBR);
    assertEquals(dateformatBR.format(date), __);
    // Japan
    Locale localeJA = new Locale("ja");
    DateFormat dateformatJA = DateFormat.getDateInstance(DateFormat.FULL, localeJA);
    // Well if you don't know how to type these characters, try "de", "it" or "us" ;-)
    assertEquals(dateformatJA.format(date), __);
}

77. LocaleTest#test_setDefaultLjava_util_Locale()

Project: j2objc
File: LocaleTest.java
/**
	 * @tests java.util.Locale#setDefault(java.util.Locale)
	 */
public void test_setDefaultLjava_util_Locale() {
    // Test for method void java.util.Locale.setDefault(java.util.Locale)
    Locale org = Locale.getDefault();
    Locale.setDefault(l);
    Locale x = Locale.getDefault();
    Locale.setDefault(org);
    assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString());
    // iOS doesn't have Turkish case tables by default, use German
    // since it has a case where "".toUpper() is "SS", and 
    // "SS".toLower() is "ss".
    Locale.setDefault(new Locale("de", ""));
    String res1 = "ß".toUpperCase();
    String res2 = "SS".toLowerCase();
    Locale.setDefault(org);
    assertEquals("Wrong toUppercase conversion", "SS", res1);
    assertEquals("Wrong toLowercase conversion", "ss", res2);
}

78. SimpleDateFormatTest#testFormattingUncommonTimeZoneAbbreviations()

Project: j2objc
File: SimpleDateFormatTest.java
// In Honeycomb, only one Olson id was associated with CET (or any other "uncommon"
// abbreviation). This was changed after KitKat to avoid Java hacks on top of ICU data.
// ICU data only provides abbreviations for timezones in the locales where they would
// not be ambiguous to most people of that locale.
public void testFormattingUncommonTimeZoneAbbreviations() {
    String fmt = "yyyy-MM-dd HH:mm:ss.SSS z";
    String unambiguousDate = "1970-01-01 01:00:00.000 CET";
    String ambiguousDate = "1970-01-01 01:00:00.000 GMT+1";
    // The locale to use when formatting. Not every Locale renders "Europe/Berlin" as "CET". The
    // UK is one that does, the US is one that does not.
    Locale cetUnambiguousLocale = Locale.UK;
    Locale cetAmbiguousLocale = Locale.US;
    SimpleDateFormat sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
    assertEquals(unambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
    assertEquals(unambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
    assertEquals(ambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
    assertEquals(ambiguousDate, sdf.format(new Date(0)));
}

79. FastDatePrinterTest#testShortDateStyleWithLocales()

Project: commons-lang
File: FastDatePrinterTest.java
/**
     * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
     */
@Test
public void testShortDateStyleWithLocales() {
    final Locale usLocale = Locale.US;
    final Locale swedishLocale = new Locale("sv", "SE");
    final Calendar cal = Calendar.getInstance();
    cal.set(2004, Calendar.FEBRUARY, 3);
    DatePrinter fdf = getDateInstance(FastDateFormat.SHORT, usLocale);
    assertEquals("2/3/04", fdf.format(cal));
    fdf = getDateInstance(FastDateFormat.SHORT, swedishLocale);
    assertEquals("2004-02-03", fdf.format(cal));
}

80. CountryUtils#getCountries()

Project: codeexamples-android
File: CountryUtils.java
/** Returns a list of countries known by Android */
public static List<String> getCountries() {
    // get available Android locales
    Locale[] locales = Locale.getAvailableLocales();
    // create a list of countries
    ArrayList<String> countries = new ArrayList<String>();
    // iterate through all locales
    for (Locale locale : locales) {
        // get country display name
        String country = locale.getDisplayCountry();
        // add country if display name is not empty
        if (!TextUtils.isEmpty(country)) {
            countries.add(country);
        }
    }
    return countries;
}

81. SeverityLevelTest#testMixedCaseSpacesWithDifferentLocales()

Project: checkstyle
File: SeverityLevelTest.java
@Test
public void testMixedCaseSpacesWithDifferentLocales() {
    final Locale[] differentLocales = { new Locale("TR", "tr") };
    final Locale defaultLocale = Locale.getDefault();
    try {
        for (Locale differentLocale : differentLocales) {
            Locale.setDefault(differentLocale);
            testMixedCaseSpaces();
        }
    } finally {
        Locale.setDefault(defaultLocale);
    }
}

82. ScopeTest#testMixedCaseSpacesWithDifferentLocales()

Project: checkstyle
File: ScopeTest.java
@Test
public void testMixedCaseSpacesWithDifferentLocales() {
    final Locale[] differentLocales = { new Locale("TR", "tr") };
    final Locale defaultLocale = Locale.getDefault();
    try {
        for (Locale differentLocale : differentLocales) {
            Locale.setDefault(differentLocale);
            testMixedCaseSpaces();
        }
    } finally {
        Locale.setDefault(defaultLocale);
    }
}

83. UtilTest#testParseLocale()

Project: calcite
File: UtilTest.java
/**
   * Unit test for {@link Util#parseLocale(String)} method.
   */
@Test
public void testParseLocale() {
    Locale[] locales = { Locale.CANADA, Locale.CANADA_FRENCH, Locale.getDefault(), Locale.US, Locale.TRADITIONAL_CHINESE };
    for (Locale locale : locales) {
        assertEquals(locale, Util.parseLocale(locale.toString()));
    }
    // Example locale names in Locale.toString() javadoc.
    String[] localeNames = { "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC" };
    for (String localeName : localeNames) {
        assertEquals(localeName, Util.parseLocale(localeName).toString());
    }
}

84. BookCatalogueActivity#reloadIfLocaleChanged()

Project: Book-Catalogue
File: BookCatalogueActivity.java
/**
     * Reload this activity if locale has changed.
     */
public void reloadIfLocaleChanged() {
    Locale old = mLastLocale;
    Locale curr = BookCatalogueApp.getPreferredLocale();
    if ((curr != null && !curr.equals(old)) || (curr == null && old != null)) {
        mLastLocale = curr;
        BookCatalogueApp.applyPreferredLocaleIfNecessary(this.getResources());
        Intent intent = getIntent();
        System.out.println("Restarting " + this.getClass().getSimpleName());
        finish();
        startActivity(intent);
    }
}

85. SOAPFaultTest#testSetFaultStringLocale()

Project: axis2-java
File: SOAPFaultTest.java
@Validated
@Test
public void testSetFaultStringLocale() throws Exception {
    MessageFactory fac = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    //MessageFactory fac = MessageFactory.newInstance();
    SOAPMessage soapMessage = fac.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPBody body = envelope.getBody();
    SOAPFault sf = body.addFault();
    Locale expected = Locale.ENGLISH;
    sf.setFaultString("this is the fault string", expected);
    Locale result = sf.getFaultStringLocale();
    assertNotNull(result);
    assertTrue(result.equals(expected));
}

86. ReadText#buildAvailableLanguages()

Project: Anki-Android
File: ReadText.java
public static void buildAvailableLanguages() {
    availableTtsLocales.clear();
    Locale[] systemLocales = Locale.getAvailableLocales();
    for (Locale loc : systemLocales) {
        try {
            int retCode = mTts.isLanguageAvailable(loc);
            if (retCode >= TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                availableTtsLocales.add(loc);
            } else {
                Timber.v("ReadText.buildAvailableLanguages() :: %s  not available (error code %d)", loc.getDisplayName(), retCode);
            }
        } catch (IllegalArgumentException e) {
            Timber.e("Error checking if language " + loc.getDisplayName() + " available");
        }
    }
}

87. ParseDateFieldUpdateProcessorFactory#init()

Project: lucene-solr
File: ParseDateFieldUpdateProcessorFactory.java
@Override
public void init(NamedList args) {
    Locale locale = Locale.ROOT;
    String localeParam = (String) args.remove(LOCALE_PARAM);
    if (null != localeParam) {
        locale = LocaleUtils.toLocale(localeParam);
    }
    Object defaultTimeZoneParam = args.remove(DEFAULT_TIME_ZONE_PARAM);
    DateTimeZone defaultTimeZone = DateTimeZone.UTC;
    if (null != defaultTimeZoneParam) {
        defaultTimeZone = DateTimeZone.forID(defaultTimeZoneParam.toString());
    }
    Collection<String> formatsParam = args.removeConfigArgs(FORMATS_PARAM);
    if (null != formatsParam) {
        for (String value : formatsParam) {
            formats.put(value, DateTimeFormat.forPattern(value).withZone(defaultTimeZone).withLocale(locale));
        }
    }
    super.init(args);
}

88. CollationField#createFromLocale()

Project: lucene-solr
File: CollationField.java
/**
   * Create a locale from language, with optional country and variant.
   * Then return the appropriate collator for the locale.
   */
private Collator createFromLocale(String language, String country, String variant) {
    Locale locale;
    if (language != null && country == null && variant != null)
        throw new SolrException(ErrorCode.SERVER_ERROR, "To specify variant, country is required");
    else if (language != null && country != null && variant != null)
        locale = new Locale(language, country, variant);
    else if (language != null && country != null)
        locale = new Locale(language, country);
    else
        locale = new Locale(language);
    return Collator.getInstance(locale);
}

89. TestJdbcDataSourceConvertType#testConvertType()

Project: lucene-solr
File: TestJdbcDataSourceConvertType.java
public void testConvertType() throws Throwable {
    final Locale loc = Locale.getDefault();
    assumeFalse("Derby is not happy with locale sr-Latn-*", Objects.equals(new Locale("sr").getLanguage(), loc.getLanguage()) && Objects.equals("Latn", loc.getScript()));
    // ironically convertType=false causes BigDecimal to String conversion
    convertTypeTest("false", String.class);
    // convertType=true uses the "long" conversion (see mapping of some_i to "long")
    convertTypeTest("true", Long.class);
}

90. TestNLS#testNLSLoading_xx_XX()

Project: lucene-solr
File: TestNLS.java
public void testNLSLoading_xx_XX() {
    Locale locale = new Locale("xx", "XX", "");
    String message = NLS.getLocalizedMessage(MessagesTestBundle.Q0004E_INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION, locale);
    /* 
     * if the default locale is ja, you get ja as a fallback:
     * see ResourceBundle.html#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)
     */
    if (!Locale.getDefault().getLanguage().equals("ja"))
        assertEquals("Truncated unicode escape sequence.", message);
    message = NLS.getLocalizedMessage(MessagesTestBundle.Q0001E_INVALID_SYNTAX, locale, "XXX");
    /* 
     * if the default locale is ja, you get ja as a fallback:
     * see ResourceBundle.html#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)
     */
    if (!Locale.getDefault().getLanguage().equals("ja"))
        assertEquals("Syntax Error: XXX", message);
}

91. TestHtmlParser#testTurkish()

Project: lucene-solr
File: TestHtmlParser.java
// LUCENE-2246
public void testTurkish() throws Exception {
    final Locale saved = Locale.getDefault();
    try {
        Locale.setDefault(new Locale("tr", "TR"));
        String text = "<html><HEAD><TITLE>???</TITLE></head><body>" + "<IMG SRC=\"../images/head.jpg\" WIDTH=570 HEIGHT=47 BORDER=0 ALT=\"?\">" + "<a title=\"(???)\"></body></html>";
        Parser parser = new Parser(new StringReader(text));
        assertEquals("???", parser.title);
        assertEquals("[?]", parser.body);
    } finally {
        Locale.setDefault(saved);
    }
}

92. LocaleManager#getSystemLanguage()

Project: zxingfragmentlib
File: LocaleManager.java
private static String getSystemLanguage() {
    Locale locale = Locale.getDefault();
    if (locale == null) {
        return DEFAULT_LANGUAGE;
    }
    String language = locale.getLanguage();
    // Special case Chinese
    if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(language)) {
        return language + "-r" + getSystemCountry();
    }
    return language;
}

93. DecodeServlet#errorResponse()

Project: zxing
File: DecodeServlet.java
private static void errorResponse(HttpServletRequest request, HttpServletResponse response, String key) throws ServletException, IOException {
    Locale locale = request.getLocale();
    if (locale == null) {
        locale = Locale.ENGLISH;
    }
    ResourceBundle bundle = ResourceBundle.getBundle("Strings", locale);
    String title = bundle.getString("response.error." + key + ".title");
    String text = bundle.getString("response.error." + key + ".text");
    request.setAttribute("title", title);
    request.setAttribute("text", text);
    request.getRequestDispatcher("response.jspx").forward(request, response);
}

94. LocaleManager#getSystemLanguage()

Project: zxing
File: LocaleManager.java
private static String getSystemLanguage() {
    Locale locale = Locale.getDefault();
    if (locale == null) {
        return DEFAULT_LANGUAGE;
    }
    String language = locale.getLanguage();
    // Special case Chinese
    if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(language)) {
        return language + "-r" + getSystemCountry();
    }
    return language;
}

95. VulnerabilitiesLoaderUnitTest#shouldLoadDefaultFileEvenIfFileWithSameLanguageButDifferentCountryIsAvailable()

Project: zaproxy
File: VulnerabilitiesLoaderUnitTest.java
@Test
public void shouldLoadDefaultFileEvenIfFileWithSameLanguageButDifferentCountryIsAvailable() {
    // Given
    Locale.setDefault(new Locale("nl", "XX"));
    Locale locale = new Locale.Builder().setLanguage("nl").setRegion("XX").build();
    loader = new VulnerabilitiesLoader(DIRECTORY, FILE_NAME, FILE_EXTENSION);
    // When
    List<Vulnerability> vulnerabilities = loader.load(locale);
    // Then
    assertThat(vulnerabilities, is(not(empty())));
    assertThat(vulnerabilities.get(0).getAlert(), is(equalTo("Locale default")));
}

96. VulnerabilitiesLoader#load()

Project: zaproxy
File: VulnerabilitiesLoader.java
/**
	 * Returns an unmodifiable {@code List} of {@code Vulnerability}s for the given {@code locale}.
	 * <p>
	 * If there's no perfect match for the given {@code locale} the default will be returned, if available. The list will be
	 * empty if an error occurs.
	 *
	 * @param locale the locale that will {@code Vulnerability}s will be loaded
	 * @return an unmodifiable {@code List} of {@code Vulnerability}s for the given {@code locale}
	 */
public List<Vulnerability> load(Locale locale) {
    List<String> filenames = getListOfVulnerabilitiesFiles();
    for (Locale candidateLocale : getCandidateLocales(locale)) {
        String candidateFilename = createFilename(candidateLocale);
        if (filenames.contains(candidateFilename)) {
            if (logger.isDebugEnabled()) {
                logger.debug("loading vulnerabilities from " + candidateFilename + " for locale " + locale + ".");
            }
            List<Vulnerability> list = loadVulnerabilitiesFile(directory.resolve(candidateFilename));
            if (list == null) {
                return Collections.emptyList();
            }
            return Collections.unmodifiableList(list);
        }
    }
    return Collections.emptyList();
}

97. WPPrefUtils#getLanguageString()

Project: WordPress-Android
File: WPPrefUtils.java
/**
     * Return a non-null display string for a given language code.
     */
public static String getLanguageString(String languageCode, Locale displayLocale) {
    if (languageCode == null || languageCode.length() < 2 || languageCode.length() > 6) {
        return "";
    }
    Locale languageLocale = WPPrefUtils.languageLocale(languageCode);
    String displayLanguage = StringUtils.capitalize(languageLocale.getDisplayLanguage(displayLocale));
    String displayCountry = languageLocale.getDisplayCountry(displayLocale);
    if (!TextUtils.isEmpty(displayCountry)) {
        return displayLanguage + " (" + displayCountry + ")";
    }
    return displayLanguage;
}

98. AppSettingsFragment#updateLanguagePreference()

Project: WordPress-Android
File: AppSettingsFragment.java
private void updateLanguagePreference(String languageCode) {
    if (mLanguagePreference == null || TextUtils.isEmpty(languageCode))
        return;
    Locale languageLocale = WPPrefUtils.languageLocale(languageCode);
    String[] availableLocales = getResources().getStringArray(R.array.available_languages);
    Pair<String[], String[]> pair = WPPrefUtils.createSortedLanguageDisplayStrings(availableLocales, languageLocale);
    // check for a possible NPE
    if (pair == null)
        return;
    String[] sortedEntries = pair.first;
    String[] sortedValues = pair.second;
    mLanguagePreference.setEntries(sortedEntries);
    mLanguagePreference.setEntryValues(sortedValues);
    mLanguagePreference.setDetails(WPPrefUtils.createLanguageDetailDisplayStrings(sortedValues));
    mLanguagePreference.setValue(languageCode);
    mLanguagePreference.setSummary(WPPrefUtils.getLanguageString(languageCode, languageLocale));
    mLanguagePreference.refreshAdapter();
}

99. HttpHeadersMethodsResource#getLanguage()

Project: wink
File: HttpHeadersMethodsResource.java
@POST
@Path("language")
public String getLanguage() {
    Locale l = headersfield.getLanguage();
    StringBuilder sb = new StringBuilder("language:");
    if (l != null) {
        sb.append(l.getLanguage() + ":");
    } else {
        sb.append("null:");
    }
    return sb.toString();
}

100. MainActivity#setLocale()

Project: wigle-wifi-wardriving
File: MainActivity.java
public static void setLocale(final Context context, final Configuration config) {
    final SharedPreferences prefs = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    final String lang = prefs.getString(ListFragment.PREF_LANGUAGE, "");
    final String current = config.locale.getLanguage();
    MainActivity.info("current lang: " + current + " new lang: " + lang);
    Locale newLocale = null;
    if (!"".equals(lang) && !current.equals(lang)) {
        newLocale = new Locale(lang);
    } else if ("".equals(lang) && ORIG_LOCALE != null && !current.equals(ORIG_LOCALE.getLanguage())) {
        newLocale = ORIG_LOCALE;
    }
    if (newLocale != null) {
        Locale.setDefault(newLocale);
        config.locale = newLocale;
        MainActivity.info("setting locale: " + newLocale);
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    }
}