Here are the examples of the java api class java.util.Locale taken from open source projects.
1. LocaleTest#test_toString()
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()
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. Lang#findLocaleDescription()
View licensepublic 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()
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() + "\""); }
5. LocaleTest#TestSimpleObjectStuff()
View licensepublic 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()
View licensepublic 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. LocaleEnhanceTest#testGetDisplayScript()
View licensepublic 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); }
8. NumberUtil#isLanguageSupported()
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; }
9. InterpretConsoleCommandExtension#pickLanguage()
View license/** * 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; }
10. LocaleEnhanceTest#testGetDisplayScript()
View licensepublic 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. 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)); }
12. ContentFilterLanguagesMapTest#testISOCodeConvertions()
View licensepublic 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])); }
13. LocaleTest#languageNamesProvided()
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()
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 licensepublic 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. OnChangeAjaxBehaviorPage#getValue()
View licenseprivate 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(); }
17. ISO8601GregorianCalendarConverter17Test#testCanLoadTimeWithDefaultDifferentLocaleForFormat()
View licensepublic 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); } }
18. 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()); } } }
19. UserLocaleHelper#getCurrentUserLocale()
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; }
20. UserLocaleHelper#getLocales()
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; }
21. LocaleUtilTest#testGetParentLocale()
View license/** * 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()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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()
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)); }
27. CurrencyTest#getsDisplayName()
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"))); }
28. Admin#doGetLocales()
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"); }
29. 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); }
30. 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); } }
31. 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; } }
32. 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); }
33. 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); } }
34. 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), __); }
35. PortletApplicationDefinition362ImplTest#testAddLocaleEncodingMapping()
View license/** * 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()
View license/** * 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()
View license/** * 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()
View license/** * 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()
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); }
40. Lang#findLocaleISO639()
View licensepublic 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()
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()); }
42. Bug4429024#getLanguage()
View licensestatic 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()
View licensestatic 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()
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); }
45. ComparableVersionTest#testLocaleIndependent()
View licensepublic 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()
View licensepublic 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()
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]); }
48. 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; }
49. LocaleTest#Test4147317()
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) { } }
50. LocaleTest#TestSerialization()
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."); }
51. FailoverTextToSpeech#onConfigurationChanged()
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(); }
52. ReadText#buildAvailableLanguages()
View licensepublic 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"); } } }
53. SOAPFaultTest#testSetFaultStringLocale()
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)); }
54. LocaleEnhanceTest#testCurrentLocales()
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); } } }
55. 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); } }
56. UtilTest#testParseLocale()
View license/** * 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()); } }
57. ScopeTest#testMixedCaseSpacesWithDifferentLocales()
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); } }
58. SeverityLevelTest#testMixedCaseSpacesWithDifferentLocales()
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); } }
59. 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; }
60. FastDatePrinterTest#testShortDateStyleWithLocales()
View license/** * 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)); }
61. SimpleDateFormatTest#testFormattingUncommonTimeZoneAbbreviations()
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))); }
62. LocaleTest#test_setDefaultLjava_util_Locale()
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); }
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), __); // 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), __); }
64. LocaleEnhanceTest#testCurrentLocales()
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); } } }
65. LocaleTest#TestSerialization()
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."); }
66. LocaleTest#Test4147317()
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) { } }
67. Bug4429024#getLanguage()
View licensestatic 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; } }
68. Bug4429024#getCountry()
View licensestatic 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; } }
69. LocaleSelectorControl#onLanguageChange()
View licenseprivate 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); } }
70. Collations#eval()
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; }
71. 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()); }
72. 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()); }
73. RawData#createCCodes()
View licensepublic 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(); }
74. 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; }
75. MultilingualContentServiceImpl#isPivotTranslation()
View licenseprivate 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; }
76. Solr4QueryParser#buildTextMLTextOrContentRange()
View licenseprivate 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; }
77. MessageBundleTest#beforeTransaction()
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); }
78. BasePortalHandler#addLocale()
View licenseprotected 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); } }
79. SerenityPreferenceActivity#populateAvailableLocales()
View licenseprotected 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); }
80. LocaleUtils#getLocale()
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; }
81. Locales#getLanguages()
View license/** * 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; }
82. L10nWsTest#should_override_locale_when_locale_param_is_set()
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\"}"); }
83. L10nWsTest#support_BCP47_formatted_language_tags()
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\"}"); }
84. L10nWsTest#fail_when_java_formatted_language_tags()
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(); }
85. 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); }
86. WebApplication#getContextLocale()
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; }
87. MacAddressOptionHandlerTest#testParseFail()
View licensepublic 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); } }
88. PatternOptionHandlerTest#testParseFail()
View licensepublic 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); } }
89. DateUtilities#getDateString()
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; }
90. DateUtilities#getDateStringHideYear()
View license/** * @param context android context * @param date date to format * @return date, with month, day, and year */ @SuppressWarnings("nls") public static String getDateStringHideYear(Context context, Date date) { String month = DateUtils.getMonthString(date.getMonth() + Calendar.JANUARY, DateUtils.LENGTH_MEDIUM); String value; Locale locale = Locale.getDefault(); // united states, you are special if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) value = "'#' d"; else value = "d '#'"; if (date.getYear() != (new Date()).getYear()) { value = value + "\nyyyy"; } if (//$NON-NLS-1$ arrayBinaryContains(locale.getLanguage(), "ja", "zh")) //$NON-NLS-1$ return new SimpleDateFormat(value).format(date).replace("#", month) + "?"; else if (//$NON-NLS-1$ "ko".equals(Locale.getDefault().getLanguage())) //$NON-NLS-1$ return new SimpleDateFormat(value).format(date).replace("#", month) + "?"; else return new SimpleDateFormat(value).format(date).replace("#", month); }
91. SOAPFaultTest#testFaultStringLocale()
View license@Validated @Test public void testFaultStringLocale() 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(); //Setting fault string with no Locale sf.setFaultString("this is the fault string"); Locale result = sf.getFaultStringLocale(); assertNotNull(result); }
92. SOAPFaultTest#testFaultStringLocale2()
View license@Validated @Test public void testFaultStringLocale2() 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(); sf.setFaultString("this is the fault string"); Locale result = sf.getFaultStringLocale(); assertNotNull(result); assertTrue(result.equals(Locale.getDefault())); }
93. LocaleSelectorControl#calculateLocale()
View licenseprivate void calculateLocale() { if (localeChanging) { return; } String language = getIsoCode(languageCombo.getText()); String country = getIsoCode(countryCombo.getText()); String variant = getIsoCode(variantCombo.getText()); currentLocale = new Locale(language, country, variant); localeText.setText(currentLocale.toString()); Event event = new Event(); event.data = currentLocale; super.notifyListeners(SWT.Selection, event); }
94. NumberInlineEditor#createControl()
View license@Override protected Text createControl(Composite editPlaceholder) { final Text editor = new Text(valueController.getEditPlaceholder(), SWT.BORDER); editor.setEditable(!valueController.isReadOnly()); editor.setTextLimit(MAX_NUMBER_LENGTH); Object curValue = valueController.getValue(); Class<?> type = curValue instanceof Number ? curValue.getClass() : valueController.getValueHandler().getValueObjectType(valueController.getValueType()); Locale locale = formatterProfile.getLocale(); if (type == Float.class || type == Double.class || type == BigDecimal.class) { editor.addVerifyListener(UIUtils.getNumberVerifyListener(locale)); } else { editor.addVerifyListener(UIUtils.getIntegerVerifyListener(locale)); } return editor; }
95. DataValueFactoryImpl#verifyCollatorSupport()
View license/** * Verify that JVM has support for the Collator for the database's locale. * * @param strength Collator strength or -1 for locale default. * @return Collator for database's locale * @throws StandardException if JVM does not have support for Collator */ private RuleBasedCollator verifyCollatorSupport(int strength) throws StandardException { Locale[] availLocales = Collator.getAvailableLocales(); //Verify that Collator can be instantiated for the given locale. boolean localeFound = false; for (int i = 0; i < availLocales.length; i++) { if (availLocales[i].equals(databaseLocale)) { localeFound = true; break; } } if (!localeFound) throw StandardException.newException(SQLState.COLLATOR_NOT_FOUND_FOR_LOCALE, databaseLocale.toString()); RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(databaseLocale); if (strength != -1) collator.setStrength(strength); return collator; }
96. BaseMonitor#setLocale()
View licenseprivate static Locale setLocale(Properties properties) throws StandardException { String userDefinedLocale = properties.getProperty(Attribute.TERRITORY); Locale locale; if (userDefinedLocale == null) locale = Locale.getDefault(); else { // validate the passed in string locale = staticGetLocaleFromString(userDefinedLocale); } properties.put(Property.SERVICE_LOCALE, locale.toString()); return locale; }
97. MailService#sendPasswordResetMail()
View license@Async public void sendPasswordResetMail(User user, String baseUrl) { log.debug("Sending password reset e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable("user", user); context.setVariable("baseUrl", baseUrl); String content = templateEngine.process("passwordResetEmail", context); String subject = messageSource.getMessage("email.reset.title", null, locale); // sendEmail(user.getEmail(), subject, content, false, true); sendMailToQueue(user.getEmail(), subject, content, false, true); }
98. EvernoteUtil#generateUserAgentString()
View license/** * Construct a user-agent string based on the running application and * the device and operating system information. This information is * included in HTTP requests made to the Evernote service and assists * in measuring traffic and diagnosing problems. */ public static String generateUserAgentString(Context ctx) { String packageName = null; int packageVersion = 0; try { packageName = ctx.getPackageName(); packageVersion = ctx.getPackageManager().getPackageInfo(packageName, 0).versionCode; } catch (PackageManager.NameNotFoundException e) { CAT.e(e.getMessage()); } String userAgent = packageName + " Android/" + packageVersion; Locale locale = java.util.Locale.getDefault(); if (locale == null) { userAgent += " (" + Locale.US + ");"; } else { userAgent += " (" + locale.toString() + "); "; } userAgent += "Android/" + Build.VERSION.RELEASE + "; "; userAgent += Build.MODEL + "/" + Build.VERSION.SDK_INT + ";"; return userAgent; }
99. MailService#sendActivationEmail()
View license@Async public void sendActivationEmail(User user, String baseUrl) { log.debug("Sending activation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable("user", user); context.setVariable("baseUrl", baseUrl); String content = templateEngine.process("activationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); // sendEmail(user.getEmail(), subject, content, false, true); sendMailToQueue(user.getEmail(), subject, content, false, true); }
100. AbstractSourceTest#createTimestampedLogs()
View licenseprotected void createTimestampedLogs(String sql, int size, String locale, String timezone) throws SQLException { Connection connection = source.getConnectionForWriting(); Locale l = LocaleUtil.toLocale(locale); TimeZone t = TimeZone.getTimeZone(timezone); source.setTimeZone(t).setLocale(l); Calendar cal = Calendar.getInstance(t, l); // half of log in the past, half of it in the future cal.add(Calendar.HOUR, -(size / 2)); for (int i = 0; i < size; i++) { Timestamp modified = new Timestamp(cal.getTimeInMillis()); String message = "Hello world"; add(connection, sql, modified, message); cal.add(Calendar.HOUR, 1); } if (!connection.getAutoCommit()) { connection.commit(); } source.closeWriting(); }