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
Source File: LocaleTest.java
View license
/**
	 * @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: jdk7u-jdk
Source File: LocaleTest.java
View license
/**
     * @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. LocaleTest#TestChangedISO639Codes()

Project: openjdk
Source File: LocaleTest.java
View license
/**
     * @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() + "\"");
}

4. Lang#findLocaleDescription()

Project: opensearchserver
Source File: Lang.java
View license
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;
}

5. LocaleTest#TestSimpleObjectStuff()

Project: jdk7u-jdk
Source File: LocaleTest.java
View license
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
Source File: LocaleTest.java
View license
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. GenericListAdapterFactoryTest#test_i18n_titles()

View license
@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));
}

8. ContentFilterLanguagesMapTest#testISOCodeConvertions()

View license
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]));
}

9. LocaleEnhanceTest#testGetDisplayScript()

Project: jdk7u-jdk
Source File: LocaleEnhanceTest.java
View license
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);
}

10. LocaleEnhanceTest#testGetDisplayScript()

Project: openjdk
Source File: LocaleEnhanceTest.java
View license
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);
}

11. NumberUtil#isLanguageSupported()

Project: opennlp
Source File: NumberUtil.java
View license
/**
   * 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;
}

12. InterpretConsoleCommandExtension#pickLanguage()

View license
/**
     * Picks the best fit from a set of available languages (given by [email protected] Locale}s).
     * Matching happens in the following priority order:
     * 1st: system's default [email protected] Locale} (e.g. "de-DE"), if contained in [email protected] locales}
     * 2nd: first item in [email protected] locales} matching system default language (e.g. "de" matches "de-CH")
     * 3rd: first language in [email protected] locales}
     * 4th: English, if [email protected] locales} is null or empty
     *
     * @param locales set of supported [email protected] Locale}s to pick from
     * @return [email protected] 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;
}

13. LocaleTest#languageNamesProvided()

Project: teavm
Source File: LocaleTest.java
View license
@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));
}

14. LocaleTest#countryNamesProvided()

Project: teavm
Source File: LocaleTest.java
View license
@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));
}

15. TimeSpanConverterTest#testSpanish()

View license
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));
}

16. ReadText#buildAvailableLanguages()

Project: Anki-Android
Source File: ReadText.java
View license
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");
        }
    }
}

17. SOAPFaultTest#testSetFaultStringLocale()

Project: axis2-java
Source File: SOAPFaultTest.java
View license
@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));
}

18. BookCatalogueActivity#reloadIfLocaleChanged()

View license
/**
     * 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);
    }
}

19. UtilTest#testParseLocale()

Project: calcite
Source File: UtilTest.java
View license
/**
   * Unit test for [email protected] 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());
    }
}

20. ScopeTest#testMixedCaseSpacesWithDifferentLocales()

Project: checkstyle
Source File: ScopeTest.java
View license
@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);
    }
}

21. SeverityLevelTest#testMixedCaseSpacesWithDifferentLocales()

Project: checkstyle
Source File: SeverityLevelTest.java
View license
@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);
    }
}

22. CountryUtils#getCountries()

View license
/** 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;
}

23. FastDatePrinterTest#testShortDateStyleWithLocales()

View license
/**
     * Test case for [email protected] 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));
}

24. MultilingualContentServiceImpl#isPivotTranslation()

View license
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;
}

25. Solr4QueryParser#buildTextMLTextOrContentRange()

View license
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;
}

26. LocaleSelectorControl#onLanguageChange()

Project: dbeaver
Source File: LocaleSelectorControl.java
View license
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);
    }
}

27. WebApplication#getContextLocale()

Project: empire-db
Source File: WebApplication.java
View license
/**
     * 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;
}

28. Collations#eval()

Project: exist
Source File: Collations.java
View license
/* (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;
}

29. BaseDateTimeDtDstu2Test#beforeClass()

View license
@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());
}

30. BaseDateTimeTypeDstu3Test#beforeClass()

View license
@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());
}

31. RawData#createCCodes()

Project: HiBench
Source File: RawData.java
View license
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();
}

32. CronTabDayOfWeekLocaleTest#parameters()

View license
@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;
}

33. SimpleDateFormatTest#testFormattingUncommonTimeZoneAbbreviations()

Project: j2objc
Source File: SimpleDateFormatTest.java
View license
// 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)));
}

34. LocaleTest#test_setDefaultLjava_util_Locale()

Project: j2objc
Source File: LocaleTest.java
View license
/**
	 * @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);
}

35. AboutLocale#localizedOutputOfDates()

Project: java-koans
Source File: AboutLocale.java
View license
@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), __);
}

36. LocaleEnhanceTest#testCurrentLocales()

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

37. LocaleTest#TestSerialization()

Project: jdk7u-jdk
Source File: LocaleTest.java
View license
/**
     * @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.");
}

38. LocaleTest#Test4147317()

Project: jdk7u-jdk
Source File: LocaleTest.java
View license
/**
     * @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) {
    }
}

39. Bug4429024#getLanguage()

Project: jdk7u-jdk
Source File: Bug4429024.java
View license
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;
    }
}

40. Bug4429024#getCountry()

Project: jdk7u-jdk
Source File: Bug4429024.java
View license
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;
    }
}

41. CronTabDayOfWeekLocaleTest#parameters()

View license
@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;
}

42. LocaleUtilTest#testLocaleUtil()

Project: jodd
Source File: LocaleUtilTest.java
View license
@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]);
}

43. StringUtilTestCase#testFormatBytes()

Project: libresonic
Source File: StringUtilTestCase.java
View license
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));
}

44. ComparableVersionTest#testLocaleIndependent()

Project: maven
Source File: ComparableVersionTest.java
View license
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);
    }
}

45. CmsContainerpageService#saveInheritanceGroup()

View license
/**
     * 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);
}

46. CmsVfsSitemapService#ensureSingleLocale()

View license
/**
     * 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);
    }
}

47. CmsVfsBundleManager#addPropertyBundle()

View license
/**
     * 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);
}

48. CmsDynamicFunctionParser#getLocaleToUse()

View license
/**
     * 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;
    }
}

49. CmsXmlContainerPage#getContainerPage()

View license
/**
     * 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);
    }
}

50. CmsXmlContainerPage#writeContainerPage()

View license
/**
     * 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);
}

51. LocaleEnhanceTest#testCurrentLocales()

Project: openjdk
Source File: LocaleEnhanceTest.java
View license
/**
     * 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. LocaleTest#TestSerialization()

Project: openjdk
Source File: LocaleTest.java
View license
/**
     * @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.");
}

53. LocaleTest#Test4147317()

Project: openjdk
Source File: LocaleTest.java
View license
/**
     * @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) {
    }
}

54. Bug4429024#getLanguage()

Project: openjdk
Source File: Bug4429024.java
View license
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;
    }
}

55. Bug4429024#getCountry()

Project: openjdk
Source File: Bug4429024.java
View license
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;
    }
}

56. ConceptTest#getName_shouldReturnExactNameLocaleMatchGivenExactEqualsTrue()

Project: openmrs-core
Source File: ConceptTest.java
View license
/**
	 * @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());
}

57. Lang#findLocaleISO639()

Project: opensearchserver
Source File: Lang.java
View license
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;
}

58. DateUtils#toDate()

Project: PlutusAndroid
Source File: DateUtils.java
View license
/**
     * 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);
}

59. PortletApplicationDefinition286ImplTest#testAddLocaleEncodingMapping()

View license
/**
    * Test method for [email protected] [email protected]nitionImpl#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));
    }
}

60. JSR362PortletAppAnnotationTest#testAddLocaleEncodingMapping()

View license
/**
    * Test method for [email protected] [email protected]nitionImpl#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));
    }
}

61. MergePortletAppTest#testAddLocaleEncodingMapping()

View license
/**
    * Test method for [email protected] [email protected]nitionImpl#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));
    }
}

62. PortletApplicationDefinition362ImplTest#testAddLocaleEncodingMapping()

View license
/**
    * Test method for [email protected] [email protected]nitionImpl#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));
    }
}

63. AboutLocale#localizedOutputOfDates()

View license
@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), __);
}

64. Admin#doGetLocales()

Project: railo
Source File: Admin.java
View license
/**
     * @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");
}

65. MessageBundleTest#beforeTransaction()

Project: sakai
Source File: MessageBundleTest.java
View license
@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);
}

66. BasePortalHandler#addLocale()

Project: sakai
Source File: BasePortalHandler.java
View license
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);
    }
}

67. SerenityPreferenceActivity#populateAvailableLocales()

View license
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);
}

68. LocaleUtils#getLocale()

Project: shopizer
Source File: LocaleUtils.java
View license
/**
	 * 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;
}

69. Locales#getLanguages()

Project: sis
Source File: Locales.java
View license
/**
     * Returns the languages of the given locales, without duplicated values.
     * The instances returned by this method have no [email protected] Locale#getCountry() country}
     * and no [email protected] 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;
}

70. L10nWsTest#should_override_locale_when_locale_param_is_set()

Project: sonarqube
Source File: L10nWsTest.java
View license
@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\"}");
}

71. L10nWsTest#support_BCP47_formatted_language_tags()

Project: sonarqube
Source File: L10nWsTest.java
View license
@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\"}");
}

72. L10nWsTest#fail_when_java_formatted_language_tags()

Project: sonarqube
Source File: L10nWsTest.java
View license
@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();
}

73. SpringSecurityMessageSourceTests#germanSystemLocaleWithEnglishLocaleContextHolder()

View license
// 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);
}

74. FailoverTextToSpeech#onConfigurationChanged()

Project: talkback
Source File: FailoverTextToSpeech.java
View license
/**
     * 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();
}

75. CurrencyTest#getsDisplayName()

Project: teavm
Source File: CurrencyTest.java
View license
@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")));
}

76. CurrencyTest#getsSymbol()

Project: teavm
Source File: CurrencyTest.java
View license
@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));
}

77. CachingLocaleUrlDefinitionDAOTest#setupUrl()

View license
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;
}

78. LocaleUrlDefinitionDAOTest#setupUrl()

View license
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;
}

79. ResolvingLocaleUrlDefinitionDAOTest#setupUrl()

View license
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;
}

80. PostfixedApplicationResource#validateLocale()

View license
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;
}

81. LocaleUtilTest#testGetParentLocale()

Project: tiles-request
Source File: LocaleUtilTest.java
View license
/**
     * Test method for [email protected] 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));
}

82. UserLocaleHelper#getLocales()

Project: uPortal
Source File: UserLocaleHelper.java
View license
/**
	 * 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;
}

83. UserLocaleHelper#getCurrentUserLocale()

Project: uPortal
Source File: UserLocaleHelper.java
View license
/**
	 * 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;
}

84. PackageResourceReferenceTest#userAttributesPreference()

View license
/**
	 * 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());
        }
    }
}

85. OnChangeAjaxBehaviorPage#getValue()

View license
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();
}

86. ISO8601GregorianCalendarConverter17Test#testCanLoadTimeWithDefaultDifferentLocaleForFormat()

View license
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);
    }
}

87. TestDataSize#testNonEnglishLocale()

Project: airlift
Source File: TestDataSize.java
View license
@Test(dataProvider = "printedValues")
public void testNonEnglishLocale(String expectedString, double value, DataSize.Unit unit) {
    Locale previous = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);
    try {
        assertEquals(new DataSize(value, unit).toString(), expectedString);
    } finally {
        Locale.setDefault(previous);
    }
}

88. TestDuration#testNonEnglishLocale()

Project: airlift
Source File: TestDuration.java
View license
@Test(dataProvider = "printedValues")
public void testNonEnglishLocale(String expectedString, double value, TimeUnit unit) throws Exception {
    Locale previous = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);
    try {
        assertEquals(new Duration(value, unit).toString(), expectedString);
    } finally {
        Locale.setDefault(previous);
    }
}

89. TicketController#sendTicketByEmail()

Project: alf.io
Source File: TicketController.java
View license
@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/{ticketIdentifier}/send-ticket-by-email", method = RequestMethod.POST)
public String sendTicketByEmail(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, @PathVariable("ticketIdentifier") String ticketIdentifier, HttpServletRequest request) throws Exception {
    Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager.fetchCompleteAndAssigned(eventName, reservationId, ticketIdentifier);
    if (!oData.isPresent()) {
        return "redirect:/event/" + eventName + "/reservation/" + reservationId;
    }
    Triple<Event, TicketReservation, Ticket> data = oData.get();
    Ticket ticket = data.getRight();
    Event event = data.getLeft();
    Locale locale = LocaleUtil.getTicketLanguage(ticket, request);
    TicketReservation reservation = data.getMiddle();
    notificationManager.sendTicketByEmail(ticket, event, locale, TemplateProcessor.buildPartialEmail(event, organizationRepository, reservation, templateManager, ticketReservationManager.ticketUpdateUrl(reservation.getId(), event, ticket.getUuid()), request), preparePdfTicket(request, event, reservation, ticket));
    return "redirect:/event/" + eventName + "/reservation/" + reservationId + ("ticket".equals(request.getParameter("from")) ? ("/" + ticket.getUuid()) : "/success") + "?ticket-email-sent=true";
}

90. LocaleManager#getSystemLanguage()

Project: android-proxy
Source File: LocaleManager.java
View license
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;
}

91. CalendarPickerViewTest#testFirstDayOfWeekIsMonday()

View license
@Test
public void testFirstDayOfWeekIsMonday() throws Exception {
    Locale greatBritain = new Locale("en", "GB");
    // Verify that firstDayOfWeek is actually Monday.
    Calendar cal = Calendar.getInstance(greatBritain);
    assertThat(cal.getFirstDayOfWeek()).isEqualTo(Calendar.MONDAY);
    view.init(minDate, maxDate, greatBritain);
    MonthView monthView = (MonthView) view.getAdapter().getView(1, null, null);
    CalendarRowView header = (CalendarRowView) monthView.grid.getChildAt(0);
    TextView firstDay = (TextView) header.getChildAt(0);
    // Monday!
    assertThat(firstDay).hasTextString("Mon");
    List<List<MonthCellDescriptor>> cells = getCells(SEPTEMBER, 2013);
    assertThat(cells).hasSize(6);
    assertCell(cells, 0, 0, 26, false, false, false, false, NONE);
    assertCell(cells, 1, 0, 2, true, false, false, true, NONE);
    assertCell(cells, 5, 0, 30, true, false, false, true, NONE);
}

92. LanguageUtil#getLocale()

Project: Anki-Android
Source File: LanguageUtil.java
View license
public static Locale getLocale(String localeCode) {
    Locale locale;
    if (localeCode == null || TextUtils.isEmpty(localeCode)) {
        localeCode = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).getString(Preferences.LANGUAGE, "");
    // If no code provided use the app language.
    }
    if (TextUtils.isEmpty(localeCode)) {
        locale = Locale.getDefault();
    // Fall back to (system) default only if that fails.
    } else if (localeCode.length() > 2) {
        try {
            locale = new Locale(localeCode.substring(0, 2), localeCode.substring(3, 5));
        } catch (StringIndexOutOfBoundsException e) {
            locale = new Locale(localeCode);
        }
    } else {
        locale = new Locale(localeCode);
    }
    return locale;
}

93. ConsolePreparableReporter#prepare()

View license
@Override
public void prepare(MetricRegistry metricsRegistry, Map stormConf) {
    LOG.debug("Preparing...");
    ConsoleReporter.Builder builder = ConsoleReporter.forRegistry(metricsRegistry);
    builder.outputTo(System.out);
    Locale locale = MetricsUtils.getMetricsReporterLocale(stormConf);
    if (locale != null) {
        builder.formattedFor(locale);
    }
    TimeUnit rateUnit = MetricsUtils.getMetricsRateUnit(stormConf);
    if (rateUnit != null) {
        builder.convertRatesTo(rateUnit);
    }
    TimeUnit durationUnit = MetricsUtils.getMetricsDurationUnit(stormConf);
    if (durationUnit != null) {
        builder.convertDurationsTo(durationUnit);
    }
    reporter = builder.build();
}

94. CsvPreparableReporter#prepare()

View license
@Override
public void prepare(MetricRegistry metricsRegistry, Map stormConf) {
    LOG.debug("Preparing...");
    CsvReporter.Builder builder = CsvReporter.forRegistry(metricsRegistry);
    Locale locale = MetricsUtils.getMetricsReporterLocale(stormConf);
    if (locale != null) {
        builder.formatFor(locale);
    }
    TimeUnit rateUnit = MetricsUtils.getMetricsRateUnit(stormConf);
    if (rateUnit != null) {
        builder.convertRatesTo(rateUnit);
    }
    TimeUnit durationUnit = MetricsUtils.getMetricsDurationUnit(stormConf);
    if (durationUnit != null) {
        builder.convertDurationsTo(durationUnit);
    }
    File csvMetricsDir = MetricsUtils.getCsvLogDir(stormConf);
    reporter = builder.build(csvMetricsDir);
}

95. DeviceInfo#getLocale()

View license
public static String getLocale() {
    final String languageTagMethodName = "toLanguageTag";
    Locale defaultLocale = Locale.getDefault();
    try {
        return (String) Locale.class.getMethod(languageTagMethodName).invoke(defaultLocale);
    } catch (Exception e) {
        InternalLogger.INSTANCE.trace("Method '%s' could not be found in Locale class - moving to fallback path.", languageTagMethodName);
    }
    final String localeFileName = "locales.properties";
    Properties localesMap = null;
    try {
        localesMap = PropertyHelper.getProperties(localeFileName);
    } catch (Exception e) {
        InternalLogger.INSTANCE.error("Could not find locale mapping file '%s'", localeFileName);
    }
    String localeString = defaultLocale.toString();
    String localeTag = localesMap != null ? localesMap.getProperty(localeString) : null;
    return localeTag != null ? localeTag : localeString;
}

96. Utils#getLanguageEnv()

Project: AppPlus
Source File: Utils.java
View license
private static String getLanguageEnv() {
    Locale l = Locale.getDefault();
    String language = l.getLanguage();
    String country = l.getCountry().toLowerCase();
    if ("zh".equals(language)) {
        if ("cn".equals(country)) {
            language = "zh-CN";
        } else if ("tw".equals(country)) {
            language = "zh-TW";
        }
    } else if ("pt".equals(language)) {
        if ("br".equals(country)) {
            language = "pt-BR";
        } else if ("pt".equals(country)) {
            language = "pt-PT";
        }
    }
    return language;
}

97. CmdLineExceptionTest#testGetLocalizedMessage()

Project: args4j
Source File: CmdLineExceptionTest.java
View license
/***
     * Test for [email protected] CmdLineException#CmdLineException(org.kohsuke.args4j.CmdLineParser, Localizable, java.lang.String...) }
     * and [email protected] CmdLineException#getLocalizedMessage() }.
     */
