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:rapture.dp.invocable.calendar.steps.GetDayOfWeekStep.java

@Override
public String invoke(CallingContext ctx) {
    DecisionApi decision = Kernel.getDecision();
    try {/*  w  ww  .j a v  a  2s  .  c o m*/
        decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName());
        String dateStr = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DATE"));
        String languageTag = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "LOCALE"));
        LocalDateTime date = (dateStr == null) ? LocalDateTime.now() : LocalDateTime.parse(dateStr);
        Locale locale = (languageTag == null) ? Locale.getDefault() : Locale.forLanguageTag(languageTag);
        String day = DayOfWeek.from(date).getDisplayName(TextStyle.FULL, locale);
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Day of week is " + day, false);
        return day;
    } catch (Exception e) {
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                "Exception in workflow : " + e.getLocalizedMessage());
        decision.setContextLiteral(ctx, getWorkerURI(), getErrName(), ExceptionToString.summary(e));
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(),
                true);
        return getErrorTransition();
    }
}

From source file:org.structr.core.parser.function.NumberFormatFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    if (sources == null || sources != null && sources.length != 3) {
        return usage(ctx.isJavaScriptContext());
    }/*from w w w  .j av  a2s  .c  o  m*/

    if (arrayHasLengthAndAllElementsNotNull(sources, 3)) {

        if (StringUtils.isBlank(sources[0].toString())) {
            return "";
        }

        try {

            Double val = Double.parseDouble(sources[0].toString());
            String langCode = sources[1].toString();
            String pattern = sources[2].toString();

            return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode)))
                    .format(val);

        } catch (Throwable t) {
        }
    }

    return "";
}

From source file:org.wallride.web.support.PathVariableLocaleResolver.java

@Override
public Locale resolveLocale(HttpServletRequest request) {
    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    String defaultLanguage = (blog != null) ? blog.getDefaultLanguage() : null;

    Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String currentLanguage = (String) pathVariables.get("language");
    if (currentLanguage == null) {
        currentLanguage = defaultLanguage;
    } else {/*from  w ww  . ja v a  2  s. c  o m*/
        boolean correct = false;
        if (blog != null) {
            for (BlogLanguage blogLanguage : blog.getLanguages()) {
                if (blogLanguage.getLanguage().equals(currentLanguage)) {
                    correct = true;
                    break;
                }
            }
        }
        if (!correct) {
            currentLanguage = defaultLanguage;
        }
    }

    return (currentLanguage != null) ? Locale.forLanguageTag(currentLanguage) : request.getLocale();
}

From source file:org.structr.core.function.ParseNumberFunction.java

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources)
        throws FrameworkException {

    if (sources == null || (sources.length == 2 && sources[1] == null) || sources.length > 2) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }//from   w ww  .  j ava  2  s. c o m

    try {

        final String numberString = sources[0].toString().replaceAll("[^\\d.,]", "");
        ;

        if (StringUtils.isBlank(numberString)) {
            return "";
        }

        Locale locale = ctx.getLocale();
        try {

            if (sources.length == 2) {

                final String localeString = sources[1].toString();

                if (StringUtils.isNotBlank(localeString)) {

                    locale = Locale.forLanguageTag(localeString);
                }
            }

            return NumberFormat.getInstance(locale).parse(numberString);

        } catch (ParseException ex) {

            logException(ex, "{}: Could not parse string \"{}\" to number. Parameters: {}",
                    new Object[] { getName(), caller, getParametersAsString(sources) });
        }

    } catch (final IllegalArgumentException e) {

        logParameterError(caller, sources, ctx.isJavaScriptContext());

        return usage(ctx.isJavaScriptContext());

    }

    return "";
}

From source file:com.jeanchampemont.notedown.utils.UserLocaleResolver.java

@Override
public Locale resolveLocale(HttpServletRequest request) {
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        return acceptHeaderLocaleResolver.resolveLocale(request);
    }// w w  w  .ja v  a 2  s. c  om
    String email = SecurityContextHolder.getContext().getAuthentication().getName();
    Optional<User> user = userService.getUserByEmail(email);
    if (!user.isPresent() || StringUtils.isEmpty(user.get().getLocale())) {
        return acceptHeaderLocaleResolver.resolveLocale(request);
    }
    return user.map(u -> Locale.forLanguageTag(u.getLocale())).get();
}

