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

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

Introduction

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

Prototype

public static Locale toLocale(String str) 

Source Link

Document

Converts a String to a Locale.

This method takes the string format of a locale and creates the locale object from it.

 LocaleUtils.toLocale("en")         = new Locale("en", "") LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB") LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#) 

(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.

Usage

From source file:org.jamwiki.servlets.JAMWikiLocaleInterceptor.java

/**
 *
 *//*from www . ja v a 2  s  . c o  m*/
private Locale retrieveUserLocale(HttpServletRequest request) throws ServletException {
    Locale locale = null;
    try {
        WikiUser user = ServletUtil.currentWikiUser();
        locale = LocaleUtils.toLocale(user.getDefaultLocale());
    } catch (AuthenticationCredentialsNotFoundException e) {
        // do nothing, just use a default locale
    }
    return locale;
}

From source file:org.jamwiki.servlets.RegisterServlet.java

/**
 *
 *//*from   www  .ja v a  2s .c o m*/
private void register(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String virtualWikiName = pageInfo.getVirtualWikiName();
    WikiUser user = this.setWikiUser(request);
    boolean isUpdate = (user.getUserId() != null);
    next.addObject("newuser", user);
    List<WikiMessage> errors = validate(request, user);
    if (!errors.isEmpty()) {
        next.addObject("errors", errors);
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        if (oldPassword != null) {
            next.addObject("oldPassword", oldPassword);
        }
        if (newPassword != null) {
            next.addObject("newPassword", newPassword);
        }
        if (confirmPassword != null) {
            next.addObject("confirmPassword", confirmPassword);
        }
        this.loadDefaults(request, next, pageInfo, user);
    } else {
        String username = request.getParameter("login");
        String newPassword = request.getParameter("newPassword");
        String encryptedPassword = null;
        if (!StringUtils.isBlank(newPassword)) {
            encryptedPassword = Encryption.encrypt(newPassword);
        }
        WikiBase.getDataHandler().writeWikiUser(user, username, encryptedPassword);
        if (!StringUtils.isBlank(newPassword)) {
            // login the user
            this.login(request, user.getUsername(), newPassword);
        }
        // update the locale key since the user may have changed default locale
        if (!StringUtils.isBlank(user.getDefaultLocale())) {
            Locale locale = LocaleUtils.toLocale(user.getDefaultLocale());
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
        }
        if (isUpdate) {
            next.addObject("updateMessage", new WikiMessage("register.caption.updatesuccess"));
            this.view(request, next, pageInfo);
        } else {
            VirtualWiki virtualWiki = WikiBase.getDataHandler().lookupVirtualWiki(virtualWikiName);
            String topic = virtualWiki.getDefaultTopicName();
            ServletUtil.redirect(next, virtualWikiName, topic);
        }
    }
}

From source file:org.jamwiki.servlets.ServletUtil.java

/**
 * Users can specify a default locale in their preferences, so determine if
 * the current user is logged-in and has chosen a locale. If not, use the
 * default locale from the request object.
 * //  w ww.j a v a  2s. c  o m
 * @param request
 *          The request object for the HTTP request.
 * @return Either the user's default locale (for logged-in users) or the
 *         locale specified in the request if no default locale is available.
 */
public static Locale retrieveUserLocale(HttpServletRequest request) {
    try {
        WikiUser user = ServletUtil.currentWikiUser();
        if (user.getDefaultLocale() != null) {
            return LocaleUtils.toLocale(user.getDefaultLocale());
        }
    } catch (AuthenticationCredentialsNotFoundException e) {
        // ignore
    }
    return request.getLocale();
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.structures.BuildData.java

public BuildData(final String requester, final ContentSpec contentSpec,
        final DocBookBuildingOptions buildOptions, final ZanataDetails zanataDetails,
        final DataProviderFactory providerFactory, boolean translationBuild) {
    this.contentSpec = contentSpec;
    this.requester = requester;
    this.buildOptions = buildOptions;
    this.zanataDetails = zanataDetails;
    escapedTitle = DocBookUtilities.escapeTitle(contentSpec.getTitleNode().getValue());
    if (BuilderConstants.VALID_PUBLICAN_DOCNAME_PATTERN.matcher(escapedTitle).matches()) {
        rootBookFileName = escapedTitle;
    } else {/* w  w  w .java  2s  .  co m*/
        rootBookFileName = contentSpec.getBookType().toString().replace("-Draft", "");
    }
    this.translationBuild = translationBuild;
    buildDate = new Date();

    // Load the server settings
    serverSettings = providerFactory.getProvider(ServerSettingsProvider.class).getServerSettings();

    // Load the locales from the server
    localeMap = buildLocaleMap(serverSettings.getLocales());

    // Configure the locales to use
    defaultLocale = contentSpec.getLocale() == null ? serverSettings.getDefaultLocale().getBuildValue()
            : contentSpec.getLocale();
    if (translationBuild) {
        locale = buildOptions.getLocale() == null ? defaultLocale : buildOptions.getLocale();
    } else {
        locale = defaultLocale;
    }
    if (buildOptions.getOutputLocale() != null) {
        outputLocale = buildOptions.getOutputLocale();
    } else if (localeMap.containsKey(locale)) {
        outputLocale = localeMap.get(locale).getBuildValue();
    } else {
        outputLocale = locale;
    }

    // Apply the build values from the spec
    applyBuildOptionsFromSpec(contentSpec, buildOptions);
    applyInjectionOptionsFromSpec(contentSpec, buildOptions);

    // Get the resource bundle to use
    if (getBuildLocale().equals("en-US") || !localeMap.containsKey(getBuildLocale())) {
        constantsResourceBundle = ResourceBundle.getBundle(
                "org.jboss.pressgang.ccms.contentspec.builder.Constants", new UTF8ResourceBundleControl());
    } else {
        final Locale buildLocale = LocaleUtils
                .toLocale(localeMap.get(getBuildLocale()).getBuildValue().replace('-', '_'));
        constantsResourceBundle = ResourceBundle.getBundle(
                "org.jboss.pressgang.ccms.contentspec.builder.Constants", buildLocale,
                new UTF8ResourceBundleControl());
    }
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.structures.POBuildData.java

public POBuildData(String requester, ContentSpec contentSpec, DocBookBuildingOptions buildOptions,
        ZanataDetails zanataDetails, DataProviderFactory providerFactory, boolean translationBuild) {
    super(requester, contentSpec, buildOptions, zanataDetails, providerFactory, translationBuild);

    // Setup the locales
    poLocale = getBuildOptions().getLocale() == null ? getBuildLocale() : getBuildOptions().getLocale();
    if (getBuildOptions().getOutputLocale() != null) {
        poOutputLocale = getBuildOptions().getOutputLocale();
    } else if (getLocaleMap().containsKey(poLocale)) {
        poOutputLocale = getLocaleMap().get(poLocale).getValue();
    } else {//from   www .j  av a  2  s .c  o m
        poOutputLocale = poLocale;
    }

    if (getLocaleMap().containsKey(getBuildLocale())) {
        outputLocale = getLocaleMap().get(getBuildLocale()).getBuildValue();
    } else {
        outputLocale = getBuildLocale();
    }

    if (getBuildLocale().equals(getPOBuildLocale())) {
        translatedConstantsResourceBundle = getConstants();
    } else {
        final Locale buildLocale = LocaleUtils
                .toLocale(getLocaleMap().get(poLocale).getBuildValue().replace('-', '_'));
        translatedConstantsResourceBundle = ResourceBundle.getBundle(
                "org.jboss.pressgang.ccms.contentspec.builder.Constants", buildLocale,
                new UTF8ResourceBundleControl());
    }
}

From source file:org.liveSense.server.i18n.loader.I18nLoader.java

public void install(Bundle bundle, String bundleName) throws Exception {
    // Removes proxy classes
    I18N.resetCache();//from w w  w .j a v  a2s .  co  m
    log.info("Registering I18n: " + bundleName);
    i18nService.registerResourceBundle(bundle, bundleName);

    Session session = null;
    try {
        session = repository.loginAdministrative(null);
        // Writing entries to Repository
        String i18nPath = new File(bundleName.replace(".", "/")).getParent();
        String i18nName = new File(bundleName.replace(".", "/")).getName();
        Enumeration entries = bundle.getEntryPaths(i18nPath);

        if (entries != null) {
            while (entries.hasMoreElements()) {
                URL url = bundle.getEntry((String) entries.nextElement());
                String urlFileName = new File(url.getFile()).getName();
                if (urlFileName.endsWith(".properties") && (urlFileName.startsWith(i18nName))) {
                    log.info("Loading " + url + " into JCR repository");
                    String locale = urlFileName.substring(i18nName.length(),
                            urlFileName.length() - ".properties".length());
                    Locale loc = Locale.getDefault();
                    if (StringUtils.isNotEmpty(locale)) {
                        loc = LocaleUtils.toLocale(locale.substring(1));

                        Node n = createPath(session, "/" + path + "/" + bundleName + "/" + loc.toString(),
                                FOLDER_NODE_TYPE);
                        boolean foundType = false;
                        for (NodeType t : n.getMixinNodeTypes()) {
                            if (t.getName().equals(NodeType.MIX_LANGUAGE)) {
                                foundType = true;
                            }
                        }
                        if (!foundType)
                            n.addMixin(NodeType.MIX_LANGUAGE);
                        n.setProperty("jcr:language", loc.toString());
                        n.setProperty("sling:basename", bundleName);

                        java.util.Properties props = new java.util.Properties();
                        InputStream in = url.openStream();
                        props.load(in);
                        in.close();

                        for (Object key : props.keySet()) {
                            if (!n.hasNode((String) key)) {
                                log.info("Creating " + (String) key);
                                Node msgNode = n.addNode((String) key, "sling:MessageEntry");
                                msgNode.setProperty("sling:key", (String) key);
                                msgNode.setProperty("sling:message", props.getProperty((String) key));
                            }
                        }
                    }
                }
            }
        }
        if (session.hasPendingChanges())
            session.save();
    } catch (RepositoryException e) {
        log.error("Cannot get session", e);
    } finally {
        if (session != null && session.isLive()) {
            try {
                session.logout();
            } catch (Exception e) {
            }
        }
    }

}

From source file:org.mule.el.context.ServerContextTestCase.java

@Test
public void dateTimeFormat() {
    Assert.assertEquals(new SimpleDateFormat("EEE, MMM d, yyyy").format(new Date()),
            evaluate("server.dateTime.format('EEE, MMM d, yyyy')"));
    Assert.assertEquals(/* w w  w  .  j a  v  a2  s . c om*/
            new SimpleDateFormat("EEE, MMM d, yyyy", LocaleUtils.toLocale("en_US")).format(new Date()),
            evaluate("server.dateTime.withLocale('en_US').format('EEE, MMM d, yyyy')"));
}

From source file:org.mule.el.context.ServerContextTestCase.java

@Test
public void dateTimeWithLocale() {
    assertEquals(new SimpleDateFormat("E").format(new Date()),
            evaluate("server.dateTime.withLocale('en_US').format('E')"));
    assertEquals(new SimpleDateFormat("E", LocaleUtils.toLocale("es_AR")).format(new Date()),
            evaluate("server.dateTime.withLocale('es_AR').format('E')"));
}

From source file:org.mule.el.datetime.AbstractInstant.java

@Override
public Instant withLocale(String locale) {
    this.locale = LocaleUtils.toLocale(locale);
    Calendar newCalendar = Calendar.getInstance(calendar.getTimeZone(), this.locale);
    newCalendar.setTime(calendar.getTime());
    this.calendar = newCalendar;
    return this;
}

From source file:org.netxilia.api.impl.format.NumberFormatter.java

/**
 * this should be called before using the formatter!
 *//*  w w w.  j  a  va2 s. com*/
public void init() {
    this.localeObject = locale != null ? LocaleUtils.toLocale(locale) : Locale.getDefault();
}