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:eu.europa.ec.grow.espd.controller.MessageSourceController.java

@RequestMapping(value = { "/translate",
        "/{flow:request|response}/{agent:ca|eo}/translate" }, method = RequestMethod.POST)
@ResponseBody//from w ww. j  av  a 2s.c  o  m
public String translate(@RequestParam(value = "labels[]") String[] labels, @RequestParam String lang)
        throws JsonProcessingException {
    Locale locale = Locale.forLanguageTag(lang);
    for (int i = 0; i < labels.length; i++) {
        if (isBlank(labels[i])) {
            continue;
        }
        labels[i] = ms.getMessage(labels[i], null, locale);
    }
    // TODO use MessageSourceResolvable to retrieve all labels at once
    return mapper.writeValueAsString(labels);
}

From source file:com.jslsolucoes.tagria.lib.util.TagUtil.java

public static Locale locale(JspContext jspContext) {
    HttpSession httpSession = ((PageContext) jspContext).getSession();
    Locale locale = Locale.forLanguageTag(getInitParam(TagriaConfigParameter.LOCALE));
    if (Config.get(httpSession, Config.FMT_LOCALE) != null) {
        locale = (Locale) Config.get(httpSession, Config.FMT_LOCALE);
    }/*ww w. j a  v a 2s  .c  o m*/
    return locale;
}

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

@Override
public Feature map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    Feature feature = new Feature();
    feature.setId((UUID) resultSet.getObject("id"));
    feature.setParentId((UUID) resultSet.getObject("parent_id"));
    feature.setSlug(resultSet.getString("slug"));
    feature.setTitle(resultSet.getString("title"));
    feature.setFeature(resultSet.getString("feature"));
    feature.setFeatureSlug(resultSet.getString("feature_slug"));

    if (MapperUtils.hasColumn("localization_data", resultSet)
            && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
        ObjectMapper mapper = new ObjectMapper();
        try {//from  ww  w  . j a  va2 s.c o m
            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"));
            }
            feature.setLocalizedVersions(localizedVersions);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }

    return feature;
}

From source file:com.haulmont.cuba.testsupport.TestUserSessionSource.java

@Override
public synchronized UserSession getUserSession() {
    if (exceptionOnGetUserSession) {
        throw new NoUserSessionException(UUID.fromString(USER_ID));
    }/*from   w  w w .  j  av  a2 s  . co m*/
    if (session == null) {
        User user = new User();
        user.setId(UUID.fromString(USER_ID));
        user.setLogin("test_admin");
        user.setName("Test Administrator");
        user.setPassword(DigestUtils.md5Hex("test_admin"));

        session = new UserSession(UUID.randomUUID(), user, Collections.<Role>emptyList(),
                Locale.forLanguageTag("en"), false);
    }
    return session;
}

From source file:io.github.xxyy.simplegiveall.SimpleGiveallMain.java

@Override
public final void onEnable() {
    initialiseConfig();/*from  www. j  a v  a  2 s. c o  m*/

    Locale locale = Locale.forLanguageTag(this.getConfig().getString("locale"));

    bundle = ResourceBundle.getBundle("io/github/xxyy/simplegiveall/simplegiveall", locale);

    this.getCommand(bundle.getString("GIVEALL")).setExecutor(this);

    System.out.println(LICENSE_HEADER);
}

From source file:uk.q3c.krail.i18n.DefaultPatternUtilityTest.java

@Test
public void writeOut_locales_provided_all_keys() throws IOException {
    //        given

    File testOutDir = new File(ResourceUtils.userTempDirectory(), "testOut");
    if (testOutDir.exists()) {
        FileUtils.deleteQuietly(testOutDir);
    }//from ww  w .j a v a  2  s.  c om
    File targetDir = new File(ResourceUtils.userTempDirectory(), "testOut/codeModel");
    writer.setOptionWritePath(targetDir);

    Set<Locale> locales = new HashSet<>();
    locales.add(Locale.GERMAN);
    locales.add(Locale.ITALIAN);
    locales.add(Locale.UK);
    locales.add(Locale.forLanguageTag(""));
    File referenceFile = new File(TestResource.testResourceRootDir("krail"), "Labels.ref");
    File targetFile = new File(targetDir, "Labels.java");
    File referenceFile_de = new File(TestResource.testResourceRootDir("krail"), "Labels_de.ref");
    File targetFile_de = new File(targetDir, "Labels_de.java");
    File referenceFile_it = new File(TestResource.testResourceRootDir("krail"), "Labels_it.ref");
    File targetFile_it = new File(targetDir, "Labels_it.java");
    File referenceFile_en_GB = new File(TestResource.testResourceRootDir("krail"), "Labels_en_GB.ref");
    File targetFile_en_GB = new File(targetDir, "Labels_en_GB.java");
    // this is to make sure that setting the default does not mess things up
    Locale.setDefault(Locale.CANADA_FRENCH);

    //when
    utility.writeOut(writer, LabelKey.class, locales, Optional.empty());
    //then line 4 is the timestamp
    assertThat(FileTestUtil.compare(referenceFile, targetFile, 4)).isEqualTo(Optional.empty());
    assertThat(FileTestUtil.compare(referenceFile_de, targetFile_de, 4)).isEqualTo(Optional.empty());
    assertThat(FileTestUtil.compare(referenceFile_it, targetFile_it, 4)).isEqualTo(Optional.empty());
    assertThat(FileTestUtil.compare(referenceFile_en_GB, targetFile_en_GB, 4)).isEqualTo(Optional.empty());
}

