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:com.boyuanitsm.fort.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);/*from   w  w w. j  a  v a 2  s  .  co  m*/
    context.setVariable(BASE_URL, 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:nu.yona.server.ThymeleafConfigurationTest.java

@Test
public void emailTemplateEngine_processBuddyInvitationSubjectDutch_dutchTemplateFoundAndExpanded() {
    String result = buildEmailSubject(Optional.of(Locale.forLanguageTag("nl-NL")));

    assertThat(result, equalTo("Word vriend op Yona!"));
}

From source file:com.haulmont.chile.core.datatypes.Datatypes.java

private FormatStrings getFormat(Locale locale) {
    if (useLocaleLanguageOnly)
        locale = Locale.forLanguageTag(locale.getLanguage());
    return formatStringsMap.get(locale);
}

From source file:org.jooby.jackson.Json.java

@Override
public void configure(final Env mode, final Config config, final Binder binder) {
    Locale locale = Locale.forLanguageTag(config.getString("application.lang").replace("_", "-"));
    // Jackson clone the date format in order to make dateFormat thread-safe
    mapper.setDateFormat(new SimpleDateFormat(config.getString("application.dateFormat"), locale));
    mapper.setLocale(locale);/*from w  ww  .  j a  v a  2 s .c  o  m*/
    mapper.setTimeZone(TimeZone.getTimeZone(config.getString("application.tz")));

    // Jackson Modules from Guice
    Multibinder<Module> moduleBinder = Multibinder.newSetBinder(binder, Module.class);
    modules.forEach(m -> moduleBinder.addBinding().toInstance(m));

    binder.bind(ObjectMapper.class).toInstance(mapper);

    // Jackson Configurer (like a post construct)
    binder.bind(PostConfigurer.class).asEagerSingleton();

    // json body parser & formatter
    BodyHandler json = new BodyHandler(mapper, types);

    Multibinder.newSetBinder(binder, Body.Formatter.class).addBinding().toInstance(json);

    Multibinder.newSetBinder(binder, Body.Parser.class).addBinding().toInstance(json);

    // direct access?
    binder.bind(Key.get(Body.Formatter.class, Names.named(json.toString()))).toInstance(json);
    binder.bind(Key.get(Body.Parser.class, Names.named(json.toString()))).toInstance(json);

}

From source file:rapture.dp.invocable.calendar.steps.CalendarLookupStep.java

@Override
public String invoke(CallingContext ctx) {
    DecisionApi decision = Kernel.getDecision();
    try {/*from   w  w  w .  j a v  a2 s.co  m*/
        decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName());

        String dateStr = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DATE"));
        String calendar = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "CALENDAR"));
        String translator = StringUtils
                .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "TRANSLATOR"));
        if (translator == null)
            translator = StringUtils
                    .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DEFAULT_TRANSLATOR"));
        LocalDate date = (dateStr == null) ? LocalDate.now() : LocalDate.parse(dateStr);

        // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving
        // Expected format is a map of dates (with or without years) to names or lists of names
        // Example:
        // {
        // "31Dec" : ["New Tear's Eve", "Hogmanay"] ,
        // "05Sep2016" : "Labor Day",
        // "04Sep2017" : "Labor Day"
        // "2015-01-01" : "New Year's Day"
        // }

        Map<String, Object> calendarTable = new HashMap<>();
        if (calendar != null) {
            String calendarJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, calendar));
            if (calendarJson != null) {
                calendarTable = JacksonUtil.getMapFromJson(calendarJson);
            }
        }

        // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving
        Map<String, Object> translationTable = new HashMap<>();
        if (translator != null) {
            String translationJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, translator));
            if (translationJson != null) {
                translationTable = JacksonUtil.getMapFromJson(translationJson);
            }
        }

        List<String> lookup = new ArrayList<>();

        String languageTag = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "LOCALE"));
        Locale locale = (languageTag == null) ? Locale.getDefault() : Locale.forLanguageTag(languageTag);

        for (DateTimeFormatter formatter : ImmutableList.of(DateTimeFormatter.ISO_LOCAL_DATE,
                DateTimeFormatter.ofPattern("ddMMMuuuu", locale), DateTimeFormatter.ofPattern("ddMMM", locale),
                DateTimeFormatter.ofPattern("MMMdduuuu", locale), DateTimeFormatter.ofPattern("MMMdd", locale),
                DateTimeFormatter.ofPattern("uuuuMMMdd", locale))) {

            String formattedDate = date.format(formatter);
            Object transList = translationTable.get(formattedDate);
            if (transList != null) {
                if (transList instanceof Iterable) {
                    for (Object o : (Iterable) transList) {
                        lookup.add(o.toString());
                    }
                } else
                    lookup.add(transList.toString());
            }
            lookup.add(formattedDate);
        }
        lookup.add(DayOfWeek.from(date).getDisplayName(TextStyle.FULL, locale));

        decision.setContextLiteral(ctx, getWorkerURI(), "DATE_TRANSLATIONS",
                JacksonUtil.jsonFromObject(lookup));

        // Calendar table defines the priority. getMapFromJson returns a LinkedHashMap so order is preserved.
        for (Entry<String, Object> calEntry : calendarTable.entrySet()) {
            if (lookup.contains(calEntry.getKey())) {
                decision.setContextLiteral(ctx, getWorkerURI(), "CALENDAR_LOOKUP_ENTRY",
                        JacksonUtil.jsonFromObject(calEntry));
                decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                        calEntry.getKey() + " matched as " + calEntry.getValue().toString(), false);
                return calEntry.getValue().toString();
            }
        }
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), getStepName() + ": No matches for "
                + DateTimeFormatter.ISO_LOCAL_DATE.format(date) + " found in calendar", false);
        return getNextTransition();
    } catch (Exception e) {
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                "Unable to access the calendar : " + e.getLocalizedMessage());
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName() + "Error", ExceptionToString.summary(e));
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(),
                true);
        return getErrorTransition();
    }
}

