public List<String> getExternalsWithResolutionOrder(Permutation permutation) { if (permutation == null) { return null; } List<String> result = new ArrayList<String>(4); result.add(permutation.toExternal()); Locale locale = permutation.getLocale(); if (locale != null) { String localeStr = locale.toString(); if (!result.contains(localeStr)) { result.add(localeStr); } if (locale.getVariant() != null && locale.getVariant().length() != 0) { Locale localeWithVar = new Locale(locale.getLanguage(), locale.getCountry()); localeStr = localeWithVar.toString(); if (!result.contains(localeStr)) { result.add(localeStr); } } if (locale.getCountry() != null && locale.getCountry().length() != 0) { Locale localeWithCountry = new Locale(locale.getLanguage()); localeStr = localeWithCountry.toString(); if (!result.contains(localeStr)) { result.add(localeStr); } } } result.add(""); return result; }
/** * Returns any occurrence of the specified Locale or any its fallback in the value collection, or * null if not found. By fallback, we mean will try without variant and country. Example, if * locale is zh_TW, it will try zh_TW and then zh. */ public static Locale getByFallback(Collection<Locale> values, Locale locale) { if (values.contains(locale)) return locale; final String lang = locale.getLanguage(); final String cnty = locale.getCountry(); final String var = locale.getVariant(); if (var != null && var.length() > 0) { locale = new Locale(lang, cnty); if (values.contains(locale)) return locale; } if (cnty != null && cnty.length() > 0) { locale = new Locale(lang, ""); if (values.contains(locale)) return locale; } // search the first one that matches partially Locale rtn = null; for (Locale l : values) { if (l.getLanguage().equals(lang)) { // case 1: it matches all but the last element -> done if (var == null || var.length() == 0 || Objects.equals(l.getCountry(), cnty)) // country might null return l; // case 2: it matches only language, we seeek for any case 1 if (rtn == null) rtn = l; } } return rtn; }
private static Locale _getSuperLocale(Locale locale) { String variant = locale.getVariant(); if (variant.length() > 0) { return new Locale(locale.getLanguage(), locale.getCountry()); } String country = locale.getCountry(); if (country.length() > 0) { Locale priorityLocale = LanguageUtil.getLocale(locale.getLanguage()); if ((priorityLocale != null) && !locale.equals(priorityLocale)) { return new Locale(priorityLocale.getLanguage(), priorityLocale.getCountry()); } return LocaleUtil.fromLanguageId(locale.getLanguage(), false, true); } String language = locale.getLanguage(); if (language.length() > 0) { return _blankLocale; } return null; }
/* * (non-Javadoc) * @see at.alladin.rmbt.db.dao.PrimaryKeyDao#getAll() */ @Override public List<QoSTestTypeDesc> getAll() throws SQLException { List<QoSTestTypeDesc> resultList = new ArrayList<>(); try (PreparedStatement psGetAll = conn.prepareStatement( "SELECT nnttd.uid AS uid, test, nntd.\"value\", nntd.lang, nntd2.\"value\" AS value_name, nntd2.lang AS name_lang " + " FROM qos_test_type_desc AS nnttd " + " JOIN qos_test_desc nntd ON nnttd.test_desc = nntd.desc_key " + " JOIN qos_test_desc nntd2 ON nnttd.test_name = nntd2.desc_key" + " WHERE nntd.lang = (" + " CASE WHEN EXISTS(SELECT 1 FROM qos_test_desc WHERE desc_key = nntd.desc_key AND lang = ?) " + " THEN ? ELSE 'en' END)" + " AND nntd2.lang = (" + " CASE WHEN EXISTS(SELECT 1 FROM qos_test_desc WHERE desc_key = nntd2.desc_key AND lang = ?) " + " THEN ? ELSE 'en' END)")) { psGetAll.setString(1, locale.getLanguage()); psGetAll.setString(2, locale.getLanguage()); psGetAll.setString(3, locale.getLanguage()); psGetAll.setString(4, locale.getLanguage()); if (psGetAll.execute()) { try (ResultSet rs = psGetAll.getResultSet()) { while (rs.next()) { resultList.add(instantiateItem(rs)); } } return resultList; } else { throw new SQLException("no result set"); } } }
public static Locale localeMatch(List<String> requestedLocales, List<Locale> availableLocales) { if (requestedLocales == null || availableLocales == null) { return null; } for (String requestedLocale : requestedLocales) { Locale reqInQuestion = LocaleUtils.toLocale(requestedLocale); List<Locale> lookupList = LocaleUtils.localeLookupList(reqInQuestion); for (Locale localeInQuestion : lookupList) { for (Locale availableLocale : availableLocales) { if (localeInQuestion.equals(availableLocale)) { return availableLocale; } } } for (Locale availableLocale : availableLocales) { if (reqInQuestion.getLanguage().equals(availableLocale.getLanguage())) { return availableLocale; } } } return null; }
private static void assertObsolete(String newCode, String oldCode, String displayName) { // Either code should get you the same locale. Locale newLocale = new Locale(newCode); Locale oldLocale = new Locale(oldCode); assertEquals(newLocale, oldLocale); // No matter what code you used to create the locale, you should get the old code back. assertEquals(oldCode, newLocale.getLanguage()); assertEquals(oldCode, oldLocale.getLanguage()); // Check we get the right display name. assertEquals(displayName, newLocale.getDisplayLanguage(newLocale)); assertEquals(displayName, oldLocale.getDisplayLanguage(newLocale)); assertEquals(displayName, newLocale.getDisplayLanguage(oldLocale)); assertEquals(displayName, oldLocale.getDisplayLanguage(oldLocale)); // Check that none of the 'getAvailableLocales' methods are accidentally returning two // equal locales (because to ICU they're different, but we mangle one into the other). assertOnce(newLocale, BreakIterator.getAvailableLocales()); assertOnce(newLocale, Calendar.getAvailableLocales()); assertOnce(newLocale, Collator.getAvailableLocales()); assertOnce(newLocale, DateFormat.getAvailableLocales()); assertOnce(newLocale, DateFormatSymbols.getAvailableLocales()); assertOnce(newLocale, NumberFormat.getAvailableLocales()); assertOnce(newLocale, Locale.getAvailableLocales()); }
/** This method must be called in a context synchronized on {@link #translationsStatistics}. */ private static LanguageEntry getSortedLanguageByLocale(Locale locale) { for (LanguageEntry entry : sortedLanguages) { if (entry.locale.equals(locale)) { return entry; } } // No exact match found, try to match only by language and country for (LanguageEntry entry : sortedLanguages) { if (entry.locale.getCountry().equals(locale.getCountry()) && entry.locale.getLanguage().equals(locale.getLanguage())) { return entry; } } // No match found on language and country, try to match only by language for (LanguageEntry entry : sortedLanguages) { if (entry.locale.getLanguage().equals(locale.getLanguage())) { return entry; } } // No match found on language, try a last desperate match only by country if (!locale.getCountry().isEmpty()) { for (LanguageEntry entry : sortedLanguages) { if (entry.locale.getCountry().equals(locale.getCountry())) { return entry; } } } // No match found, return null return null; }
public List<Locale> getAvailableLanguages() { Locale[] locales = Locale.getAvailableLocales(); Map<String, Locale> localeMap = new HashMap<String, Locale>(); // remove all variants for (Locale locale : locales) { if (isTranslationsOnly() && !ArrayUtils.contains(config.getAvailableTranslations(), locale.getLanguage())) { continue; } if (localeMap.containsKey(locale.getLanguage()) && locale.getDisplayName().indexOf('(') != -1) { continue; } localeMap.put(locale.getLanguage(), locale); } SortedSet<Locale> localeSet = new TreeSet<Locale>(new LocaleComparator(LocaleComparator.CompareType.LANGUAGE)); for (Locale locale : localeMap.values()) { localeSet.add(locale); } return new ArrayList<Locale>(localeSet); }
/** * @return * @throws SQLException */ public HashMap<TestType, QoSTestTypeDesc> getAllToMap() throws SQLException { HashMap<TestType, QoSTestTypeDesc> resultMap = new HashMap<>(); try (PreparedStatement psGetAll = conn.prepareStatement( "SELECT nnttd.uid AS uid, test, nntd.\"value\", nntd.lang, nntd2.\"value\" AS value_name, nntd2.lang AS name_lang " + " FROM qos_test_type_desc AS nnttd " + " JOIN qos_test_desc nntd ON nnttd.test_desc = nntd.desc_key " + " JOIN qos_test_desc nntd2 ON nnttd.test_name = nntd2.desc_key" + " WHERE nntd.lang = (" + " CASE WHEN EXISTS(SELECT 1 FROM qos_test_desc WHERE desc_key = nntd.desc_key AND lang = ?) " + " THEN ? ELSE 'en' END)" + " AND nntd2.lang = (" + " CASE WHEN EXISTS(SELECT 1 FROM qos_test_desc WHERE desc_key = nntd2.desc_key AND lang = ?) " + " THEN ? ELSE 'en' END)")) { psGetAll.setString(1, locale.getLanguage()); psGetAll.setString(2, locale.getLanguage()); psGetAll.setString(3, locale.getLanguage()); psGetAll.setString(4, locale.getLanguage()); if (psGetAll.execute()) { try (ResultSet rs = psGetAll.getResultSet()) { while (rs.next()) { QoSTestTypeDesc item = instantiateItem(rs); resultMap.put(item.getTestType(), item); } return resultMap; } } else { throw new SQLException("no result set"); } } }
/** * a utility method to answer the name of a resource bundle according to the given base name and * locale * * @param baseName the given base name * @param locale the locale to use * @return the name of a resource bundle according to the given base name and locale */ public String toBundleName(String baseName, Locale locale) { final String emptyString = EMPTY_STRING; final String preString = UNDER_SCORE; final String underline = UNDER_SCORE; if (null == baseName) { throw new NullPointerException(); } StringBuilder ret = new StringBuilder(); StringBuilder prefix = new StringBuilder(); ret.append(baseName); if (!locale.getLanguage().equals(emptyString)) { ret.append(underline); ret.append(locale.getLanguage()); } else { prefix.append(preString); } if (!locale.getCountry().equals(emptyString)) { ret.append((CharSequence) prefix); ret.append(underline); ret.append(locale.getCountry()); prefix = new StringBuilder(); } else { prefix.append(preString); } if (!locale.getVariant().equals(emptyString)) { ret.append((CharSequence) prefix); ret.append(underline); ret.append(locale.getVariant()); } return ret.toString(); }
protected void drawMonthDayLabels(Canvas canvas) { int y = getMonthHeaderSize() - (MONTH_DAY_LABEL_TEXT_SIZE / 2); int dayWidthHalf = (mWidth - mEdgePadding * 2) / (mNumDays * 2); for (int i = 0; i < mNumDays; i++) { int x = (2 * i + 1) * dayWidthHalf + mEdgePadding; int calendarDay = (i + mWeekStart) % mNumDays; mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay); Locale locale = Locale.getDefault(); String localWeekDisplayName = mDayLabelCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale); String weekString = localWeekDisplayName.toUpperCase(locale).substring(0, 1); if (locale.equals(Locale.CHINA) || locale.equals(Locale.CHINESE) || locale.equals(Locale.SIMPLIFIED_CHINESE) || locale.equals(Locale.TRADITIONAL_CHINESE)) { int len = localWeekDisplayName.length(); weekString = localWeekDisplayName.substring(len - 1, len); } if (locale.getLanguage().equals("he") || locale.getLanguage().equals("iw")) { if (mDayLabelCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) { int len = localWeekDisplayName.length(); weekString = localWeekDisplayName.substring(len - 2, len - 1); } else { // I know this is duplication, but it makes the code easier to grok by // having all hebrew code in the same block weekString = localWeekDisplayName.toUpperCase(locale).substring(0, 1); } } canvas.drawText(weekString, x, y, mMonthDayLabelPaint); } }
public String format(String key, String dflt, Object... args) { if (key == null) { return dflt; } if (dflt == null) { dflt = key; } Locale locale = CurrentLocale.get(); // first look for most-specific catalog String message = getCatalogMessage(locale, key); if (message == null) { message = getCatalogMessage(new Locale(locale.getLanguage(), locale.getCountry()), key); } // now look for language if (message == null) { message = getCatalogMessage(new Locale(locale.getLanguage()), key); } // otherwise use the default catalog if (message == null) { message = getCatalogMessage(new Locale(""), key); } // and default to framework if (message == null) { message = getFrameworkMessage(locale, key); } if (message == null) { return dflt; } else { MessageFormat formater = new MessageFormat(message, locale); return formater.format(args, new StringBuffer(), null).toString(); } }
// Compares the specified locale against the supported variants private int _compareLocale(Locale locale) { // If we don't have any locales specified, anything matches if (_locales.isEmpty()) return _LOCALE_UNKNOWN_MATCH; // On the other hand, if the client-locale is not specified, // but we do have a locale specified, there is no match. if (locale == null) return 0; int match = 0; for (Locale tmpLocale : _locales) { if (tmpLocale.getLanguage().equals(locale.getLanguage())) { if (tmpLocale.getCountry().equals(locale.getCountry())) { match = _LOCALE_EXACT_MATCH; break; } // If we've got a partial match, keep looking - we may could find // an exact match match = _LOCALE_PARTIAL_MATCH; } } return match; }
public int a(Locale paramLocale1, Locale paramLocale2) { if (paramLocale1.equals(paramLocale2)) { return 0; } return String.valueOf(paramLocale1.getLanguage()) .compareToIgnoreCase(String.valueOf(paramLocale2.getLanguage())); }
private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/').replace('$', '/') + "/help" + suffix; ClassLoader cl = c.getClassLoader(); if (cl == null) return null; InputStream in; in = cl.getResourceAsStream( base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if (in != null) return in; in = cl.getResourceAsStream( base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if (in != null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if (in != null) return in; // default return cl.getResourceAsStream(base + ".html"); }
/** @param reallyRemoveIt true: really remove it; false: dry run, only produce logging */ public void removeXKeysTask(boolean reallyRemoveIt) { List<String> allBundles = I18nModule.getBundleNamesContainingI18nFiles(); Set<String> allLangs = getAllLanguages(); int counter = 0; for (String langKey : allLangs) { Locale locale = i18nMgr.getLocaleOrNull(langKey); for (String bundleName : allBundles) { Properties properties = i18nMgr.getPropertiesWithoutResolvingRecursively(locale, bundleName); Set<Object> keys = properties.keySet(); for (Object keyObj : keys) { String key = (String) keyObj; if (key.endsWith("X")) { String value = properties.getProperty(key); if (StringHelper.containsNonWhitespace(value)) { log.warn( "NONEMPTY XKEY detected in lang::" + locale.getLanguage() + " bundle::" + bundleName + " key::" + key + " value::" + value); if (reallyRemoveIt) { addKey(locale, bundleName, key.substring(0, key.length() - 1), value); } } log.info( "XKEY detected in lang::" + locale.getLanguage() + " bundle::" + bundleName + " key::" + key); logText.append( i18nMgr.getPropertiesFile( locale, bundleName, I18nModule.getPropertyFilesBaseDir(locale, bundleName)) + " XKEY detected in lang::" + locale.getLanguage() + " bundle::" + bundleName + " key::" + key + " value::" + value + "\n"); if (reallyRemoveIt) { deleteKey(locale, bundleName, key); } counter++; } } } } if (reallyRemoveIt) { log.info(counter + " X-Keys got removed!"); } }
/** * Get the appropriate localized version of a file according to language settings e. g. help files * in jsp/help/ * * @param locale Locale to get the file for * @param fileName String fileName, to get the localized file for * @param fileType String file extension * @return localizedFileName String - localized filename */ private static String getFilename(Locale locale, String fileName, String fileType) { String localizedFileName = null; boolean fileFound = false; // with Language, Country, Variant String fileNameLCV = null; // with Language, Country String fileNameLC = null; // with Language String fileNameL = null; fileNameL = fileName + "_" + locale.getLanguage(); if (fileType == null) { fileType = ""; } if (!("".equals(locale.getCountry()))) { fileNameLC = fileName + "_" + locale.getLanguage() + "_" + locale.getCountry(); if (!("".equals(locale.getVariant()))) { fileNameLCV = fileName + "_" + locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant(); } } if (fileNameLCV != null && !fileFound) { File fileTmp = new File(fileNameLCV + fileType); if (fileTmp.exists()) { fileFound = true; localizedFileName = fileNameLCV + fileType; } } if (fileNameLC != null && !fileFound) { File fileTmp = new File(fileNameLC + fileType); if (fileTmp.exists()) { fileFound = true; localizedFileName = fileNameLC + fileType; } } if (fileNameL != null && !fileFound) { File fileTmp = new File(fileNameL + fileType); if (fileTmp.exists()) { fileFound = true; localizedFileName = fileNameL + fileType; } } if (!fileFound) { localizedFileName = fileName + fileType; } return localizedFileName; }
/** @param reallyRemoveIt true: really remove it; false: dry run, only produce logging */ public void removeTodoKeysTask(boolean reallyRemoveIt) { List<String> allBundles = I18nModule.getBundleNamesContainingI18nFiles(); Set<String> allLangs = getAllLanguages(); int counter = 0; String[] comparisonStrings = {"TODO"}; for (String langKey : allLangs) { Locale locale = i18nMgr.getLocaleOrNull(langKey); for (String bundleName : allBundles) { Properties properties = i18nMgr.getPropertiesWithoutResolvingRecursively(locale, bundleName); Set<Object> keys = properties.keySet(); for (Object keyObj : keys) { String key = (String) keyObj; String value = properties.getProperty(key); for (int i = 0; i < comparisonStrings.length; i++) { int pos = value.toLowerCase().indexOf(comparisonStrings[i].toLowerCase()); if (pos != -1 && pos < 2 && !value.toLowerCase().equals("todos")) { log.info( "TODO-Key detected in lang::" + locale.getLanguage() + " bundle::" + bundleName + " key::" + key + " value::" + value); if (value.length() > comparisonStrings[i].length() + 1) { log.warn( "this is a TODO-Key WITH TEXT::" + value.substring(comparisonStrings[i].length()) + "::"); } else { logText.append( i18nMgr.getPropertiesFile( locale, bundleName, I18nModule.getPropertyFilesBaseDir(locale, bundleName)) + " TODO-Key detected in lang::" + locale.getLanguage() + " bundle::" + bundleName + " key::" + key + " value::" + value + "\n"); if (reallyRemoveIt) { deleteKey(locale, bundleName, key); } } counter++; } } } // each key } // each bundle } log.info(counter + " TODO-Keys got removed!"); }
@Test public void testListAllSerbianCountries() { for (final Locale aLocale : CollectionHelper.getSorted(Locale.getAvailableLocales(), new ComparatorLocale())) if (aLocale.getLanguage().equals("sr") || aLocale.getLanguage().equals("sh") || aLocale.getLanguage().equals("bs")) s_aLogger.info(aLocale.toString() + ": " + aLocale.getDisplayName()); }
private boolean isAvailableLocale(Locale locale) { String language = locale.getLanguage(); for (Locale availableLocale : getAvailableLocales()) { String availableLanguage = availableLocale.getLanguage(); if (language.equals(availableLanguage)) { return true; } } return false; }
private Language parseLocaleToLanguage(Locale locale) { Language language = null; try { language = Language.valueOf(locale.getLanguage().toUpperCase()); } catch (Exception e) { logger.error( "Could not parse " + locale.getLanguage() + " to a language in the Language enum."); } return language; }
/** * Compatible is a looser matching than that provided by Locale.equals(). Two locales are * considered equal if they are equal, or if either does not have a country specified and the * languages match. * * @param lhs left hand side Locale * @param rhs right hand side Locale * @return true if the two locales are compatible, false otherwise * @should confirm different language missing country as compatible * @should confirm same language missing country as compatible * @should not confirm different country as compatible * @should confirm matching country as compatible * @should not confirm different language as compatible * @should confirm matching language as compatible */ public static boolean areCompatible(Locale lhs, Locale rhs) { if (lhs.equals(rhs)) { return true; } else if ((lhs.getCountry() == "") || (rhs.getCountry() == "")) { // no country specified, so language match is good enough if (lhs.getLanguage().equals(rhs.getLanguage())) { return true; } } return false; }
public String toString(final Locale locale) { if (locale == null) { return null; } final String variant = locale.getVariant(); if (StringUtils.isEmpty(variant)) { return locale.getLanguage() + "_" + locale.getCountry(); } else { return locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant(); } }
/** {@inheritDoc} */ @Override public void loadLocale(Locale l) throws NoSuchLocalizationException { messages.remove(l); InputStream resstream = null; InputStream filestream = null; try { filestream = new FileInputStream(new File(plugin.getDataFolder(), l.getLanguage() + ".yml")); } catch (FileNotFoundException e) { } try { resstream = plugin.getResource( new StringBuilder(LOCALIZATION_FOLDER_NAME) .append("/") .append(l.getLanguage()) .append(".yml") .toString()); } catch (Exception e) { } if ((resstream == null) && (filestream == null)) throw new NoSuchLocalizationException(l); messages.put(l, new HashMap<Message, List<String>>(Message.values().length)); FileConfiguration resconfig = (resstream == null) ? null : YamlConfiguration.loadConfiguration(resstream); FileConfiguration fileconfig = (filestream == null) ? null : YamlConfiguration.loadConfiguration(filestream); for (Message m : Message.values()) { List<String> values = m.getDefault(); if (resconfig != null) { if (resconfig.isList(m.toString())) { values = resconfig.getStringList(m.toString()); } else { values.add(resconfig.getString(m.toString(), values.get(0))); } } if (fileconfig != null) { if (fileconfig.isList(m.toString())) { values = fileconfig.getStringList(m.toString()); } else { values.add(fileconfig.getString(m.toString(), values.get(0))); } } messages.get(l).put(m, values); } }
/** * Test for lax Locale equality. More precisely, returns true if (a) both are equal; (b) general * only specifies language, and specific has the same language; (c) general specifies language and * country, and specific has the same language and country. Else returns false. */ public static boolean subsumes(Locale general, Locale specific) { if (general == null || specific == null) return false; if (general.equals(specific)) return true; else if (general.getVariant().equals("")) { if (general.getCountry().equals("")) { if (general.getLanguage().equals(specific.getLanguage())) return true; } else { if (general.getLanguage().equals(specific.getLanguage()) && general.getCountry().equals(specific.getCountry())) return true; } } return false; }
@RequestMapping(value = "/user/changePassword", method = RequestMethod.GET) public String showChangePasswordPage( final Locale locale, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) { final String result = securityUserService.validatePasswordResetToken(id, token); if (result != null) { model.addAttribute("message", messages.getMessage("auth.message." + result, null, locale)); return "redirect:/login?lang=" + locale.getLanguage(); } return "redirect:/updatePassword.html?lang=" + locale.getLanguage(); }
/** * Return the resource file suffic for the indicated locale For most locales, this will be based * the language code. However for Chinese, we do distinguish between Taiwan and PRC * * @param locale the locale * @return an String suffix which canbe appended to a resource name */ private static final String getResourceSuffix(Locale locale) { String lang = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); String suffix = "_" + locale.getLanguage(); if (lang.equals("zh")) suffix += "_" + country; if (country.equals("JP")) suffix += "_" + country + "_" + variant; return suffix; }
/* * Gets the resource bundle with the given base name and preferred locale. * * This method calls java.util.ResourceBundle.getBundle(), but ignores * its return value unless its locale represents an exact or language match * with the given preferred locale. * * @param basename the resource bundle base name * @param pref the preferred locale * * @return the requested resource bundle, or <tt>null</tt> if no resource * bundle with the given base name exists or if there is no exact- or * language-match between the preferred locale and the locale of * the bundle returned by java.util.ResourceBundle.getBundle(). */ private static ResourceBundle findMatch(String basename, Locale pref) { ResourceBundle match = null; try { ResourceBundle bundle = ResourceBundle.getBundle(basename, pref, Thread.currentThread().getContextClassLoader()); Locale avail = bundle.getLocale(); if (pref.equals(avail)) { // Exact match match = bundle; } else { /* * We have to make sure that the match we got is for * the specified locale. The way ResourceBundle.getBundle() * works, if a match is not found with (1) the specified locale, * it tries to match with (2) the current default locale as * returned by Locale.getDefault() or (3) the root resource * bundle (basename). * We must ignore any match that could have worked with (2) or (3). * So if an exact match is not found, we make the following extra * tests: * - avail locale must be equal to preferred locale * - avail country must be empty or equal to preferred country * (the equality match might have failed on the variant) */ if (pref.getLanguage().equals(avail.getLanguage()) && ("".equals(avail.getCountry()) || pref.getCountry().equals(avail.getCountry()))) { /* * Language match. * By making sure the available locale does not have a * country and matches the preferred locale's language, we * rule out "matches" based on the container's default * locale. For example, if the preferred locale is * "en-US", the container's default locale is "en-UK", and * there is a resource bundle (with the requested base * name) available for "en-UK", ResourceBundle.getBundle() * will return it, but even though its language matches * that of the preferred locale, we must ignore it, * because matches based on the container's default locale * are not portable across different containers with * different default locales. */ match = bundle; } } } catch (MissingResourceException mre) { } return match; }
/** * Return the default date pattern for this application.<br> * If the locale is not null then uses the format associated with this specific locale if it * exists * * @param locale a {@link Locale} * @return a String pattern */ public static String getDefaultDatePattern(Locale locale) { if (locale == null) { return getDefaultDatePattern(); } if (Play.application() .configuration() .keys() .contains("maf.default.date.format." + locale.getLanguage())) { return Play.application() .configuration() .getString("maf.default.date.format." + locale.getLanguage()); } return getDefaultDatePattern(); }
public void testLocaleTokenizer() { try { I18NTokenizer tok = new I18NTokenizer(HEADER); Locale locale = (Locale) tok.next(); assertEquals("Either wrong language or order parsing: " + locale, locale.getLanguage(), "en"); locale = (Locale) tok.next(); assertEquals("Either wrong language or order parsing: " + locale, locale.getLanguage(), "es"); locale = (Locale) tok.next(); assertEquals("Either wrong country or order parsing: " + locale, locale.getCountry(), "TW"); } catch (Exception e) { e.printStackTrace(); fail(); } }