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.onehippo.forge.properties.tags.PropertyTag.java

@Override
protected int doEndTag(final HstRequest hstRequest, final HstResponse hstResponse) {

    // required att
    if (name == null) {
        throw new IllegalStateException("Missing required attribute 'name' in PropertyTag");
    }/*  w  w  w.  j a  v a 2 s.co m*/

    final ComponentManager componentManager = HstServices.getComponentManager();

    final String propertiesManagerPostfix = (managerPostfix != null) ? managerPostfix : MANAGER_POSTFIX_DEFAULT;
    final String propertiesManagerId = PropertiesManager.class.getName() + "." + propertiesManagerPostfix;

    PropertiesManager propertiesManager = componentManager.getComponent(propertiesManagerId);

    // use PropertiesManager API to retrieve property map
    final HippoBean siteContentBaseBean = this.getSiteContentBaseBean(hstRequest);
    final PropertiesBean propertiesBean = (language == null)
            ? propertiesManager.getPropertiesBean(documentPath, siteContentBaseBean, hstRequest.getLocale())
            : propertiesManager.getPropertiesBean(documentPath, siteContentBaseBean,
                    LocaleUtils.toLocale(language));
    final Map<String, String> properties = PropertiesUtil.toMap(propertiesBean);

    if (properties == null) {
        handleValue(getDefaultValue(propertiesManager), hstRequest);
    } else {
        // get value and handle it
        String value = properties.get(this.name);
        if (value != null) {
            handleValue(value, hstRequest);
        } else {
            handleValue(getDefaultValue(propertiesManager), hstRequest);
        }
    }

    cleanup();
    return EVAL_PAGE;
}

From source file:org.opencastproject.serviceregistry.impl.endpoint.IncidentServiceEndpoint.java

@GET
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)//  ww w.j av  a 2  s. c o  m
@Path("localization/{id}")
@RestQuery(name = "getlocalization", description = "Returns the localization of an incident by it's id as JSON", returnDescription = "The localization of the incident as JSON", pathParameters = {
        @RestParameter(name = "id", isRequired = true, description = "The incident identifiers.", type = Type.INTEGER) }, restParameters = {
                @RestParameter(name = "locale", isRequired = true, description = "The locale.", type = Type.STRING) }, reponses = {
                        @RestResponse(responseCode = SC_OK, description = "The localization of the given job incidents."),
                        @RestResponse(responseCode = SC_NOT_FOUND, description = "No job incident with this incident identifier was found.") })
public Response getLocalization(@PathParam("id") final long incidentId, @QueryParam("locale") String locale)
        throws NotFoundException {
    try {
        IncidentL10n localization = svc.getLocalization(incidentId, LocaleUtils.toLocale(locale));
        JSONObject json = new JSONObject();
        json.put("title", localization.getTitle());
        json.put("description", localization.getDescription());
        return Response.ok(json.toJSONString()).build();
    } catch (IncidentServiceException e) {
        logger.warn("Unable to get job localization of jo incident: {}", e);
        throw new WebApplicationException(INTERNAL_SERVER_ERROR);
    }
}

From source file:org.opoo.press.impl.SiteImpl.java

void setup() {
    //ensure source not in destination
    for (File source : sources) {
        source = PathUtils.canonical(source);
        if (dest.equals(source) || source.getAbsolutePath().startsWith(dest.getAbsolutePath())) {
            throw new IllegalArgumentException(
                    "Destination directory cannot be or contain the Source directory.");
        }//  ww w. jav a2 s  . c  o m
    }

    //locale
    String localeString = config.get("locale");
    if (localeString != null) {
        locale = LocaleUtils.toLocale(localeString);
        log.debug("Set locale: " + locale);
    }

    //date_format
    dateFormatPattern = config.get("date_format");
    if (dateFormatPattern == null) {
        dateFormatPattern = "yyyy-MM-dd";
    } else if ("ordinal".equals(dateFormatPattern)) {
        dateFormatPattern = "MMM d yyyy";
    }

    //object instances
    classLoader = createClassLoader(config, theme);
    taskExecutor = new TaskExecutor(config);
    factory = FactoryImpl.createInstance(this);

    processors = new ProcessorsProcessor(factory.getPluginManager().getProcessors());

    //Construct RendererImpl after initializing all plugins
    renderer = factory.createRenderer(this);
}

From source file:org.richfaces.tests.metamer.ftest.AbstractGrapheneTest.java

/**
 * Returns the locale of the tested page
 *
 * @return the locale of the tested page
 *//*from  w w w  . j  ava  2s.  com*/
public Locale getLocale() {
    String localeString = selenium.getText(id("locale"));
    return LocaleUtils.toLocale(localeString);
}

From source file:org.sakaiproject.emailtemplateservice.service.impl.EmailTemplateServiceImpl.java

