Example usage for org.apache.commons.lang LocaleUtils isAvailableLocale

List of usage examples for org.apache.commons.lang LocaleUtils isAvailableLocale

Introduction

In this page you can find the example usage for org.apache.commons.lang LocaleUtils isAvailableLocale.

Prototype

public static boolean isAvailableLocale(Locale locale) 

Source Link

Document

Checks if the locale specified is in the list of available locales.

Usage

From source file:de.sub.goobi.forms.SpracheForm.java

/**
 * The constructor of this class loads the required MessageBundle.
 *///from w ww. ja v a 2s. com
public SpracheForm() {
    String key = ConfigCore.getParameter("language.force-default", "de");
    Locale locale = new Locale.Builder().setLanguageTag(key).build();
    if (!LocaleUtils.isAvailableLocale(locale)) {
        FacesContext context = FacesContext.getCurrentInstance();
        if (!Objects.equals(context.getViewRoot(), null)) {
            context.getViewRoot().setLocale(locale);
            context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.i18n.selection.LocaleSelectionController.java

private void processSelectedLocale(HttpServletRequest req, String selectedLocale) {
    if (StringUtils.isBlank(selectedLocale)) {
        log.debug("No '" + PARAMETER_SELECTION + "' parameter");
        return;//  w  ww  .j a  va 2s  .  c o  m
    }

    Locale locale = null;

    try {
        locale = LocaleUtils.toLocale(selectedLocale.trim());
        log.debug("Locale selection is " + locale);
    } catch (IllegalArgumentException e) {
        log.error("Failed to convert the selection to a Locale", e);
        DisplayMessage.setMessage(req, I18n.bundle(req).text("language_selection_failed"));
        return;
    }

    List<Locale> selectables = SelectedLocale.getSelectableLocales(req);
    if (!selectables.contains(locale)) {
        log.warn("User selected a locale '" + locale + "' that was not in the list: " + selectables);
    } else if (!LocaleUtils.isAvailableLocale(locale)) {
        log.warn("User selected an unrecognized locale: '" + locale + "'");
    }

    SelectedLocale.setSelectedLocale(req, locale);
    log.debug("Setting selected locale to " + locale);
}

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

@Override
protected Locale onDetermineLocale() {
    Locale locale = null;//from ww  w  . j  a  v  a  2 s  .  c om
    Locale validUnsupportedLocale = null;
    final String i18nURI = MgnlContext.getAggregationState().getCurrentURI();
    log.debug("URI to check for locales is {}", i18nURI);
    final String[] splitURI = i18nURI.split("/");
    final int lastTokenIdx = splitURI.length - 1;
    for (int i = 0; i < splitURI.length; i++) {
        String uriToken = splitURI[i];
        if (i == lastTokenIdx) {
            uriToken = StringUtils.substringBefore(uriToken, ".");
        }
        locale = determineLocalFromString(uriToken);
        if (LocaleUtils.isAvailableLocale(locale)) {
            log.debug("found a valid Locale code {}", uriToken);
            if (isLocaleSupported(locale)) {
                break;
            }
            // the URI contains a valid Locale code but it is not
            // supported by the current I18n configuration.
            // We store it anyway and eventually return it if no exact
            // match will be found at the end of this loop.
            validUnsupportedLocale = locale;
        }
        locale = null;
    }

    return locale != null ? locale : validUnsupportedLocale;
}

From source file:edu.cornell.mannlib.vitro.webapp.i18n.selection.LocaleSelectionSetup.java

private Locale buildLocale(String localeString) throws IllegalArgumentException {
    Locale locale = LocaleUtils.toLocale(localeString);

    if (!"es_GO".equals(localeString) && // No complaint about bogus locale
            !LocaleUtils.isAvailableLocale(locale)) {
        ssWarning("'" + locale + "' is not a recognized locale.");
    }/*  w  w w  .  java  2  s  . c om*/
    return locale;
}

From source file:de.uni_tuebingen.ub.ixTheo.handler.component.FacetPrefixSortComponent.java

/**
 * Choose the collator according to the selected language
 *//*from w w  w . j av a 2 s  . c o m*/

private void setCollator(final String langCode) {

    Locale locale = Locale.GERMAN;
    String transformedLangCode = "";

    // Rewrite lang parameter to required layout
    Matcher m = LANG_CODE_TRANSFORMATION_PATTERN.matcher(langCode);
    StringBuffer sb = new StringBuffer(langCode.length());
    while (m.find()) {
        if (m.group(1) != null)
            sb.append(m.group(1).toLowerCase());

        if (m.group(2) != null)
            sb.append(m.group(2).equals("-") ? "_" : "");

        if (m.group(3) != null)
            sb.append(m.group(3).toUpperCase());

        transformedLangCode = sb.toString();
    }

    try {
        locale = LocaleUtils.toLocale(transformedLangCode);
    } catch (IllegalArgumentException e) {
    }

    if (LocaleUtils.isAvailableLocale(locale))
        collator = Collator.getInstance(locale);
    else
        collator = Collator.getInstance(Locale.GERMAN);
}

From source file:de.sub.goobi.forms.SpracheForm.java

/**
 * Get locale.//from  w  w  w .ja v  a2 s. c o m
 *
 * @return Locale object
 */
public Locale getLocale() {
    FacesContext fac = FacesContext.getCurrentInstance();
    @SuppressWarnings("rawtypes")
    UIViewRoot frame = fac.getViewRoot();
    if (!Objects.equals(frame, null)) {
        Map session = fac.getExternalContext().getSessionMap();
        if (session.containsKey(SESSION_LOCALE_FIELD_ID)) {
            Locale locale = (Locale) session.get(SESSION_LOCALE_FIELD_ID);
            if (frame.getLocale() != locale) {
                frame.setLocale(locale);
            }
            return locale;
        } else {
            return frame.getLocale();
        }
    } else {
        /*
         * When no locale is given (no Accept-Language Http Request header
         * is present) return default language
         */
        String key = ConfigCore.getParameter("language.default", "de");
        Locale locale = new Locale.Builder().setLanguageTag(key).build();
        if (LocaleUtils.isAvailableLocale(locale)) {
            return locale;
        } else {
            throw new IllegalArgumentException("Locale code is not valid");
        }
    }
}

From source file:org.kitodo.production.forms.LanguageForm.java

/**
 * Set session locale field id.//from  w  w  w . ja  va 2s .  com
 *
 *
 */
private void setSessionLocaleFieldId() {
    String key = "";
    if (Objects.isNull(ServiceManager.getUserService().getAuthenticatedUser())) {
        key = ConfigCore.getParameterOrDefaultValue(ParameterCore.LANGUAGE_DEFAULT);
    } else {
        try {
            User user = ServiceManager.getUserService()
                    .getById(ServiceManager.getUserService().getAuthenticatedUser().getId());
            key = user.getLanguage();
        } catch (DAOException e) {
            Helper.setErrorMessage("Error in retrieving user ", logger, e);
        }
    }
    Locale locale = new Locale.Builder().setLanguageTag(key).build();
    if (LocaleUtils.isAvailableLocale(locale)) {
        FacesContext context = FacesContext.getCurrentInstance();
        if (Objects.nonNull(context.getViewRoot())) {
            context.getViewRoot().setLocale(locale);
            context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale);
        }
    }
}

From source file:org.kitodo.production.forms.LanguageForm.java

/**
 * Get locale./*from w  w  w. ja  v a 2 s .  c  o  m*/
 *
 * @return Locale object
 */
public Locale getLocale() {
    setSessionLocaleFieldId();
    FacesContext fac = FacesContext.getCurrentInstance();
    UIViewRoot frame = fac.getViewRoot();
    if (!Objects.equals(frame, null)) {
        @SuppressWarnings("rawtypes")
        Map session = fac.getExternalContext().getSessionMap();
        if (session.containsKey(SESSION_LOCALE_FIELD_ID)) {
            Locale locale = (Locale) session.get(SESSION_LOCALE_FIELD_ID);
            if (frame.getLocale() != locale) {
                frame.setLocale(locale);
            }
            return locale;
        } else {
            return frame.getLocale();
        }
    } else {
        /*
         * When no locale is given (no Accept-Language Http Request header
         * is present) return default language
         */
        String key = ConfigCore.getParameterOrDefaultValue(ParameterCore.LANGUAGE_DEFAULT);
        Locale locale = new Locale.Builder().setLanguageTag(key).build();
        if (LocaleUtils.isAvailableLocale(locale)) {
            return locale;
        } else {
            throw new IllegalArgumentException("Locale code is not valid");
        }
    }
}

From source file:org.sakaiproject.webservices.SakaiScript.java

/**
 * Edit a user's locale//  w  w w. jav  a 2 s. c  o  m
 *
 * @param sessionid the id of a valid session
 * @param eid       the login username (ie jsmith26) of the user you want to edit
 * @param locale  the locale for the user
 * @return success or exception message
 * @throws RuntimeException
 */
@WebMethod
@Path("/changeUserLocale")
@Produces("text/plain")
@GET
public String changeUserLocale(
        @WebParam(name = "sessionid", partName = "sessionid") @QueryParam("sessionid") String sessionid,
        @WebParam(name = "eid", partName = "eid") @QueryParam("eid") String eid,
        @WebParam(name = "locale", partName = "locale") @QueryParam("locale") String locale) {
    Session session = establishSession(sessionid);

    try {
        Locale localeParam = LocaleUtils.toLocale(locale);
        if (!LocaleUtils.isAvailableLocale(localeParam)) {
            LOG.warn("WS changeUserLocale(): Locale not available");
            return "";
        }
    } catch (Exception e) {
        LOG.error("WS changeUserLocale(): " + e.getClass().getName() + " : " + e.getMessage());
        return e.getClass().getName() + " : " + e.getMessage();
    }

    UserEdit userEdit = null;
    PreferencesEdit prefs = null;
    try {
        User user = userDirectoryService.getUserByEid(eid);

        try {
            prefs = (PreferencesEdit) preferencesService.edit(user.getId());
        } catch (IdUnusedException e1) {
            prefs = (PreferencesEdit) preferencesService.add(user.getId());
        }
        ResourcePropertiesEdit props = prefs.getPropertiesEdit(ResourceLoader.APPLICATION_ID);
        props.addProperty(ResourceLoader.LOCALE_KEY, locale);
        preferencesService.commit(prefs);
    } catch (Exception e) {
        preferencesService.cancel(prefs);
        LOG.error("WS changeUserLocale(): " + e.getClass().getName() + " : " + e.getMessage());
        return e.getClass().getName() + " : " + e.getMessage();
    }
    return "success";
}