Example usage for java.util Locale getLanguage

List of usage examples for java.util Locale getLanguage

Introduction

In this page you can find the example usage for java.util Locale getLanguage.

Prototype

public String getLanguage() 

Source Link

Document

Returns the language code of this Locale.

Usage

From source file:com.parking.billing.ParkingPayment.java

/**
 * Replaces the language and/or country of the device into the given string.
 * The pattern "%lang%" will be replaced by the device's language code and
 * the pattern "%region%" will be replaced with the device's country code.
 *
 * @param str the string to replace the language/country within
 * @return a string containing the local language and region codes
 *///  ww w  . j  a va 2s.c o  m
private String replaceLanguageAndRegion(String str) {
    // Substitute language and or region if present in string
    if (str.contains("%lang%") || str.contains("%region%")) {
        Locale locale = Locale.getDefault();
        str = str.replace("%lang%", locale.getLanguage().toLowerCase());
        str = str.replace("%region%", locale.getCountry().toLowerCase());
    }
    return str;
}

From source file:org.sakaiproject.adminsiteperms.tool.ResourceLoaderMessageSource.java

protected MessageFormat resolveCode(String code, Locale locale) {
    if (locale != null && resourceLoader.getLocale() == null) {
        resourceLoader.setContextLocale(locale);
    } else {/*  ww w .  j  a va  2  s  . c  o  m*/
        locale = resourceLoader.getLocale();
    }
    String msg;
    if ("DEBUG".equals(locale.getVariant()) || "XX".equals(locale.getCountry())) {
        msg = "** " + code + " **";
    } else {
        msg = resourceLoader.getString(code);
    }
    if (log.isTraceEnabled())
        log.trace("MSG resolveCode: " + code + " (" + locale.getLanguage() + "_" + locale.getCountry()
                + (locale.getVariant() == null ? "" : " -" + locale.getVariant()) + ") into msg: " + msg);
    return createMessageFormat(msg, locale);
}

From source file:org.smigo.species.JdbcSpeciesDao.java

@Override
public List<Species> searchSpecies(String search, Locale locale) {
    String query = (search.length() >= 5 ? "%" : "") + search.toUpperCase() + (search.length() >= 3 ? "%" : "");
    final String whereClause = "SPECIES.ID IN (SELECT SPECIES_ID FROM VERNACULARS WHERE upper(VERNACULAR_NAME) LIKE ? AND LANGUAGE=?) OR upper(SCIENTIFIC_NAME) LIKE ? OR upper(FAMILIES.NAME) LIKE ? OR CAST(SPECIES.ID AS TEXT) LIKE ?";
    final String sql = String.format(SELECT, whereClause, 10);
    return jdbcTemplate.query(sql, new Object[] { query, locale.getLanguage(), query, query, search },
            rowMapper);/*  w  ww  .  j  av a2 s  . c o m*/
}

From source file:com.jaeksoft.searchlib.parser.ParserResultItem.java

protected Locale langDetection(int textLength, ParserFieldEnum parserField) {
    Locale lang = null;
    String text = getMergedBodyText(textLength, " ", parserField);
    if (StringUtils.isEmpty(text))
        return null;
    try {/*from  w ww  . j  av  a2  s  . c  o m*/
        lang = Lang.langDetection(text, text.length());
    } catch (LangDetectException e) {
        Logging.warn(e);
        return null;
    }
    if (lang == null)
        return null;

    addField(ParserFieldEnum.lang, lang.getLanguage());
    addField(ParserFieldEnum.lang_method, NGRAM_RECOGNITION);
    return lang;
}

From source file:org.openmrs.module.custommessage.CustomMessageSource.java

/**
 * @see AbstractMessageSource#resolveCode(String, Locale)
 *//*www  .j  av a2 s .c o m*/
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
    if (showMessageCode) {
        return new MessageFormat(code);
    }
    PresentationMessage pm = getPresentation(code, locale); // Check exact match
    if (pm == null) {
        if (locale.getVariant() != null) {
            pm = getPresentation(code, new Locale(locale.getLanguage(), locale.getCountry())); // Try to match language and country
            if (pm == null) {
                pm = getPresentation(code, new Locale(locale.getLanguage())); // Try to match language only
            }
        }
    }
    if (pm != null) {
        return new MessageFormat(pm.getMessage());
    }
    return null;
}

From source file:org.sakaiproject.adminsiteperms.tool.ResourceLoaderMessageSource.java