public void processEmailTemplates(List<String> templatePaths) {

    final String ADMIN = "admin";

    Persister persister = new Persister();
    for (String templatePath : templatePaths) {

        log.debug("Processing template: " + templatePath);

        InputStream in = getClass().getClassLoader().getResourceAsStream(templatePath);

        if (in == null) {
            log.warn("Could not load resource from '" + templatePath + "'. Skipping ...");
            continue;
        }/*from w ww  . j  a  v  a 2  s.c  om*/

        EmailTemplate template = null;
        try {
            template = persister.read(EmailTemplate.class, in);
        } catch (Exception e) {
            log.warn("Error processing template: '" + templatePath + "', " + e.getClass() + ":" + e.getMessage()
                    + ". Skipping ...");
            continue;
        }

        //check if we have an existing template of this key and locale
        //its possible the template has no locale set
        //The locale could also be the Default
        Locale loc = null;
        if (template.getLocale() != null && !"".equals(template.getLocale())
                && !EmailTemplate.DEFAULT_LOCALE.equals(template.getLocale())) {
            loc = LocaleUtils.toLocale(template.getLocale());
        }

        EmailTemplate existingTemplate = getEmailTemplateNoDefault(template.getKey(), loc);
        if (existingTemplate == null) {
            //no existing, save this one
            Session sakaiSession = sessionManager.getCurrentSession();
            sakaiSession.setUserId(ADMIN);
            sakaiSession.setUserEid(ADMIN);
            saveTemplate(template);
            sakaiSession.setUserId(null);
            sakaiSession.setUserId(null);
            log.info("Saved email template: " + template.getKey() + " with locale: " + template.getLocale());
            continue; //skip to next
        }

        //check version, if local one newer than persisted, update it - SAK-17679
        //also update the locale - SAK-20987
        int existingTemplateVersion = existingTemplate.getVersion() != null
                ? existingTemplate.getVersion().intValue()
                : 0;
        if (template.getVersion() > existingTemplateVersion) {
            existingTemplate.setSubject(template.getSubject());
            existingTemplate.setMessage(template.getMessage());
            existingTemplate.setHtmlMessage(template.getHtmlMessage());
            existingTemplate.setVersion(template.getVersion());
            existingTemplate.setOwner(template.getOwner());
            existingTemplate.setLocale(template.getLocale());

            Session sakaiSession = sessionManager.getCurrentSession();
            sakaiSession.setUserId(ADMIN);
            sakaiSession.setUserEid(ADMIN);
            updateTemplate(existingTemplate);
            sakaiSession.setUserId(null);
            sakaiSession.setUserId(null);
            log.info("Updated email template: " + template.getKey() + " with locale: " + template.getLocale());
        }
    }
}

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

/**
 * Edit a user's locale//from   w w w  .j  av  a2  s .  com
 *
 * @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";
}

From source file:org.sonar.server.charts.jruby.TrendsChart.java

public TrendsChart(int width, int height, String localeKey, boolean displayLegend) {
    super(width, height);
    this.displayLegend = displayLegend;
    seriesById = new TreeMap<Long, TimeSeries>();
    plot = new XYPlot();
    DateAxis dateAxis = new DateAxis();
    dateAxis.setDateFormatOverride(/*from ww  w  .  j ava2 s.  c  o  m*/
            DateFormat.getDateInstance(DateFormat.SHORT, LocaleUtils.toLocale(localeKey)));
    plot.setDomainAxis(dateAxis);
}

From source file:org.sonar.server.platform.ws.L10nWs.java

protected void serializeMessages(Request request, Response response) throws IOException {
    Date timestamp = request.paramAsDateTime("ts");
    if (timestamp != null && timestamp.after(server.getStartedAt())) {
        response.stream().setStatus(HttpURLConnection.HTTP_NOT_MODIFIED).output().close();
    } else {//from w  w  w  . j a v  a  2s .  co m

        Locale locale = userSession.locale();
        String localeParam = request.param("locale");
        if (localeParam != null) {
            locale = LocaleUtils.toLocale(localeParam);
        }
        JsonWriter json = response.newJsonWriter().beginObject();
        for (String messageKey : i18n.getPropertyKeys()) {
            json.prop(messageKey, i18n.message(locale, messageKey, messageKey));
        }
        json.endObject().close();
    }
}

From source file:org.tdl.vireo.model.jpa.JpaSubmissionImplTests.java

/**
 * Test converting document language into a locale
 *//* ww  w  . j  a va  2s .co  m*/
@Test
public void testGetLocale() {

    Submission sub = subRepo.createSubmission(person).save();

    sub.setDocumentLanguage("de");
    Locale german = LocaleUtils.toLocale("de");
    assertEquals(german, sub.getDocumentLanguageLocale());

    sub.setDocumentLanguage("de_CH");
    Locale germanAustria = LocaleUtils.toLocale("de_CH");
    assertEquals(germanAustria, sub.getDocumentLanguageLocale());

    sub.setDocumentLanguage(null);
    assertEquals(null, sub.getDocumentLanguageLocale());

    sub.delete();
}

From source file:org.xdi.oxauth.model.util.LocaleUtil.java

public static Locale localeMatch(List<String> requestedLocales, List<Locale> availableLocales) {
    if (requestedLocales == null || availableLocales == null) {
        return null;
    }//from  w  w w . j a  va2 s.  c om

    for (String requestedLocale : requestedLocales) {
        Locale reqInQuestion = LocaleUtils.toLocale(requestedLocale);
        List<Locale> lookupList = LocaleUtils.localeLookupList(reqInQuestion);

        for (Locale localeInQuestion : lookupList) {
            for (Locale availableLocale : availableLocales) {
                if (localeInQuestion.equals(availableLocale)) {
                    return availableLocale;
                }
            }
        }

        for (Locale availableLocale : availableLocales) {
            if (reqInQuestion.getLanguage().equals(availableLocale.getLanguage())) {
                return availableLocale;
            }
        }
    }

    return null;
}