From source file:org.pdfsam.context.DefaultI18nContext.java

private Locale getBestLocale() {
    String localeString = DefaultUserContext.getInstance().getLocale();
    if (StringUtils.isNotBlank(localeString)) {
        LOG.trace("Found locale string {}", localeString);
        return Locale.forLanguageTag(localeString);
    }/*  w  w  w  . j  a v  a 2  s  .c o m*/
    if (SUPPORTED_LOCALES.contains(Locale.getDefault())) {
        LOG.trace("Using default locale {}", Locale.getDefault());
        return Locale.getDefault();
    }
    Locale onlyLanguage = new Locale(Locale.getDefault().getLanguage());
    if (SUPPORTED_LOCALES.contains(onlyLanguage)) {
        LOG.trace("Using supported locale closest to default {}", onlyLanguage);
        return onlyLanguage;
    }
    LOG.trace("Using fallback locale");
    return Locale.UK;
}

From source file:it.uniud.ailab.dcore.wrappers.external.CybozuLanguageDetectorAnnotator.java

/**
 * Wraps the Cybozu lybrary and detects the most used probable language 
 * of the specified {@link it.uniud.ailab.dcore.persistence.DocumentComponent}.
 * Note: the component supports only components written in a single language
 * and with no children.//from ww  w  .  j  av a2  s  .  co  m
 * 
 * @param blackboard the current blackboard
 * @param component the component to analyze
 */
@Override
public void annotate(Blackboard blackboard, DocumentComponent component) {

    String lang = "";
    try {
        lang = detect(component.getText());
    } catch (LangDetectException ex) {
        throw new AnnotationException(this, "CybozuLanguageDetector - error during language detection", ex);
    }
    if (lang.isEmpty()) {
        throw new AnnotationException(this, "CybozuLanguageDetector could not detect a language");
    }
    Locale loc = Locale.forLanguageTag(lang);
    component.setLanguage(loc);
}

From source file:net.pms.configuration.PmsConfigurationTest.java

/**
 * Test Logging Configuration defaults//  w ww .  j  ava  2 s  .  c  om
 */