protected String resolveCodeWithoutArguments(String code, Locale locale) {
    if (locale != null && resourceLoader.getLocale() == null) {
        resourceLoader.setContextLocale(locale);
    } else {//from   w w w  . j av  a2s .  c o m
        locale = resourceLoader.getLocale();
    }
    String msg;
    if ("DEBUG".equals(locale.getVariant()) || "XX".equals(locale.getCountry())) {
        msg = "** " + code + " **";
    } else {
        msg = resourceLoader.getString(code);
    }
    if (log.isTraceEnabled())
        log.trace("MSG resolveCode (noargs): " + code + " (" + locale.getLanguage() + "_" + locale.getCountry()
                + (locale.getVariant() == null ? "" : " -" + locale.getVariant()) + ") into msg: " + msg);
    return msg;
}

From source file:com.mfalaize.ant.LocalizeTask.java

/**
 * Get the list of available/*w  ww  .  java  2  s  .  c  o  m*/
 * <code>ResourceBundle</code> in the project.
 *
 * @return The list of <code>ResourceBundle</code> available in the project
 * to build.
 * @throws BuildException when the <code>ResourceBundle</code> cannot be
 * find.
 */
private List<ResourceBundle> getAvailableResourceBundles() throws BuildException {
    List<ResourceBundle> list = new ArrayList<ResourceBundle>();

    for (Locale locale : Locale.getAvailableLocales()) {
        try {
            ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundleBaseName, locale);

            if (locale.equals(resourceBundle.getLocale())) {
                list.add(resourceBundle);
            } else {
                log(String.format("No resource bundle exists for the locale %s. Continue...",
                        locale.getLanguage()), Project.MSG_VERBOSE);
            }
        } catch (Throwable ex) {
            throw new BuildException(ex);
        }
    }

    return list;
}

From source file:info.magnolia.cms.i18n.AbstractI18nContentSupport.java

/**
 * Returns the closest locale for which {@link #isLocaleSupported(Locale)} is true.
 * <ul>// w  w  w  .  j  a  v a  2  s. co m
 * <li>If the locale has a country specified (fr_CH) the locale without country (fr) will be returned.</li>
 * <li>If the locale has no country specified (fr) the first locale with the same language but specific country (fr_CH) will be returned.</li>
 * <li>If this fails the fall-back locale is returned</li>
 * </ul>
 * Warning: if you have configured both (fr and fr_CH) this method will jiter between this two values.
 */
protected Locale getNextLocale(Locale locale) {
    // if this locale defines a country
    if (StringUtils.isNotEmpty(locale.getCountry())) {
        // try to use the language only
        Locale langOnlyLocale = new Locale(locale.getLanguage());
        if (isLocaleSupported(langOnlyLocale)) {
            return langOnlyLocale;
        }
    }
    // try to find a locale with the same language (ignore the country)
    for (Iterator<Locale> iter = getLocales().iterator(); iter.hasNext();) {
        Locale otherCountryLocale = iter.next();
        // same lang, but not the same country as well or we end up in the loop
        if (locale.getLanguage().equals(otherCountryLocale.getLanguage())
                && !locale.equals(otherCountryLocale)) {
            return otherCountryLocale;
        }
    }
    return getFallbackLocale();
}

From source file:de.micromata.genome.gwiki.controls.GWikiRegisterUserActionBean.java

