Example usage for java.util Locale forLanguageTag

List of usage examples for java.util Locale forLanguageTag

Introduction

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

Prototype

public static Locale forLanguageTag(String languageTag) 

Source Link

Document

Returns a locale for the specified IETF BCP 47 language tag string.

Usage

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

/**
 *Returns the content of the specified properties file in a defined language
 * and returns the default value if the key doesn't exists in that lanaguage.
 *
 * @param sessionid        id of a valid session
 * @param locale            the language to return in  IETF BCP 47 language tag string (samples: es-ES, jap)
 * @param resourceClass   Where to find the properties files (Samples: org.sakaiproject.rubrics.logic.RubricsService  or org.sakaiproject.sharedI18n.SharedProperties)
 * @param resourceBundle  The bundle itself (Samples: rubricsMessages, or org.sakaiproject.sharedI18n.bundle.shared)
 * @return  a String containing a "properties" file in the desired language
 *
 *///from   w w w  . j a v  a2s . co  m
@WebMethod
@Path("/getI18nProperties")
@Produces("text/plain")
@GET
public String getI18nProperties(
        @WebParam(name = "sessionid", partName = "sessionid") @QueryParam("sessionid") String sessionid,
        @WebParam(name = "locale", partName = "locale") @QueryParam("locale") String locale,
        @WebParam(name = "resourceclass", partName = "resourceclass") @QueryParam("resourceclass") String resourceClass,
        @WebParam(name = "resourcebundle", partName = "resourcebundle") @QueryParam("resourcebundle") String resourceBundle) {

    Session session = establishSession(sessionid);
    if (!securityService.isSuperUser()) {
        LOG.warn("NonSuperUser trying to access to translations: " + session.getUserId());
        throw new RuntimeException("NonSuperUser trying to access to translations: " + session.getUserId());
    }
    try {
        StringBuilder lines = new StringBuilder();
        //Convert the locale string in a Locale object
        Locale loc = Locale.forLanguageTag(locale);
        ResourceLoader rb = new Resource().getLoader(resourceClass, resourceBundle);
        rb.setContextLocale(loc);
        //Get all the properties and iterate to return the right value
        Set properties = rb.keySet();
        Iterator keys = properties.iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            lines.append(key + "=" + rb.getString(key) + "\n");
        }
        return lines.toString();
    } catch (Exception e) {
        LOG.warn("WS getI18nProperties(): " + e.getClass().getName() + " : " + e.getMessage());
        return "";
    }

}

From source file:com.github.aynu.yukar.framework.util.PropertiesHelper.java

/**
 * ????/*from w w  w. j  ava  2 s .c  o  m*/
 * @param baseName ??
 * @return ??
 */
private PropertiesConfiguration getPropertiesConfiguration(final String baseName) {
    final String languageTag = String.format("%s-%s", SystemUtils.USER_LANGUAGE, SystemUtils.USER_COUNTRY);
    final Control control = Control.getControl(Control.FORMAT_DEFAULT);
    final Collection<Locale> locales = control.getCandidateLocales("messages",
            Locale.forLanguageTag(languageTag));
    final StringBuilder builder = new StringBuilder();
    for (final Locale locale : locales) {
        try {
            final String bundleName = control.toBundleName(baseName, locale);
            final String resourceName = control.toResourceName(bundleName, "properties");
            final URL url = getClass().getResource("/" + resourceName);
            // final URL url = ClassLoader.getSystemResource(resourceName);
            if (url != null) {
                if (builder.length() > 0) {
                    LOG.debug("Resource could not be found ({}).", builder.toString());
                }
                LOG.debug("Resource could be found ({}).", resourceName);
                return new PropertiesConfiguration(url);
            }
            builder.append(" " + resourceName);
        } catch (final ConfigurationException e) {
            LOG.warn(e.toString(), e);
            throw new StandardRuntimeException(e);
        }
    }
    throw new StandardRuntimeException(String.format("PROPERTY is NOT_FOUND. [baseName=%s]", baseName));
}

From source file:org.mayocat.shop.catalog.store.jdbi.mapper.ProductMapper.java