@Test
public void testLoggingConfigurationDefaults() {
    // Test defaults and valid values where applicable
    assertFalse("LogSearchCaseSensitiveDefault", configuration.getGUILogSearchCaseSensitive());
    assertFalse("LogSearchMultiLineDefault", configuration.getGUILogSearchMultiLine());
    assertFalse("LogSearchRegEx", configuration.getGUILogSearchRegEx());
    assertTrue("LogFileNameValid", FileUtil.isValidFileName(configuration.getDefaultLogFileName()));
    assertEquals("LogFileNameDefault", configuration.getDefaultLogFileName(), "debug.log");
    File file = new File(configuration.getDefaultLogFileFolder());
    assertTrue("DefaultLogFileFolder", file.isDirectory());
    file = new File(configuration.getDefaultLogFilePath());
    assertTrue("DefaultLogFilePath", configuration.getDefaultLogFilePath().endsWith("debug.log"));
    assertFalse("LoggingBufferedDefault", configuration.getLoggingBuffered());
    assertEquals("LoggingFilterConsoleDefault", configuration.getLoggingFilterConsole(), Level.INFO);
    assertEquals("LoggingFilterLogsTabDefault", configuration.getLoggingFilterLogsTab(), Level.INFO);
    assertEquals("LoggingLogsTabLinebufferDefault", configuration.getLoggingLogsTabLinebuffer(), 1000);
    assertTrue("LoggingLogsTabLinebufferLegal",
            configuration.getLoggingLogsTabLinebuffer() >= PmsConfiguration.LOGGING_LOGS_TAB_LINEBUFFER_MIN
                    && configuration
                            .getLoggingLogsTabLinebuffer() <= PmsConfiguration.LOGGING_LOGS_TAB_LINEBUFFER_MAX);
    assertEquals("LoggingSyslogFacilityDefault", configuration.getLoggingSyslogFacility(), "USER");
    assertEquals("LoggingSyslogHostDefault", configuration.getLoggingSyslogHost(), "");
    assertEquals("LoggingSyslogPortDefault", configuration.getLoggingSyslogPort(), 514);
    assertFalse("LoggingUseSyslogDefault", configuration.getLoggingUseSyslog());
    assertEquals("getLanguageLocaleDefault", configuration.getLanguageLocale(),
            Languages.toLocale(Locale.getDefault()));
    assertEquals("getLanguageTagDefault", configuration.getLanguageTag(),
            Languages.toLanguageTag(Locale.getDefault()));
    configuration.getConfiguration().setProperty("language", "");
    assertEquals("getLanguageLocaleDefault", configuration.getLanguageLocale(),
            Languages.toLocale(Locale.getDefault()));
    assertEquals("getLanguageTagDefault", configuration.getLanguageTag(),
            Languages.toLanguageTag(Locale.getDefault()));
    configuration.getConfiguration().setProperty("language", "en-GB");
    assertEquals("getLanguageLocaleBritishEnglish", configuration.getLanguageLocale(),
            Locale.forLanguageTag("en-GB"));
    assertEquals("getLanguageTagBritishEnglish", configuration.getLanguageTag(), "en-GB");
    configuration.getConfiguration().setProperty("language", "en");
    assertEquals("getLanguageLocaleEnglish", configuration.getLanguageLocale(), Locale.forLanguageTag("en-US"));
    assertEquals("getLanguageTagEnglish", configuration.getLanguageTag(), "en-US");
    configuration.getConfiguration().setProperty("language", "zh");
    assertEquals("getLanguageLocaleChinese", configuration.getLanguageLocale(),
            Locale.forLanguageTag("zh-Hant"));
    assertEquals("getLanguageTagChinese", configuration.getLanguageTag(), "zh-Hant");
    configuration.setLanguage(Locale.UK);
    assertEquals("setLanguageUK", configuration.getLanguageLocale(), Locale.forLanguageTag("en-GB"));
    configuration.setLanguage(Locale.SIMPLIFIED_CHINESE);
    assertEquals("setLanguageSimplifiedChinese", configuration.getLanguageLocale(),
            Locale.forLanguageTag("zh-Hans"));
    configuration.setLanguage(Locale.TRADITIONAL_CHINESE);
    assertEquals("setLanguageTraditionalChinese", configuration.getLanguageLocale(),
            Locale.forLanguageTag("zh-Hant"));
    Locale locale = null;
    configuration.setLanguage(locale);
    assertEquals("setLanguageNull", configuration.getLanguageLocale(), Locale.forLanguageTag("zh-Hant"));
    String code = null;
    configuration.setLanguage(code);
    assertEquals("setLanguageNull", configuration.getLanguageLocale(), Locale.forLanguageTag("zh-Hant"));
    configuration.setLanguage("");
    assertEquals("setLanguageEmpty", configuration.getLanguageLocale(), Locale.forLanguageTag("zh-Hant"));
    configuration.setLanguage("en");
    assertEquals("setLanguageEnglish", configuration.getLanguageLocale(), Locale.forLanguageTag("en-US"));
}