From source file:org.obiba.mica.micaConfig.rest.DataAccessResource.java

@GET
@Path("/form")
@Timed// w w w.j  a  va  2  s .  c o m
public Mica.DataAccessFormDto getDataAccessForm(@QueryParam("lang") String lang) {
    Optional<DataAccessForm> d = dataAccessFormService.find();

    if (!d.isPresent())
        throw NoSuchDataAccessFormException.withDefaultMessage();

    DataAccessForm dataAccessForm = d.get();
    Mica.DataAccessFormDto.Builder builder = Mica.DataAccessFormDto.newBuilder(dtos.asDto(dataAccessForm))
            .clearProperties().clearPdfTemplates();

    String langTag = !Strings.isNullOrEmpty(lang) ? Locale.forLanguageTag(lang).toLanguageTag()
            : LanguageTag.UNDETERMINED;

    Map<String, LocalizedString> properties = dataAccessForm.getProperties().entrySet().stream()
            .map(e -> Maps.immutableEntry(e.getKey(),
                    new LocalizedString().forLanguageTag(langTag, e.getValue().get(langTag))))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

    builder.addAllProperties(dtos.asDtoList(properties));

    return builder.build();
}

From source file:eu.trentorise.opendata.commons.TodUtils.java

/**
 * Converts a language code to Java Locale. On null input returns
 * {@link Locale#ROOT}/*www . j a  v  a2  s.  c  o m*/
 * 
 * Notice Java 7 introduced {@link Locale#forLanguageTag(String)}, but that
 * method throws null pointer exception on null string, which unfortunately
 * can happen quite often, so we use this method instead.
 * 
 * @see Locale#forLanguageTag(String)
 * @see #localeToLanguageTag(Locale) localeToLanguageTag(Locale) for the inverse operation
 */
public static Locale languageTagToLocale(@Nullable String languageTag) {

    if (languageTag == null) {
        LOG.warning("Found null locale, returning Locale.ROOT");
        return Locale.ROOT;
    }
    return Locale.forLanguageTag(languageTag);
}

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

@Test
public void testIsValid() {
    // Test the string version
    assertFalse("enIsInvalid", Languages.isValid("en"));
    assertTrue("en-USIsValid", Languages.isValid("en-US"));
    assertTrue("en-GBIsValid", Languages.isValid("en-GB"));
    assertTrue("zh-HansIsValid", Languages.isValid("zh-Hans"));
    assertFalse("cmn-HantIsInvalid", Languages.isValid("cmn-Hant"));
    assertFalse("EmptyIsInvalid", Languages.isValid(""));
    String code = null;/*  w  w  w . j a v  a  2 s .  c om*/
    assertFalse("NullIsInvalid", Languages.isValid(code));

    // Test the locale version
    assertTrue("enIsValid", Languages.isValid(Locale.forLanguageTag("en")));
    assertTrue("en-USIsValid", Languages.isValid(Locale.forLanguageTag("en-US")));
    assertTrue("en-GBIsValid", Languages.isValid(Locale.forLanguageTag("en-GB")));
    assertTrue("zh-HansIsValid", Languages.isValid(Locale.forLanguageTag("zh-Hans")));
    assertTrue("cmn-HantIsValid", Languages.isValid(Locale.forLanguageTag("cmn-Hant")));
    assertTrue("zh-CHIsValid", Languages.isValid(Locale.forLanguageTag("zh-CH")));
    assertTrue("zh-TWIsValid", Languages.isValid(Locale.forLanguageTag("zh-TH")));
    assertTrue("pt-PTIsValid", Languages.isValid(Locale.forLanguageTag("pt-PT")));
    assertTrue("no-NOIsValid", Languages.isValid(Locale.forLanguageTag("no-NO")));
    assertFalse("EmptyIsInvalid", Languages.isValid(Locale.forLanguageTag("")));
    Locale locale = null;
    assertFalse("NullIsInvalid", Languages.isValid(locale));
}

From source file:alfio.util.MustacheCustomTagInterceptor.java

private static Pair<String, Optional<Locale>> parseParams(String r) {

    int indexLocale = r.indexOf(LOCALE_LABEL),
            end = Math.min(r.length(), indexLocale != -1 ? indexLocale : r.length());
    String format = substring(r, r.indexOf(" "), end);

    //// w  ww .j  a v  a2s .  co  m
    String[] res = r.split("\\s+");
    Optional<Locale> locale = Arrays.asList(res).stream().filter((s) -> s.startsWith(LOCALE_LABEL)).findFirst()
            .map((l) -> {
                return Locale.forLanguageTag(substring(l, LOCALE_LABEL.length()));
            });
    //

    return Pair.of(format, locale);
}