@Override
public Product map(int index, ResultSet resultSet, StatementContext statementContext) throws SQLException {
    try {//from w  w  w. j av a 2 s  . c  o m
        Product product = new Product((UUID) resultSet.getObject("id"));
        product.setTenantId((UUID) resultSet.getObject("tenant_id"));
        if (resultSet.getObject("parent_id") != null) {
            product.setParentId((UUID) resultSet.getObject("parent_id"));
        }
        product.setSlug(resultSet.getString("slug"));
        product.setTitle(resultSet.getString("title"));
        product.setDescription(resultSet.getString("description"));
        product.setCreationDate(resultSet.getTimestamp("creation_date"));
        if (resultSet.getObject("on_shelf") != null) {
            product.setOnShelf(resultSet.getBoolean("on_shelf"));
        }
        product.setPrice(resultSet.getBigDecimal("price"));

        if (!Strings.isNullOrEmpty(resultSet.getString("taxes"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> taxes = mapper.readValue(resultSet.getString("taxes"),
                    new TypeReference<Map<String, String>>() {
                    });
            if (taxes.containsKey("vat")) {
                product.setVatRateId(taxes.get("vat"));
            }
        }

        product.setWeight(resultSet.getBigDecimal("weight"));
        if (resultSet.getObject("stock") != null) {
            product.setStock(resultSet.getInt("stock"));
        }
        product.setVirtual(resultSet.getBoolean("virtual"));
        UUID featuredImageId = (UUID) resultSet.getObject("featured_image_id");
        if (featuredImageId != null) {
            product.setFeaturedImageId(featuredImageId);
        }

        if (MapperUtils.hasColumn("localization_data", resultSet)
                && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {

                localizedVersions.put(Locale.forLanguageTag((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            product.setLocalizedVersions(localizedVersions);
        }

        String model = resultSet.getString("model");
        if (!Strings.isNullOrEmpty(model)) {
            product.setModel(model);
        }
        String type = resultSet.getString("product_type");
        if (!Strings.isNullOrEmpty(type)) {
            product.setType(type);
        }

        if (resultSet.getArray("features") != null) {
            // There's no support for getting the pg uuid array as a Java UUID array (or even String array) at the time
            // this is written, we have to iterate over the array own result set and construct the Java array ourselves
            List<UUID> ids = new ArrayList<>();
            Array array = resultSet.getArray("features");
            if (array != null) {
                ResultSet featuresResultSet = array.getResultSet();
                while (featuresResultSet.next()) {
                    ids.add((UUID) featuresResultSet.getObject("value"));
                }
                product.setFeatures(ids);
            }
        }

        return product;
    } catch (IOException e) {
        throw new SQLException("Failed to de-serialize JSON data", e);
    }
}

From source file:org.obiba.mica.access.rest.DataAccessRequestsResource.java

@GET
@Path("/_history")
@Produces("text/csv")
public Response downloadHistory(@QueryParam("lang") @DefaultValue("en") String lang) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    new CsvHistoryReportGenerator(listAllWithAmendments(),
            JsonTranslator.buildSafeTranslator(() -> micaConfigService.getTranslations(lang, false)),
            Locale.forLanguageTag(lang), userProfileService, SecurityUtils.getSubject().hasRole(Roles.MICA_DAO)
                    || SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN)).write(byteArrayOutputStream);

    String date = new DateTime().toString("YYYY-MM-dd");
    String filename = String.format("attachment; filename=\"Access-Requests-History-Report_%s.csv\"", date);
    return Response.ok(byteArrayOutputStream.toByteArray()).header("Content-Disposition", filename).build();
}

From source file:com.adaptris.core.services.metadata.DateFormatBuilder.java

private SimpleDateFormat createWithLocale(AdaptrisMessage msg) {
    String language = msg.resolve(getLanguageTag());
    String format = msg.resolve(getFormat());
    return (!isBlank(language)) ? new SimpleDateFormat(format, Locale.forLanguageTag(language))
            : new SimpleDateFormat(format);
}

From source file:com.haulmont.cuba.core.sys.remoting.LocalServiceInvokerImpl.java

@Override
public LocalServiceInvocationResult invoke(LocalServiceInvocation invocation) {
    if (invocation == null) {
        throw new IllegalArgumentException("Invocation is null");
    }// ww  w.j a  v a 2s.co m

    LocalServiceInvocationResult result = new LocalServiceInvocationResult();
    ClassLoader clientClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader classLoader = target.getClass().getClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);

        String[] parameterTypeNames = invocation.getParameterTypeNames();
        Class[] parameterTypes = new Class[parameterTypeNames.length];
        for (int i = 0; i < parameterTypeNames.length; i++) {
            Class<?> paramClass = ClassUtils.getClass(classLoader, parameterTypeNames[i]);
            parameterTypes[i] = paramClass;
        }

        byte[][] argumentsData = invocation.getArgumentsData();
        Object[] notSerializableArguments = invocation.getNotSerializableArguments();
        Object[] arguments;
        if (argumentsData == null) {
            arguments = null;
        } else {
            arguments = new Object[argumentsData.length];
            for (int i = 0; i < argumentsData.length; i++) {
                if (argumentsData[i] == null) {
                    if (notSerializableArguments[i] == null) {
                        arguments[i] = null;
                    } else {
                        arguments[i] = notSerializableArguments[i];
                    }
                } else {
                    arguments[i] = SerializationSupport.deserialize(argumentsData[i]);
                }
            }
        }

        SecurityContext targetSecurityContext = null;
        if (invocation.getSessionId() != null) {
            targetSecurityContext = new SecurityContext(invocation.getSessionId());
        }
        AppContext.setSecurityContext(targetSecurityContext);

        if (invocation.getLocale() != null) {
            Locale locale = Locale.forLanguageTag(invocation.getLocale());
            UserInvocationContext.setRequestScopeInfo(invocation.getSessionId(), locale,
                    invocation.getTimeZone(), invocation.getAddress(), invocation.getClientInfo());
        }

        Method method = target.getClass().getMethod(invocation.getMethodName(), parameterTypes);
        Object data = method.invoke(target, arguments);

        if (invocation.canResultBypassSerialization()) {
            result.setNotSerializableData(data);
        } else {
            result.setData(SerializationSupport.serialize(data));
        }
        return result;
    } catch (Throwable t) {
        if (t instanceof InvocationTargetException)
            t = ((InvocationTargetException) t).getTargetException();
        result.setException(SerializationSupport.serialize(t));
        return result;
    } finally {
        Thread.currentThread().setContextClassLoader(clientClassLoader);
        AppContext.setSecurityContext(null);
        UserInvocationContext.clearRequestScopeInfo();
    }
}

From source file:com.boyuanitsm.fort.service.MailService.java

@Async
public void sendCreationEmail(User user, String baseUrl) {
    log.debug("Sending creation e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);/*w w  w  .  j  a va2 s  . c o m*/
    context.setVariable(BASE_URL, baseUrl);
    String content = templateEngine.process("creationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}

From source file:it.cineca.pst.huborcid.service.MailService.java

@Async
public void sendPasswordResetMail(User user, String baseUrl) {
    log.debug("Sending password reset e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable("user", user);
    context.setVariable("baseUrl", baseUrl);
    String content = templateEngine.process("passwordResetEmail", context);
    String subject = messageSource.getMessage("email.reset.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}

From source file:com.joliciel.talismane.languageDetector.LanguageDetectorImpl.java

@Override
public List<WeightedOutcome<Locale>> detectLanguages(String text) {
    MONITOR.startTask("detectLanguages");
    try {//from   w ww  .  java  2 s .  c  o  m

        if (LOG.isTraceEnabled()) {
            LOG.trace("Testing text: " + text);
        }

        text = text.toLowerCase(Locale.ENGLISH);
        text = Normalizer.normalize(text, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");

        List<FeatureResult<?>> featureResults = new ArrayList<FeatureResult<?>>();
        for (LanguageDetectorFeature<?> feature : features) {
            RuntimeEnvironment env = this.featureService.getRuntimeEnvironment();
            FeatureResult<?> featureResult = feature.check(text, env);
            if (featureResult != null)
                featureResults.add(featureResult);
        }
        if (LOG.isTraceEnabled()) {
            for (FeatureResult<?> result : featureResults) {
                LOG.trace(result.toString());
            }
        }

        List<Decision<LanguageOutcome>> decisions = this.decisionMaker.decide(featureResults);
        if (LOG.isTraceEnabled()) {
            for (Decision<LanguageOutcome> decision : decisions) {
                LOG.trace(decision.getCode() + ": " + decision.getProbability());
            }
        }

        List<WeightedOutcome<Locale>> results = new ArrayList<WeightedOutcome<Locale>>();
        for (Decision<LanguageOutcome> decision : decisions) {
            Locale locale = Locale.forLanguageTag(decision.getOutcome().getCode());
            results.add(new WeightedOutcome<Locale>(locale, decision.getProbability()));
        }

        return results;
    } finally {
        MONITOR.endTask();
    }
}