From source file:nu.yona.server.goals.service.ActivityCategoryDto.java

private static Map<Locale, String> mapToLocaleMap(Map<String, String> localeStringMap) {
    return localeStringMap.entrySet().stream()
            .collect(Collectors.toMap(e -> Locale.forLanguageTag(e.getKey()), Map.Entry::getValue));
}

From source file:org.wso2.carbon.uuf.api.config.I18nResources.java

/**
 * Returns the local for the supported language.
 *
 * @param localeHeaderValue local header value
 * @return Locale object for language support
 *//*w  ww.  j  ava 2 s .co m*/
public Locale getLocale(String localeHeaderValue) {
    if (localeHeaderValue == null) {
        return Locale.forLanguageTag(DEFAULT_LOCALE.replace("_", "-"));
    }

    // example: en,en-us;q=0.7, en-au;q=0.3
    // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    // Change the locale value to lower case because we store the language keys in lower case.
    String languageCode = localeHeaderValue.toLowerCase().split(",")[0];
    Locale locale = Locale.forLanguageTag(languageCode);
    String currentLang = null;
    for (String language : getAvailableLanguages()) {
        if (StringUtils.isNotEmpty(locale.toLanguageTag())
                && language.equalsIgnoreCase(locale.toLanguageTag())) {
            currentLang = language;
        } else if (StringUtils.isNotEmpty(locale.getLanguage()) && language.startsWith(locale.getLanguage())) {
            currentLang = language;
        }
    }
    if (currentLang == null) {
        currentLang = DEFAULT_LOCALE.replace("_", "-");
    }
    return Locale.forLanguageTag(currentLang);
}

From source file:us.askplatyp.kb.lucene.model.Context.java

@JsonCreator
public Context(@JsonProperty("@language") String languageCode) {
    this(Locale.forLanguageTag(languageCode));
}

From source file:nu.yona.server.properties.YonaProperties.java

public void setDefaultLocale(String defaultLocale) {
    this.defaultLocale = Locale.forLanguageTag(defaultLocale);
}

From source file:com.jslsolucoes.tagria.lib.servlet.Tagria.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uri = request.getRequestURI().replaceAll(";jsessionid=.*", "");
    String etag = DigestUtils.sha256Hex(uri);

    if (uri.endsWith("blank")) {
        response.setStatus(HttpServletResponse.SC_OK);
        return;//from  w  w w.  jav  a  2  s.  co m
    }

    if (uri.endsWith("locale")) {
        Config.set(request.getSession(), Config.FMT_LOCALE,
                Locale.forLanguageTag(request.getParameter("locale")));
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    if (request.getHeader("If-None-Match") != null && etag.equals(request.getHeader("If-None-Match"))) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    String charset = "utf-8";
    if (TagUtil.getInitParam(TagriaConfigParameter.ENCODING) != null) {
        charset = TagUtil.getInitParam(TagriaConfigParameter.ENCODING);
    }
    response.setCharacterEncoding(charset);
    try {

        DateTime today = new DateTime();
        DateTime expires = new DateTime().plusDays(CACHE_EXPIRES_DAY);

        if (uri.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (uri.endsWith(".js")) {
            response.setContentType("text/javascript");
        } else if (uri.endsWith(".png")) {
            response.setContentType("image/png");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH);

        if (Boolean.valueOf(TagUtil.getInitParam(TagriaConfigParameter.CDN_ENABLED))) {
            response.setHeader(HttpHeaderParameter.ACCESS_CONTROL_ALLOW_ORIGIN.getName(), "*");
        }

        response.setHeader(HttpHeaderParameter.ETAG.getName(), etag);
        response.setHeader(HttpHeaderParameter.EXPIRES.getName(), sdf.format(expires.toDate()));
        response.setHeader(HttpHeaderParameter.CACHE_CONTROL.getName(),
                "public,max-age=" + Seconds.secondsBetween(today, expires).getSeconds());

        String url = "/com/jslsolucoes"
                + uri.replaceFirst(request.getContextPath(), "").replaceAll(";jsessionid=.*", "");
        InputStream in = getClass().getResourceAsStream(url);
        IOUtils.copy(in, response.getOutputStream());
        in.close();

    } catch (Exception exception) {
        logger.error("Could not load resource", exception);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}