public void testGetLocalizedMessage() {
    TestBean testBean = new TestBean();
    Locale cur = Locale.getDefault();
    Locale.setDefault(Locale.GERMANY);
    try {
        CmdLineParser parser = new CmdLineParser(testBean);
        CmdLineException e = new CmdLineException(parser, Messages.NO_ARGUMENT_ALLOWED, "foofoo");
        assertEquals("No argument is allowed: foofoo", e.getMessage());
        assertEquals("Kein Argument erlaubt: foofoo", e.getLocalizedMessage());
        assertSame(parser, e.getParser());
    } catch (Exception e1) {
        Locale.setDefault(cur);
    }
}

98. MacAddressOptionHandlerTest#testParseFail()

View license
public void testParseFail() throws Exception {
    Locale old = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
    TestBean bean = new TestBean();
    CmdLineParser parser = new CmdLineParser(bean);
    try {
        parser.parseArgument("-mac", "00:11:22:33:44:55:ff");
        fail("Expecting exception");
    } catch (CmdLineException e) {
        assertEquals("\"00:11:22:33:44:55:ff\" must be an MAC address", e.getMessage());
    } finally {
        Locale.setDefault(old);
    }
}

99. PatternOptionHandlerTest#testParseFail()

View license
public void testParseFail() throws Exception {
    Locale old = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
    TestBean bean = new TestBean();
    CmdLineParser parser = new CmdLineParser(bean);
    try {
        parser.parseArgument("-pattern", "*");
        fail("Expecting exception");
    } catch (CmdLineException e) {
        assertEquals("\"-pattern\" must be a regular expression", e.getMessage());
    } finally {
        Locale.setDefault(old);
    }
}

100. DateUtilities#getDateString()

Project: astrid
Source File: DateUtilities.java
View license
/**
     * @param context android context
     * @param date date to format
     * @return date, with month, day, and year
     */
@SuppressWarnings("nls")
public static String getDateString(Context context, Date date, boolean includeYear) {
    String month = DateUtils.getMonthString(date.getMonth() + Calendar.JANUARY, DateUtils.LENGTH_MEDIUM);
    String value;
    String standardDate;
    // united states, you are special
    Locale locale = Locale.getDefault();
    if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US"))
        value = "'#' d'$'";
    else
        value = "d'$' '#'";
    if (includeYear)
        value += ", yyyy";
    if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) {
        //$NON-NLS-1$
        standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "?");
    } else if ("ko".equals(Locale.getDefault().getLanguage())) {
        //$NON-NLS-1$
        standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "?");
    } else {
        standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "");
    }
    return standardDate;
}