protected boolean doRegister() {
    if (StringUtils.isBlank(catchaInput) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.nocatcha", "catchaInput");
        return false;
    }/*ww w .j ava2  s.c o  m*/
    if (checkCatcha() == false) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.wrongcatcha", "catchaInput");
        return false;
    }
    user = StringUtils.trim(user);
    if (StringUtils.isBlank(user) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userempty", "user");
        return false;
    }
    email = StringUtils.trim(email);
    if (StringUtils.isBlank(email) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailempty", "email");
        return false;
    }
    if (checkEmail(email) == false) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailnotvalid", "email");
        return false;
    }
    if (doubleOptIn == false) {
        if (StringUtils.isBlank(pass) == true) {
            wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passempty", "pass");
            pass2 = "";
            return false;
        }
        if (pass.equals(pass2) == false) {
            wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passnotequal", "pass");
            return false;
        }
    } else {
        pass = GWikiLoginActionBean.genPassword();
    }

    GWikiAuthorizationExt authExt = (GWikiAuthorizationExt) wikiContext.getWikiWeb().getAuthorization();
    if (authExt.hasUser(wikiContext, user) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userexists", "user");
        return false;
    }
    if (GWikiSimpleUserAuthorization.rankPasswort(pass) < 1000) {
        wikiContext.addValidationFieldError("gwiki.profile.message.password_too_simple", "pass");
        return false;
    }
    String cp = GWikiSimpleUserAuthorization.encrypt(pass);
    GWikiProps props = new GWikiProps();
    GWikiElement registeredUser = wikiContext.getWikiWeb().findElement("admin/user/registereduser");
    if (registeredUser != null) {
        props = new GWikiProps(((GWikiPropsArtefakt) registeredUser.getMainPart()).getCompiledObject());
    }
    props.setStringValue(GWikiAuthorizationExt.USER_PROP_EMAIL, email);
    if (props.getStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, null) == null) {
        props.setStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, "GWIKI_VIEWPAGES");
    }
    props.setStringValue(GWikiAuthorizationExt.USER_PROP_PASSWORD, cp);
    Locale loc = wikiContext.getRequest().getLocale();
    GWikiGlobalConfig gc = wikiContext.getWikiWeb().getWikiConfig();

    if (loc != null) {
        String lang = loc.getLanguage();
        if (gc.getAvailableLanguages(wikiContext).contains(lang) == true) {
            props.setStringValue(GWikiAuthorizationExt.USER_LANG, lang);
        }
    }
    if (StringUtils.isEmpty(clientTzOffset) == false) {
        try {
            int offsetMin = Integer.parseInt(clientTzOffset);
            int daysaving = TimeZone.getDefault().getDSTSavings();
            int offsetMs = (offsetMin * 1000 * 60 * -1) - daysaving;
            int offsetHour = ((offsetMin / 60) * -1) - (daysaving / ((int) TimeInMillis.HOUR));
            String tzs = "Etc/GMT";
            if (offsetHour != 0) {
                if (offsetHour > 0) {
                    tzs += "+";
                }
                tzs += offsetHour;
            }
            List<String> tcs = gc.getAvailableTimeZones(wikiContext);
            if (tcs.contains(tzs) == true) {
                props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzs);
            } else {
                // String[] offsets = TimeZone.getAvailableIDs(offsetMs);

                for (String tzss : tcs) {
                    TimeZone tz = TimeZone.getTimeZone(tzss);
                    int rawo = tz.getOffset(System.currentTimeMillis());
                    if (rawo == offsetMs) {
                        props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzss);
                        break;
                    }
                }
            }
        } catch (NumberFormatException ex) {
            // ignore
        }
    }
    if (authExt.createUser(wikiContext, user, props) == false) {
        wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.internalerrorstore");
        return false;
    }
    if (doubleOptIn == true) {
        try {
            GWikiLoginActionBean.sendPasswordToUser(wikiContext, user, email, pass);

            wikiContext.addValidationError("gwiki.page.admin.Login.message.resetpassw.emailsent");
        } catch (Exception ex) {
            GWikiLog.error("Cannot send register email: " + ex.getMessage(), ex);
            wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.unabletosend");
        }
        showForm = false;
    } else {
        boolean success = wikiContext.getWikiWeb().getAuthorization().login(wikiContext, StringUtils.trim(user),
                StringUtils.trim(pass));
        if (success == false) {
            return false;
        }
    }
    return true;
}

From source file:com.doculibre.constellio.lucene.impl.SkosIndexHelperImpl.java

@Override
public List<SkosConcept> searchAllLabels(String input, Thesaurus thesaurus, Locale locale) {
    input = adjustInputWildcard(input);/*from  w  w w . j  av  a  2 s.  co m*/
    String adjustedInput = getAndQuery(input);

    StringBuffer luceneQuery = new StringBuffer();
    luceneQuery.append(THESAURUS_ID + ":" + thesaurus.getId());
    luceneQuery.append(" AND ");
    if (locale != null) {
        String suffix = "_" + locale.getLanguage();
        luceneQuery.append("(");
        luceneQuery.append(PREF_LABEL + suffix + ":");
        luceneQuery.append("(");
        luceneQuery.append(adjustedInput);
        luceneQuery.append(")");
        luceneQuery.append(" OR ");
        luceneQuery.append(ALT_LABEL + suffix + ":");
        luceneQuery.append("(");
        luceneQuery.append(adjustedInput);
        luceneQuery.append(")");
        luceneQuery.append(")");
    } else {
        luceneQuery.append("(");
        luceneQuery.append(PREF_LABEL + ":");
        luceneQuery.append("(");
        luceneQuery.append(adjustedInput);
        luceneQuery.append(")");
        luceneQuery.append(" OR ");
        luceneQuery.append(ALT_LABEL + ":");
        luceneQuery.append("(");
        luceneQuery.append(adjustedInput);
        luceneQuery.append(")");
        luceneQuery.append(")");
    }
    return super.search(luceneQuery.toString());
}