From source file:org.pdfsam.i18n.DefaultI18nContext.java

@EventListener
public void refresh(SetLocaleEvent e) {
    String localeString = e.getLocaleString();
    if (StringUtils.isNotBlank(localeString)) {
        LOG.trace("Setting default locale to {}", localeString);
        Optional.ofNullable(Locale.forLanguageTag(localeString)).filter(SUPPORTED_LOCALES::contains)
                .ifPresent(Locale::setDefault);
        refreshBundles();//from w w  w  .  jav  a 2 s  .co  m
    }
}

From source file:net.pms.util.LanguagesTest.java

@Test
public void testToLanguageCode() {
    // Test the string version
    assertEquals("EnIsen-US", Languages.toLanguageTag("En"), "en-US");
    assertEquals("EN-USIsen-US", Languages.toLanguageTag("EN-US"), "en-US");
    assertEquals("En-gBIsen-GB", Languages.toLanguageTag("En-gB"), "en-GB");
    assertEquals("zh-hansIszh-Hans", Languages.toLanguageTag("zh-hans"), "zh-Hans");
    assertEquals("cmn-HantIszh-Hant", Languages.toLanguageTag("cmn-HantIs"), "zh-Hant");
    assertNull("EmptyIsNull", Languages.toLanguageTag(""));
    String code = null;//from www  .ja  va2s .c  o m
    assertNull("NullIsNull", Languages.toLanguageTag(code));

    // Test the locale version
    assertEquals("enIsen-US", Languages.toLanguageTag(Locale.forLanguageTag("en")), "en-US");
    assertEquals("en-USIsen-US", Languages.toLanguageTag(Locale.forLanguageTag("en-US")), "en-US");
    assertEquals("en-GBIsen-GB", Languages.toLanguageTag(Locale.forLanguageTag("en-GB")), "en-GB");
    assertEquals("zh-HansIszh-Hans", Languages.toLanguageTag(Locale.forLanguageTag("zh-Hans")), "zh-Hans");
    assertEquals("cmn-HantIszh-Hant", Languages.toLanguageTag(Locale.forLanguageTag("cmn-Hant")), "zh-Hant");
    assertEquals("zh-CNIszh-Hans", Languages.toLanguageTag(Locale.forLanguageTag("zh-CN")), "zh-Hans");
    assertEquals("zh-SGIszh-Hans", Languages.toLanguageTag(Locale.forLanguageTag("zh-SG")), "zh-Hans");
    assertEquals("zh-TWIszh-Hant", Languages.toLanguageTag(Locale.forLanguageTag("zh-TW")), "zh-Hant");
    assertEquals("pt-PTIspt", Languages.toLanguageTag(Locale.forLanguageTag("pt-PT")), "pt");
    assertEquals("no-NOIsno", Languages.toLanguageTag(Locale.forLanguageTag("no-NO")), "no");
    assertNull("EmptyIsNull", Languages.toLanguageTag(Locale.forLanguageTag("")));
    Locale locale = null;
    assertNull("NullIsNull", Languages.toLanguageTag(locale));
}