private List<String> getPath(Locale locale) { List<String> path = resolvingPath.get(locale); if (path == null) { path = new ArrayList<String>(); List<Locale> localePath = LocaleUtils.getPath(locale, getDefaultLocale()); for (Locale loc : localePath) { if (loc == null) { path.add("_"); } else { String language = LocaleUtils.getLanguage(loc); String country = LocaleUtils.getCountry(loc); String variant = LocaleUtils.getVariant(loc); if (!variant.isEmpty()) { path.add(String.format("_%s_%s_%s", language, country, variant)); } else if (!country.isEmpty()) { path.add(String.format("_%s_%s", language, country)); } else if (!language.isEmpty()) { path.add(String.format("_%s", language)); } } } resolvingPath.put(locale, path); } return path; }
public static boolean isExtensionSingleton(String s) { // singleton = DIGIT ; 0 - 9 // / %x41-57 ; A - W // / %x59-5A ; Y - Z // / %x61-77 ; a - w // / %x79-7A ; y - z return (s.length() == 1) && LocaleUtils.isAlphaString(s) && !LocaleUtils.caseIgnoreMatch(PRIVATEUSE, s); }
public static boolean isVariant(String s) { // variant = 5*8alphanum ; registered variants // / (DIGIT 3alphanum) int len = s.length(); if (len >= 5 && len <= 8) { return LocaleUtils.isAlphaNumericString(s); } if (len == 4) { return LocaleUtils.isNumeric(s.charAt(0)) && LocaleUtils.isAlphaNumeric(s.charAt(1)) && LocaleUtils.isAlphaNumeric(s.charAt(2)) && LocaleUtils.isAlphaNumeric(s.charAt(3)); } return false; }
/** Ssets the locale context-wide based on a call to {@link JiveGlobals#getLocale()}. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final String pathInfo = ((HttpServletRequest) request).getPathInfo(); if (pathInfo == null) { // Note, putting the locale in the application at this point is a little overkill // (ie, every user who hits this filter will do this). Eventually, it might make // sense to just set the locale in the user's session and if that's done we might // want to honor a preference to get the user's locale based on request headers. // For now, this is just a convenient place to set the locale globally. Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale()); } else { try { String[] parts = pathInfo.split("/"); String pluginName = parts[1]; ResourceBundle bundle = LocaleUtils.getPluginResourceBundle(pluginName); LocalizationContext ctx = new LocalizationContext(bundle, JiveGlobals.getLocale()); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, ctx); } catch (Exception e) { // Note, putting the locale in the application at this point is a little overkill // (ie, every user who hits this filter will do this). Eventually, it might make // sense to just set the locale in the user's session and if that's done we might // want to honor a preference to get the user's locale based on request headers. // For now, this is just a convenient place to set the locale globally. Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale()); } } // Move along: chain.doFilter(request, response); }
public static ArrayList<DictionaryInfo> getCurrentDictionaryFileNameAndVersionInfo( final Context context) { final ArrayList<DictionaryInfo> dictList = CollectionUtils.newArrayList(); // Retrieve downloaded dictionaries final File[] directoryList = getCachedDirectoryList(context); if (null != directoryList) { for (final File directory : directoryList) { final String localeString = getWordListIdFromFileName(directory.getName()); File[] dicts = BinaryDictionaryGetter.getCachedWordLists(localeString, context); for (final File dict : dicts) { final String wordListId = getWordListIdFromFileName(dict.getName()); if (!DictionaryInfoUtils.isMainWordListId(wordListId)) continue; final Locale locale = LocaleUtils.constructLocaleFromString(localeString); final AssetFileAddress fileAddress = AssetFileAddress.makeFromFile(dict); final DictionaryInfo dictionaryInfo = createDictionaryInfoFromFileAddress(fileAddress); // Protect against cases of a less-specific dictionary being found, like an // en dictionary being used for an en_US locale. In this case, the en dictionary // should be used for en_US but discounted for listing purposes. if (!dictionaryInfo.mLocale.equals(locale)) continue; addOrUpdateDictInfo(dictList, dictionaryInfo); } } } // Retrieve files from assets final Resources resources = context.getResources(); final AssetManager assets = resources.getAssets(); for (final String localeString : assets.getLocales()) { final Locale locale = LocaleUtils.constructLocaleFromString(localeString); final int resourceId = DictionaryInfoUtils.getMainDictionaryResourceIdIfAvailableForLocale( context.getResources(), locale); if (0 == resourceId) continue; final AssetFileAddress fileAddress = BinaryDictionaryGetter.loadFallbackResource(context, resourceId); final DictionaryInfo dictionaryInfo = createDictionaryInfoFromFileAddress(fileAddress); // Protect against cases of a less-specific dictionary being found, like an // en dictionary being used for an en_US locale. In this case, the en dictionary // should be used for en_US but discounted for listing purposes. if (!dictionaryInfo.mLocale.equals(locale)) continue; addOrUpdateDictInfo(dictList, dictionaryInfo); } return dictList; }
public static boolean isLanguage(String s) { // language = 2*3ALPHA ; shortest ISO 639 code // ["-" extlang] ; sometimes followed by // ; extended language subtags // / 4ALPHA ; or reserved for future use // / 5*8ALPHA ; or registered language subtag int len = s.length(); return (len >= 2) && (len <= 8) && LocaleUtils.isAlphaString(s); }
public static String formatCurrency(double amount, String currencyCode) { // I don't know why this is happening but sometimes currencyCode is Kč instead of CZK currencyCode = currencyCode.replace("Kč", "CZK"); Currency currency = Currency.getInstance(currencyCode); String formatted = LocaleUtils.formatCurrency(amount, currency); // hack for Czech crowns - there is no better solution because Android doesn't allow different // settings for // locale and language return formatted.replace("CZK", "CZK ").replace("Kč", "Kč "); }
private static DictionaryInfo createDictionaryInfoFromFileAddress( final AssetFileAddress fileAddress) { final FileHeader header = BinaryDictIOUtils.getDictionaryFileHeaderOrNull( new File(fileAddress.mFilename), fileAddress.mOffset, fileAddress.mLength); final String id = header.getId(); final Locale locale = LocaleUtils.constructLocaleFromString(header.getLocaleString()); final String description = header.getDescription(); final String version = header.getVersion(); return new DictionaryInfo(id, locale, description, fileAddress, Integer.parseInt(version)); }
@Override public void setToolTipText(@Nullable String toolTipTextKey) { if (LocaleUtils.isEmpty(toolTipTextKey)) { toolTipText = null; super.setToolTipText(""); } else { toolTipText = toolTipText == null ? new LocaledString(toolTipTextKey) : toolTipText.setKey(toolTipTextKey); super.setToolTipText(LocaledString.valueOf(toolTipText)); } }
/** * Generate an implementation for the given type. * * @param logger error logger * @param context generator context * @param typeName target type name * @return generated class name * @throws UnableToCompleteException */ @Override public final String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { assert CURRENCY_LIST.equals(typeName); TypeOracle typeOracle = context.getTypeOracle(); PropertyOracle propertyOracle = context.getPropertyOracle(); LocaleUtils localeUtils = LocaleUtils.getInstance(logger, propertyOracle, context); GwtLocale locale = localeUtils.getCompileLocale(); Set<GwtLocale> runtimeLocales = localeUtils.getRuntimeLocales(); JClassType targetClass; try { targetClass = typeOracle.getType(typeName); } catch (NotFoundException e) { logger.log(TreeLogger.ERROR, "No such type", e); throw new UnableToCompleteException(); } if (runtimeLocales.isEmpty()) { return generateLocaleTree(logger, context, targetClass, locale); } CachedGeneratorContext cachedContext = new CachedGeneratorContext(context); return generateRuntimeSelection(logger, cachedContext, targetClass, locale, runtimeLocales); }
/* * BNF in RFC5646 * * Language-Tag = langtag ; normal language tags * / privateuse ; private use tag * / grandfathered ; grandfathered tags * * * langtag = language * ["-" script] * ["-" region] * *("-" variant) * *("-" extension) * ["-" privateuse] * * language = 2*3ALPHA ; shortest ISO 639 code * ["-" extlang] ; sometimes followed by * ; extended language subtags * / 4ALPHA ; or reserved for future use * / 5*8ALPHA ; or registered language subtag * * extlang = 3ALPHA ; selected ISO 639 codes * *2("-" 3ALPHA) ; permanently reserved * * script = 4ALPHA ; ISO 15924 code * * region = 2ALPHA ; ISO 3166-1 code * / 3DIGIT ; UN M.49 code * * variant = 5*8alphanum ; registered variants * / (DIGIT 3alphanum) * * extension = singleton 1*("-" (2*8alphanum)) * * ; Single alphanumerics * ; "x" reserved for private use * singleton = DIGIT ; 0 - 9 * / %x41-57 ; A - W * / %x59-5A ; Y - Z * / %x61-77 ; a - w * / %x79-7A ; y - z * * privateuse = "x" 1*("-" (1*8alphanum)) * */ public static LanguageTag parse(String languageTag, ParseStatus sts) { if (sts == null) { sts = new ParseStatus(); } else { sts.reset(); } StringTokenIterator itr; // Check if the tag is grandfathered String[] gfmap = GRANDFATHERED.get(LocaleUtils.toLowerString(languageTag)); if (gfmap != null) { // use preferred mapping itr = new StringTokenIterator(gfmap[1], SEP); } else { itr = new StringTokenIterator(languageTag, SEP); } LanguageTag tag = new LanguageTag(); // langtag must start with either language or privateuse if (tag.parseLanguage(itr, sts)) { tag.parseExtlangs(itr, sts); tag.parseScript(itr, sts); tag.parseRegion(itr, sts); tag.parseVariants(itr, sts); tag.parseExtensions(itr, sts); } tag.parsePrivateuse(itr, sts); if (!itr.isDone() && !sts.isError()) { String s = itr.current(); sts.errorIndex = itr.currentStart(); if (s.length() == 0) { sts.errorMsg = "Empty subtag"; } else { sts.errorMsg = "Invalid subtag: " + s; } } return tag; }
// Update the current input locale from Locale string. private void updateInputLocale(String inputLocaleStr) { // example: inputLocaleStr = "en_US" "en" "" // "en_US" --> language: en & country: US // "en" --> language: en // "" --> the system locale if (!TextUtils.isEmpty(inputLocaleStr)) { mInputLocale = LocaleUtils.constructLocaleFromString(inputLocaleStr); mInputLocaleStr = inputLocaleStr; } else { mInputLocale = mSystemLocale; String country = mSystemLocale.getCountry(); mInputLocaleStr = mSystemLocale.getLanguage() + (TextUtils.isEmpty(country) ? "" : "_" + mSystemLocale.getLanguage()); } mIsSystemLanguageSameAsInputLanguage = getSystemLocale().getLanguage().equalsIgnoreCase(getInputLocale().getLanguage()); mNeedsToDisplayLanguage = !(getEnabledKeyboardLocaleCount() <= 1 && mIsSystemLanguageSameAsInputLanguage); }
public static boolean isPrivateusePrefixChar(char c) { return (LocaleUtils.caseIgnoreMatch(PRIVATEUSE, String.valueOf(c))); }
@Override public void changeLocale() { setToolTipText(toolTipText); LocaleUtils.localeInnerComponents(this); }
public static boolean isScript(String s) { // script = 4ALPHA ; ISO 15924 code return (s.length() == 4) && LocaleUtils.isAlphaString(s); }
public static String canonicalizePrivateuseSubtag(String s) { return LocaleUtils.toLowerString(s); }
public static boolean isRegion(String s) { // region = 2ALPHA ; ISO 3166-1 code // / 3DIGIT ; UN M.49 code return ((s.length() == 2) && LocaleUtils.isAlphaString(s)) || ((s.length() == 3) && LocaleUtils.isNumericString(s)); }
public static String canonicalizeVariant(String s) { return LocaleUtils.toLowerString(s); }
public static String canonicalizeExtensionSubtag(String s) { return LocaleUtils.toLowerString(s); }
public static String canonicalizeScript(String s) { return LocaleUtils.toTitleString(s); }
public static String canonicalizeRegion(String s) { return LocaleUtils.toUpperString(s); }
public static String canonicalizeExtlang(String s) { return LocaleUtils.toLowerString(s); }
public static boolean isExtensionSubtag(String s) { // extension = singleton 1*("-" (2*8alphanum)) int len = s.length(); return (len >= 2) && (len <= 8) && LocaleUtils.isAlphaNumericString(s); }
public static boolean isKey(String s) { // 2alphanum return (s.length() == 2) && LocaleUtils.isAlphaNumericString(s); }
public User createUser(String username, String password, String name, String email) throws UserAlreadyExistsException { if (isReadOnly()) { // Reject the operation since the provider is read-only throw new UnsupportedOperationException(); } try { loadUser(username); // The user already exists since no exception, so: throw new UserAlreadyExistsException("Username " + username + " already exists"); } catch (UserNotFoundException unfe) { // The user doesn't already exist so we can create a new user // Determine if the password should be stored as plain text or encrypted. boolean usePlainPassword = JiveGlobals.getBooleanProperty("user.usePlainPassword"); String encryptedPassword = null; if (!usePlainPassword) { try { encryptedPassword = AuthFactory.encryptPassword(password); // Set password to null so that it's inserted that way. password = null; } catch (UnsupportedOperationException uoe) { // Encrypting the password may have failed if in setup mode. Therefore, // use the plain password. } } Date now = new Date(); Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_USER); pstmt.setString(1, username); if (password == null) { pstmt.setNull(2, Types.VARCHAR); } else { pstmt.setString(2, password); } if (encryptedPassword == null) { pstmt.setNull(3, Types.VARCHAR); } else { pstmt.setString(3, encryptedPassword); } if (name == null) { pstmt.setNull(4, Types.VARCHAR); } else { pstmt.setString(4, name); } if (email == null) { pstmt.setNull(5, Types.VARCHAR); } else { pstmt.setString(5, email); } pstmt.setString(6, StringUtils.dateToMillis(now)); pstmt.setString(7, StringUtils.dateToMillis(now)); pstmt.execute(); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { DbConnectionManager.closeConnection(pstmt, con); } return new User(username, name, email, now, now); } }
public static boolean isPrivateusePrefix(String s) { // privateuse = "x" 1*("-" (1*8alphanum)) return (s.length() == 1) && LocaleUtils.caseIgnoreMatch(PRIVATEUSE, s); }
public static boolean isSingletonChar(char c) { return (SINGLETON == LocaleUtils.toLower(c)); }
public static boolean isPrivateuseSubtag(String s) { // privateuse = "x" 1*("-" (1*8alphanum)) int len = s.length(); return (len >= 1) && (len <= 8) && LocaleUtils.isAlphaNumericString(s); }
public static boolean isTypeSubtag(String s) { // 3*8alphanum int len = s.length(); return (len >= 3) && (len <= 8) && LocaleUtils.isAlphaNumericString(s); }
static { // grandfathered = irregular ; non-redundant tags registered // / regular ; during the RFC 3066 era // // irregular = "en-GB-oed" ; irregular tags do not match // / "i-ami" ; the 'langtag' production and // / "i-bnn" ; would not otherwise be // / "i-default" ; considered 'well-formed' // / "i-enochian" ; These tags are all valid, // / "i-hak" ; but most are deprecated // / "i-klingon" ; in favor of more modern // / "i-lux" ; subtags or subtag // / "i-mingo" ; combination // / "i-navajo" // / "i-pwn" // / "i-tao" // / "i-tay" // / "i-tsu" // / "sgn-BE-FR" // / "sgn-BE-NL" // / "sgn-CH-DE" // // regular = "art-lojban" ; these tags match the 'langtag' // / "cel-gaulish" ; production, but their subtags // / "no-bok" ; are not extended language // / "no-nyn" ; or variant subtags: their meaning // / "zh-guoyu" ; is defined by their registration // / "zh-hakka" ; and all of these are deprecated // / "zh-min" ; in favor of a more modern // / "zh-min-nan" ; subtag or sequence of subtags // / "zh-xiang" final String[][] entries = { // {"tag", "preferred"}, {"art-lojban", "jbo"}, {"cel-gaulish", "xtg-x-cel-gaulish"}, // fallback {"en-GB-oed", "en-GB-x-oed"}, // fallback {"i-ami", "ami"}, {"i-bnn", "bnn"}, {"i-default", "en-x-i-default"}, // fallback {"i-enochian", "und-x-i-enochian"}, // fallback {"i-hak", "hak"}, {"i-klingon", "tlh"}, {"i-lux", "lb"}, {"i-mingo", "see-x-i-mingo"}, // fallback {"i-navajo", "nv"}, {"i-pwn", "pwn"}, {"i-tao", "tao"}, {"i-tay", "tay"}, {"i-tsu", "tsu"}, {"no-bok", "nb"}, {"no-nyn", "nn"}, {"sgn-BE-FR", "sfb"}, {"sgn-BE-NL", "vgt"}, {"sgn-CH-DE", "sgg"}, {"zh-guoyu", "cmn"}, {"zh-hakka", "hak"}, {"zh-min", "nan-x-zh-min"}, // fallback {"zh-min-nan", "nan"}, {"zh-xiang", "hsn"}, }; for (String[] e : entries) { GRANDFATHERED.put(LocaleUtils.toLowerString(e[0]), e); } }