private String compatibleLanguageCode(Locale language) { final ArrayList<Locale> compatibleLanguages = new ArrayList<Locale>(); for (Locale supportedLanguage : supportedLanguages) { try { if (supportedLanguage.getISO3Language().equals(language.getISO3Language())) { compatibleLanguages.add(supportedLanguage); } } catch (MissingResourceException e) { } // No 3-letter language code for locale (as in cmn-Hans-CN), which can be ignored in our // case } if (!compatibleLanguages.isEmpty() && language.getCountry().equals("")) return compatibleLanguages.get(0).getLanguage(); // Not a country specific locale for (Locale compatibleLanguage : compatibleLanguages) { try { if (compatibleLanguage.getISO3Country().equals(language.getISO3Country())) { return compatibleLanguage.getLanguage() + "-" + compatibleLanguage.getCountry().toUpperCase(); } } catch (MissingResourceException e) { } // No 3-letter country code for locale (as in cmn-Hans-CN), which can be ignored in our case } return compatibleLanguages.isEmpty() ? null : compatibleLanguages.get(0).getLanguage(); }
/** * @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) { } }
@Override public String getString(String key, Locale locale) { ResourceBundle bundle = resourceBundles.get(locale.getISO3Language()); if (bundle == null) { try { bundle = ResourceBundle.getBundle(languageBundleName, locale); resourceBundles.put(locale.getISO3Language(), bundle); } catch (MissingResourceException e) { bundle = resourceBundles.get(FALLBACK_LANGUAGE_ISO); } } try { String value = bundle.getString(key); if (LOG.isDebugEnabled()) { LOG.debug( "Key '" + key + "' with ISO " + locale.getISO3Language() + " resulted in value: " + value); } return value; } catch (MissingResourceException e) { return "Missing text for key " + key; } }
public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { if (dataTable[LANG][i].equals("xx")) continue; Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln("Testing " + testLocale + "..."); if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) errln( " ISO-3 language code mismatch: " + testLocale.getISO3Language() + " versus " + dataTable[LANG3][i]); if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) errln( " ISO-3 country code mismatch: " + testLocale.getISO3Country() + " versus " + dataTable[CTRY3][i]); /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) errln(" LCID mismatch: " + testLocale.getLCID() + " versus " + dataTable[LCID][i]); */ } }
public static String get639_1Code(String lang639_2Code) { String[] languages = Locale.getISOLanguages(); Map<String, Locale> localeMap = new HashMap<String, Locale>(languages.length); // Add 639-2/T variants for (String language : languages) { Locale locale = new Locale(language); localeMap.put(locale.getISO3Language(), locale); } // Add 639-2/B variants below this line localeMap.put("alb", new Locale("sq")); localeMap.put("arm", new Locale("hy")); localeMap.put("baq", new Locale("eu")); localeMap.put("bur", new Locale("my")); localeMap.put("chi", new Locale("zh")); localeMap.put("cze", new Locale("cs")); localeMap.put("dut", new Locale("nl")); localeMap.put("fre", new Locale("fr")); localeMap.put("geo", new Locale("ka")); localeMap.put("ger", new Locale("de")); localeMap.put("gre", new Locale("el")); localeMap.put("ice", new Locale("is")); localeMap.put("mac", new Locale("mk")); localeMap.put("mao", new Locale("mi")); localeMap.put("may", new Locale("ms")); localeMap.put("per", new Locale("fa")); localeMap.put("rum", new Locale("ro")); localeMap.put("slo", new Locale("sk")); localeMap.put("tib", new Locale("bo")); localeMap.put("wel", new Locale("cy")); return localeMap.get(lang639_2Code).toString(); }
/** * Checks if specified locale object is valid * * @param locale object for validation * @return true if locale is available */ public static boolean isValid(Locale locale) { try { return locale.getISO3Language() != null && locale.getISO3Country() != null; } catch (MissingResourceException e) { return false; } }
public static void main(final String[] args) { if (args.length >= 2) { final String localeSetting = args[0]; System.out.println("Setting Locale to " + localeSetting + "\n"); Locale.setDefault(new Locale(localeSetting)); final String timezoneSetting = args[1]; System.out.println("Setting TimeZone to " + timezoneSetting + "\n"); TimeZone.setDefault(TimeZone.getTimeZone(timezoneSetting)); } final Locale locale = Locale.getDefault(); System.out.println("Locale"); System.out.println("Code: " + locale.toString()); try { System.out.println("Country: " + locale.getISO3Country()); } catch (final MissingResourceException e) { System.out.println("Country: " + e.getMessage()); } try { System.out.println("Language: " + locale.getISO3Language()); } catch (final MissingResourceException e) { System.out.println("Language: " + e.getMessage()); } System.out.println("\nTimezone"); final TimeZone timezone = TimeZone.getDefault(); System.out.println("Code: " + timezone.getID()); System.out.println("Name: " + timezone.getDisplayName()); System.out.println("Offset: " + timezone.getRawOffset() / (1000 * 60 * 60)); System.out.println("DST: " + timezone.getDSTSavings() / (1000 * 60 * 60)); }
@Inject public DefaultLanguageService(@Named("LanguageBundleName") String languageBundleName) { resourceBundles.put( FALLBACK_LANGUAGE_ISO.getISO3Language(), ResourceBundle.getBundle( languageBundleName, FALLBACK_LANGUAGE_ISO, getClass().getClassLoader(), new ResourceBundleControl())); this.languageBundleName = languageBundleName; }
@Override public TemplateModel get(String key) throws TemplateModelException { final HttpServletRequest request = super.getRequest(); final Locale locale = request.getLocale(); if ("iso3language".equals(key)) { return new SimpleScalar(locale.getISO3Language()); } if ("language".equals(key)) { return new SimpleScalar(locale.getLanguage()); } return null; }
public static boolean setNewLocale(Context context, Locale locale) { Configuration config = context.getResources().getConfiguration(); config.locale = locale; // Locale.setDefault(locale); context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); Log.d("Gibberbot", "locale = " + locale.getDisplayName()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Editor prefEdit = prefs.edit(); prefEdit.putString(ImApp.PREF_DEFAULT_LOCALE, locale.getISO3Language()); prefEdit.commit(); return true; }
/** @bug 4011756 4011380 */ public void TestISO3Fallback() { Locale test = new Locale("xx", "YY", ""); boolean gotException = false; String result = ""; try { result = test.getISO3Language(); } catch (MissingResourceException e) { gotException = true; } if (!gotException) errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); gotException = false; try { result = test.getISO3Country(); } catch (MissingResourceException e) { gotException = true; } if (!gotException) errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); }
public void main(IWContext iwc) throws Exception { // TODO eiki cache countries // some caching made by aron super.main(iwc); // System.out.println( "country dropdown main start "+ // com.idega.util.IWTimestamp.RightNow().toString()); List localeCountries = Arrays.asList(Locale.getISOCountries()); // List locales = Arrays.asList( java.util.Locale.getAvailableLocales()); // List locales = ICLocaleBusiness.listOfAllLocalesJAVA(); Locale currentLocale = iwc.getCurrentLocale(); // Iterator iter = locales.iterator(); Iterator iter = localeCountries.iterator(); Country country = null; String countryDisplayName = null; Map countries = new HashMap(); String lang = currentLocale.getISO3Language(); Locale locale; List smallCountries = new Vector(); // CountryHome countryHome = getAddressBusiness(iwc).getCountryHome(); while (iter.hasNext()) { // Locale locale = (Locale) iter.next(); String ISOCountry = (String) iter.next(); try { locale = new Locale(lang, ISOCountry); countryDisplayName = locale.getDisplayCountry(currentLocale); // country = countryHome.findByIsoAbbreviation(locale.getCountry()); country = getCountryByISO(locale.getCountry()); if (countryDisplayName != null && country != null && !countries.containsKey(country.getPrimaryKey())) { countries.put(country.getPrimaryKey(), country); // cache SmallCountry sCountry = new SmallCountry( (Integer) country.getPrimaryKey(), countryDisplayName, ISOCountry, currentLocale); smallCountries.add(sCountry); // addMenuElement(((Integer)country.getPrimaryKey()).intValue(),countryDisplayName); } } catch (Exception e1) { // e1.printStackTrace(); } } Collections.sort(smallCountries); for (Iterator iterator = smallCountries.iterator(); iterator.hasNext(); ) { SmallCountry sCountry = (SmallCountry) iterator.next(); // we dont want the ISO code into the list if (!sCountry.name.equalsIgnoreCase(sCountry.code)) { addMenuElement(sCountry.getID().intValue(), sCountry.getName()); } } try { if (!StringUtil.isEmpty(this.selectedCountryName)) { this.selectedCountry = getAddressBusiness(iwc).getCountryHome().findByCountryName(this.selectedCountryName); } // we must ensure no external selected country is set else if (this.selectedCountry == null && !StringUtil.isEmpty(currentLocale.getCountry())) { this.selectedCountry = getAddressBusiness(iwc) .getCountryHome() .findByIsoAbbreviation(currentLocale.getCountry()); } } catch (RemoteException e) { e.printStackTrace(); } catch (EJBException e) { e.printStackTrace(); } catch (FinderException e) { e.printStackTrace(); } if (this.selectedCountry != null) { setSelectedElement(((Integer) this.selectedCountry.getPrimaryKey()).intValue()); } // System.out.println( "country dropdown main end "+ // com.idega.util.IWTimestamp.RightNow().toString()); }
@Override protected void onHandleIntent(Intent intent) { final boolean force = intent.getBooleanExtra("force", false); try { Locale loc = Locale.getDefault(); String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; // T-values if present both T and B if (lang == null || lang.length() == 0) { lang = ""; } int serverVersion = intent.getIntExtra("serverVersion", -1); boolean fromPush = serverVersion != -1; JSONObject versionJson = null; if (!fromPush) { versionJson = getVersion(true); serverVersion = versionJson.getInt("version"); } int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1); final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, ""); if (serverVersion <= localVersion && !force && lang.equals(localLanguage) && !LOCAL_DEFINITION_TESTING) { // don't update DebugLog.i("Nothing new, not updating"); return; } // update but don't notify about it. boolean firstLaunchNoUpdate = ((localVersion == -1 && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage)); if (!firstLaunchNoUpdate) { DebugLog.i("There are new definitions available!"); } handleAuthorMessage(versionJson, lang, intent, fromPush); InputStream is = getIS(URL_TICKETS_ID); try { String json = readResult(is); JSONObject o = new JSONObject(json); JSONArray array = o.getJSONArray("tickets"); final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase(); for (int i = 0; i < array.length(); i++) { final JSONObject city = array.getJSONObject(i); try { final ContentValues cv = new ContentValues(); cv.put(Cities._ID, city.getInt("id")); cv.put(Cities.CITY, getStringLocValue(city, lang, "city")); if (city.has("city_pubtran")) { cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran")); } cv.put(Cities.COUNTRY, city.getString("country")); cv.put(Cities.CURRENCY, city.getString("currency")); cv.put(Cities.DATE_FORMAT, city.getString("dateFormat")); cv.put(Cities.IDENTIFICATION, city.getString("identification")); cv.put(Cities.LAT, city.getDouble("lat")); cv.put(Cities.LON, city.getDouble("lon")); cv.put(Cities.NOTE, getStringLocValue(city, lang, "note")); cv.put(Cities.NUMBER, city.getString("number")); cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom")); cv.put(Cities.P_DATE_TO, city.getString("pDateTo")); cv.put(Cities.P_HASH, city.getString("pHash")); cv.put(Cities.PRICE, city.getString("price")); cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote")); cv.put(Cities.REQUEST, city.getString("request")); cv.put(Cities.VALIDITY, city.getInt("validity")); if (city.has("confirmReq")) { cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq")); } if (city.has("confirm")) { cv.put(Cities.CONFIRM, city.getString("confirm")); } final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers"); for (int j = 0; j < additionalNumbers.length() && j < 3; j++) { cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j)); } db.beginTransaction(); int count = db.update( DatabaseHelper.CITY_TABLE_NAME, cv, Cities._ID + " = " + cv.getAsInteger(Cities._ID), null); if (count == 0) { db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv); } db.setTransactionSuccessful(); getContentResolver().notifyChange(Cities.CONTENT_URI, null); } finally { if (db.inTransaction()) { db.endTransaction(); } } } Preferences.set(c, Preferences.DATA_VERSION, serverVersion); Preferences.set(c, Preferences.DATA_LANGUAGE, lang); if (!firstLaunchNoUpdate && !fromPush) { final int finalServerVersion = serverVersion; mHandler.post( new Runnable() { @Override public void run() { Toast.makeText( UpdateService.this, getString(R.string.cities_update_completed, finalServerVersion), Toast.LENGTH_LONG) .show(); } }); } if (LOCAL_DEFINITION_TESTING) { DebugLog.w( "Local definition testing - data updated from assets - must be removed in production!"); } } finally { is.close(); } } catch (IOException e) { DebugLog.e("IOException when calling update: " + e.getMessage(), e); } catch (JSONException e) { DebugLog.e("JSONException when calling update: " + e.getMessage(), e); } }
static String describeLocale(String name) { final StringBuilder result = new StringBuilder(); result.append("<html>"); final Locale locale = localeByName(name); result.append("<p>"); append(result, "Display Name", locale.getDisplayName()); append(result, "Localized Display Name", locale.getDisplayName(locale)); if (locale.getLanguage().length() > 0) { String iso3Language = "(not available)"; try { iso3Language = locale.getISO3Language(); } catch (MissingResourceException ignored) { } result.append("<p>"); append(result, "Display Language", locale.getDisplayLanguage()); append(result, "Localized Display Language", locale.getDisplayLanguage(locale)); append(result, "2-Letter Language Code", locale.getLanguage()); append(result, "3-Letter Language Code", iso3Language); } if (locale.getCountry().length() > 0) { String iso3Country = "(not available)"; try { iso3Country = locale.getISO3Country(); } catch (MissingResourceException ignored) { } result.append("<p>"); append(result, "Display Country", locale.getDisplayCountry()); append(result, "Localized Display Country", locale.getDisplayCountry(locale)); append(result, "2-Letter Country Code", locale.getCountry()); append(result, "3-Letter Country Code", iso3Country); } if (locale.getVariant().length() > 0) { result.append("<p>"); append(result, "Display Variant", locale.getDisplayVariant()); append(result, "Localized Display Variant", locale.getDisplayVariant(locale)); append(result, "Variant Code", locale.getVariant()); } result.append("<p><b>Number Formatting</b>"); describeNumberFormat(result, "Decimal", NumberFormat.getInstance(locale), 1234.5, -1234.5); describeNumberFormat(result, "Integer", NumberFormat.getIntegerInstance(locale), 1234, -1234); describeNumberFormat( result, "Currency", NumberFormat.getCurrencyInstance(locale), 1234.5, -1234.5); describeNumberFormat(result, "Percent", NumberFormat.getPercentInstance(locale), 12.3); boolean hasLocaleData = hasLocaleData(); if (!hasLocaleData) { result.append("<p><b>Decimal Format Symbols</b>"); NumberFormat nf = NumberFormat.getInstance(locale); if (nf instanceof DecimalFormat) { describeDecimalFormatSymbols(result, ((DecimalFormat) nf).getDecimalFormatSymbols()); } else { result.append("(Didn't expect " + nf.getClass() + ".)"); } } Date now = new Date(); // FIXME: it might be more useful to always show a time in the afternoon, to // make 24-hour patterns more obvious. result.append("<p><b>Date/Time Formatting</b>"); describeDateFormat( result, "Full Date", DateFormat.getDateInstance(DateFormat.FULL, locale), now); describeDateFormat( result, "Long Date", DateFormat.getDateInstance(DateFormat.LONG, locale), now); describeDateFormat( result, "Medium Date", DateFormat.getDateInstance(DateFormat.MEDIUM, locale), now); describeDateFormat( result, "Short Date", DateFormat.getDateInstance(DateFormat.SHORT, locale), now); result.append("<p>"); describeDateFormat( result, "Full Time", DateFormat.getTimeInstance(DateFormat.FULL, locale), now); describeDateFormat( result, "Long Time", DateFormat.getTimeInstance(DateFormat.LONG, locale), now); describeDateFormat( result, "Medium Time", DateFormat.getTimeInstance(DateFormat.MEDIUM, locale), now); describeDateFormat( result, "Short Time", DateFormat.getTimeInstance(DateFormat.SHORT, locale), now); result.append("<p>"); describeDateFormat( result, "Full Date/Time", DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locale), now); describeDateFormat( result, "Long Date/Time", DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale), now); describeDateFormat( result, "Medium Date/Time", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale), now); describeDateFormat( result, "Short Date/Time", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale), now); if (!hasLocaleData) { result.append("<p><b>Date Format Symbols</b><p>"); DateFormat edf = DateFormat.getDateInstance(DateFormat.FULL, Locale.US); DateFormatSymbols edfs = ((SimpleDateFormat) edf).getDateFormatSymbols(); DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, locale); DateFormatSymbols dfs = ((SimpleDateFormat) df).getDateFormatSymbols(); append(result, "Local Pattern Chars", dfs.getLocalPatternChars()); append(result, "Am/pm", Arrays.toString(dfs.getAmPmStrings())); append(result, "Eras", Arrays.toString(dfs.getEras())); append(result, "Months", Arrays.toString(dfs.getMonths())); append(result, "Short Months", Arrays.toString(dfs.getShortMonths())); append(result, "Weekdays", Arrays.toString(dfs.getWeekdays())); append(result, "Short Weekdays", Arrays.toString(dfs.getShortWeekdays())); } result.append("<p><b>Calendar</b><p>"); Calendar c = Calendar.getInstance(locale); int firstDayOfWeek = c.getFirstDayOfWeek(); String firstDayOfWeekString = new DateFormatSymbols(locale).getWeekdays()[firstDayOfWeek]; String englishFirstDayOfWeekString = new DateFormatSymbols(Locale.US).getWeekdays()[firstDayOfWeek]; String firstDayOfWeekDetails = firstDayOfWeek + " '" + firstDayOfWeekString + "'"; if (!englishFirstDayOfWeekString.equals(firstDayOfWeekString)) { firstDayOfWeekDetails += " (" + englishFirstDayOfWeekString + ")"; } append(result, "First Day of the Week", firstDayOfWeekDetails); append(result, "Minimal Days in First Week", c.getMinimalDaysInFirstWeek()); // If this locale specifies a country, check out the currency. // Languages don't have currencies; countries do. if (!locale.getCountry().equals("")) { result.append("<p><b>Currency</b><p>"); try { Currency currency = Currency.getInstance(locale); append(result, "ISO 4217 Currency Code", currency.getCurrencyCode()); append( result, "Currency Symbol", unicodeString(currency.getSymbol(locale)) + " (" + currency.getSymbol(Locale.US) + ")"); append(result, "Default Fraction Digits", currency.getDefaultFractionDigits()); } catch (IllegalArgumentException ex) { result.append( "<p>(This version of Android is unable to return a Currency for this Locale.)"); } } result.append("<p><b>Data Availability</b><p>"); appendAvailability(result, locale, "BreakIterator", BreakIterator.class); appendAvailability(result, locale, "Calendar", NumberFormat.class); appendAvailability(result, locale, "Collator", Collator.class); appendAvailability(result, locale, "DateFormat", DateFormat.class); appendAvailability(result, locale, "DateFormatSymbols", DateFormatSymbols.class); appendAvailability(result, locale, "DecimalFormatSymbols", DecimalFormatSymbols.class); appendAvailability(result, locale, "NumberFormat", NumberFormat.class); if (hasLocaleData) { result.append("<p><b>libcore.icu.LocaleData</b>"); try { Object enUsData = getLocaleDataInstance(Locale.US); Object localeData = getLocaleDataInstance(locale); String[] previous; result.append("<p>"); describeStringArray(result, "amPm", enUsData, localeData, null); describeStringArray(result, "eras", enUsData, localeData, null); result.append("<p>"); previous = describeStringArray(result, "longMonthNames", enUsData, localeData, null); describeStringArray(result, "longStandAloneMonthNames", enUsData, localeData, previous); previous = describeStringArray(result, "shortMonthNames", enUsData, localeData, null); describeStringArray(result, "shortStandAloneMonthNames", enUsData, localeData, previous); previous = describeStringArray(result, "tinyMonthNames", enUsData, localeData, null); describeStringArray(result, "tinyStandAloneMonthNames", enUsData, localeData, previous); result.append("<p>"); previous = describeStringArray(result, "longWeekdayNames", enUsData, localeData, null); describeStringArray(result, "longStandAloneWeekdayNames", enUsData, localeData, previous); previous = describeStringArray(result, "shortWeekdayNames", enUsData, localeData, null); describeStringArray(result, "shortStandAloneWeekdayNames", enUsData, localeData, previous); previous = describeStringArray(result, "tinyWeekdayNames", enUsData, localeData, null); describeStringArray(result, "tinyStandAloneWeekdayNames", enUsData, localeData, previous); result.append("<p>"); describeString(result, "yesterday", enUsData, localeData); describeString(result, "today", enUsData, localeData); describeString(result, "tomorrow", enUsData, localeData); result.append("<p>"); describeString(result, "timeFormat12", enUsData, localeData); describeString(result, "timeFormat24", enUsData, localeData); result.append("<p>"); describeChar(result, "zeroDigit", enUsData, localeData); describeChar(result, "decimalSeparator", enUsData, localeData); describeChar(result, "groupingSeparator", enUsData, localeData); describeChar(result, "patternSeparator", enUsData, localeData); describeChar(result, "percent", enUsData, localeData); describeChar(result, "perMill", enUsData, localeData); describeChar(result, "monetarySeparator", enUsData, localeData); describeChar(result, "minusSign", enUsData, localeData); describeString(result, "exponentSeparator", enUsData, localeData); describeString(result, "infinity", enUsData, localeData); describeString(result, "NaN", enUsData, localeData); } catch (Exception ex) { result.append("(" + ex.getClass().getSimpleName() + " thrown: " + ex.getMessage() + ")"); System.err.println(ex); } } return result.toString(); }
/** * @param strLocale * @return return locale match to String * @throws ExpressionException */ public static Locale getLocale(String strLocale) throws ExpressionException { String strLocaleLC = strLocale.toLowerCase().trim(); Locale l = locales.get(strLocaleLC); if (l != null) return l; l = localeAlias.get(strLocaleLC); if (l != null) return l; Matcher matcher = localePattern2.matcher(strLocaleLC); if (matcher.find()) { int len = matcher.groupCount(); if (len == 2) { String lang = matcher.group(1).trim(); String country = matcher.group(2).trim(); Locale locale = new Locale(lang, country); try { locale.getISO3Language(); setLocalAlias(strLocaleLC, locale); return locale; } catch (Exception e) { } } } matcher = localePattern3.matcher(strLocaleLC); if (matcher.find()) { int len = matcher.groupCount(); if (len == 3) { String lang = matcher.group(1).trim(); String country = matcher.group(2).trim(); String variant = matcher.group(3).trim(); Locale locale = new Locale(lang, country, variant); try { locale.getISO3Language(); setLocalAlias(strLocaleLC, locale); return locale; } catch (Exception e) { } } } matcher = localePattern.matcher(strLocaleLC); if (matcher.find()) { int len = matcher.groupCount(); if (len == 3) { String lang = matcher.group(1).trim(); String country = matcher.group(3); if (country != null) country = country.trim(); Object objLocale = null; if (country != null) objLocale = locales.get(lang.toLowerCase() + " (" + (country.toLowerCase()) + ")"); else objLocale = locales.get(lang.toLowerCase()); if (objLocale != null) return (Locale) objLocale; Locale locale; if (country != null) locale = new Locale(lang.toUpperCase(), country.toLowerCase()); else locale = new Locale(lang); try { locale.getISO3Language(); } catch (Exception e) { if (strLocale.indexOf('-') != -1) return getLocale(strLocale.replace('-', '_')); throw new ExpressionException( "unsupported Locale [" + strLocale + "]", "supported Locales are:" + getSupportedLocalesAsString()); } setLocalAlias(strLocaleLC, locale); return locale; } } throw new ExpressionException( "can't cast value (" + strLocale + ") to a Locale", "supported Locales are:" + getSupportedLocalesAsString()); }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String r = sc.getRealPath(""); String path = fc.getInitParameter(request.getRequestURI()); if (path != null && path.equals("nocache")) { chain.doFilter(request, response); return; } path = r + path; String id = request.getRequestURI() + request.getQueryString(); String localeSensitive = fc.getInitParameter("locale-sensitive"); if (localeSensitive != null) { StringWriter ldata = new StringWriter(); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); ldata.write(locale.getISO3Language()); } id = id + ldata.toString(); } File tempDir = (File) sc.getAttribute("javax.servlet.context.tempdir"); String temp = tempDir.getAbsolutePath(); File file = new File(temp + id); if (path == null) { path = sc.getRealPath(request.getRequestURI()); } File current = new File(path); try { long now = Calendar.getInstance().getTimeInMillis(); if (!file.exists() || (file.exists() && current.lastModified() > file.lastModified()) || cacheTimeout < now - file.lastModified()) { String name = file.getAbsolutePath(); name = name.substring(0, name.lastIndexOf("/") == -1 ? 0 : name.lastIndexOf("/")); new File(name).mkdirs(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CacheResponseWrapper wrappedResponse = new CacheResponseWrapper(response, baos); chain.doFilter(req, wrappedResponse); FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } } catch (ServletException e) { if (!file.exists()) { throw new ServletException(e); } } catch (IOException e) { if (!file.exists()) { throw e; } } FileInputStream fis = new FileInputStream(file); String mt = sc.getMimeType(request.getRequestURI()); response.setContentType(mt); ServletOutputStream sos = res.getOutputStream(); for (int i = fis.read(); i != -1; i = fis.read()) { sos.write((byte) i); } }