Example usage for java.util Locale toLanguageTag

List of usage examples for java.util Locale toLanguageTag

Introduction

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

Prototype

public String toLanguageTag() 

Source Link

Document

Returns a well-formed IETF BCP 47 language tag representing this locale.

Usage

From source file:org.daxplore.presenter.server.servlets.PresenterServlet.java

private String getEmbedHTML(PersistenceManager pm, String prefix, Locale locale, String queryString,
        String baseurl, ServerPrefixProperties properties, String gaTemplate)
        throws BadRequestException, InternalServerException {

    QuestionMetadata questionMetadata;//from www.  ja v a  2s  .  c om
    String key = prefix + "_" + locale.toLanguageTag();
    if (metadataMap.containsKey(key)) {
        questionMetadata = metadataMap.get(key);
    } else {
        String questionText = TextFileStore.getFile(pm, prefix, "meta/questions", locale, ".json");
        questionMetadata = new QuestionMetadataServerImpl(new StringReader(questionText));
        metadataMap.put(key, questionMetadata);
    }

    QueryDefinition queryDefinition = new QueryDefinition(questionMetadata, queryString);
    String statItem = StatDataItemStore.getStats(pm, prefix, queryDefinition);

    LinkedList<String> questions = new LinkedList<>();
    questions.add(queryDefinition.getQuestionID());
    questions.add(queryDefinition.getPerspectiveID());

    String pageTitle = SettingItemStore.getLocalizedProperty(pm, prefix, "properties/usertexts", locale,
            "page_title");

    String questionString = StorageTools.getQuestionDefinitions(pm, prefix, questions, locale);

    String prefixProperties = properties.toJson().toJSONString();

    String[] arguments = { prefix, // {0}
            locale.toLanguageTag(), // {1}
            pageTitle, // {2}
            baseurl, // {3}
            gaTemplate, // {4}
            statItem, // {5}
            questionString, // {6}
            prefixProperties // {7}
    };

    if (embedHtmlTemplate == null) {
        try {
            embedHtmlTemplate = IOUtils
                    .toString(getServletContext().getResourceAsStream("/templates/embed.html"));
        } catch (IOException e) {
            throw new InternalServerException("Failed to load the embed html template", e);
        }
    }

    return MessageFormat.format(embedHtmlTemplate, (Object[]) arguments);
}

From source file:com.haulmont.cuba.web.App.java

protected Locale resolveLocale(@Nullable Locale requestLocale) {
    Map<String, Locale> locales = globalConfig.getAvailableLocales();

    if (globalConfig.getLocaleSelectVisible()) {
        String lastLocale = getCookieValue(COOKIE_LOCALE);
        if (lastLocale != null) {
            for (Locale locale : locales.values()) {
                if (locale.toLanguageTag().equals(lastLocale)) {
                    return locale;
                }//from w w  w  . j  a v  a  2s .  c om
            }
        }
    }

    if (requestLocale != null) {
        Locale requestTrimmedLocale = messageTools.trimLocale(requestLocale);
        if (locales.containsValue(requestTrimmedLocale)) {
            return requestTrimmedLocale;
        }

        // if not found and application locale contains country, try to match by language only
        if (!StringUtils.isEmpty(requestLocale.getCountry())) {
            Locale appLocale = Locale.forLanguageTag(requestLocale.getLanguage());
            for (Locale locale : locales.values()) {
                if (Locale.forLanguageTag(locale.getLanguage()).equals(appLocale)) {
                    return locale;
                }
            }
        }
    }

    // return default locale
    return messageTools.getDefaultLocale();
}

From source file:com.hangum.tadpole.login.core.dialog.LoginDialog.java

/**
 * register login id/* w  ww.ja va 2  s . c  o m*/
 */
private void registLoginID() {
    try {
        if (!btnCheckButton.getSelection()) {
            CookieUtils.deleteLoginCookie();
            return;
        }

        CookieUtils.saveCookie(PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK,
                Boolean.toString(btnCheckButton.getSelection()));
        CookieUtils.saveCookie(PublicTadpoleDefine.TDB_COOKIE_USER_ID, textEMail.getText());
        Locale locale = (Locale) comboLanguage.getData(comboLanguage.getText());
        CookieUtils.saveCookie(PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE, locale.toLanguageTag());
    } catch (Exception e) {
        logger.error("registe cookie", e);
    }
}

From source file:com.kaikoda.cah.TestDeck.java

@Test
public void testDeckGetLocale() throws SAXException, IOException, ParserConfigurationException {

    Deck customDeck = new Deck(this.getDocument("/data/test/cards/netherlands.xml"));

    Locale expected = Locale.forLanguageTag("en-nl");
    Locale result = customDeck.getLocale();

    assertEquals(expected, result);//from  w w  w.  ja  va  2s . c om
    assertEquals("en-NL", result.toLanguageTag());

}

From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java

/**
 * {@inheritDoc}// w  ww  .j ava2 s .  c o  m
 */
@Override
public String[] getAcceptableLocales() {
    ArrayList<String> retVal = new ArrayList<String>();
    Header[] hdrs = request.getHeaders("Accept-Language");
    if ((hdrs != null) && (hdrs.length > 0)) {
        // Store the accumulated languages that have been requested in a local collection, sorted by the quality value (so we can add Locales in descending order).
        // The values will be ArrayLists containing the corresponding Locales to be added
        TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<Double, ArrayList<Locale>>();
        for (Header hdr : hdrs)
            parseLocalesHeader(hdr.getValue(), locales);
        // Process the quality values in highest->lowest order (due to negating the Double value when creating the key)
        for (ArrayList<Locale> list : locales.values())
            for (Locale locale : list)
                retVal.add(locale.toLanguageTag());
        Collections.reverse(retVal);
    }
    retVal.add(Locale.getDefault().toLanguageTag());
    return retVal.toArray(new String[retVal.size()]);
}

From source file:com.haulmont.cuba.web.LoginWindow.java

protected Locale resolveLocale(App app) {
    if (globalConfig.getLocaleSelectVisible()) {
        String lastLocale = app.getCookieValue(COOKIE_LOCALE);
        if (lastLocale != null) {
            for (Locale locale : locales.values()) {
                if (locale.toLanguageTag().equals(lastLocale)) {
                    return locale;
                }//  w  ww  . j  a v  a  2s  .  c  o  m
            }
        }
    }

    for (Locale locale : locales.values()) {
        if (locale.equals(app.getLocale())) {
            return locale;
        }
    }

    // if not found and application locale contains country, try to match by language only
    if (!StringUtils.isEmpty(app.getLocale().getCountry())) {
        Locale appLocale = Locale.forLanguageTag(app.getLocale().getLanguage());
        for (Locale locale : locales.values()) {
            if (Locale.forLanguageTag(locale.getLanguage()).equals(appLocale)) {
                return locale;
            }
        }
    }
    // return first locale set in the cuba.availableLocales app property
    return locales.values().iterator().next();
}

From source file:org.daxplore.presenter.server.servlets.AdminPanelServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {//from w w  w  .ja va  2  s . c o  m
        Locale locale = new Locale("en");
        String pageTitle = "Daxplore Admin";

        if (adminHtmlTemplate == null) {
            try {
                adminHtmlTemplate = IOUtils
                        .toString(getServletContext().getResourceAsStream("/templates/admin.html"));
            } catch (IOException e) {
                throw new InternalServerException("Failed to load the html admin template", e);
            }
        }

        String baseurl = request.getRequestURL().toString();
        baseurl = baseurl.substring(0, baseurl.lastIndexOf("/") + 1);

        String[] arguments = { locale.toLanguageTag(), // {0}
                pageTitle, // {1}
                baseurl // {2}
        };

        try (Writer writer = response.getWriter()) {
            writer.write(MessageFormat.format(adminHtmlTemplate, (Object[]) arguments));
            writer.close();
        } catch (IOException e) {
            throw new InternalServerException(e);
        }
    } catch (InternalServerException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.smigo.message.MessageHandler.java

public void addNewYearNewsMessage(Optional<AuthenticatedUser> optionalUser, int year, List<Plant> plants,
        Locale locale) {
    final List<Integer> validYears = Arrays.asList(Year.now().getValue(), Year.now().plusYears(1).getValue());
    if (!optionalUser.isPresent() || !validYears.contains(year) || plants.size() < 10) {
        optionalUser.ifPresent(u -> log.info("Not adding new year news message for:" + u.getUsername()));
        return;/*w  w w  . ja v a2  s  .  c o  m*/
    }
    final AuthenticatedUser user = optionalUser.get();
    final MessageAdd message = new MessageAdd();
    final String text = messageSource.getMessage("msg.useraddedyearmessage",
            new Object[] { user.getUsername(), year }, locale);
    message.setText(text);
    message.setSubmitterUserId(1);
    message.setLocale(locale.toLanguageTag());
    messageDao.addMessage(message);
}

From source file:com.michellemay.mappings.MappingsFactory.java

private Mapping createCustomMapping(MappingConfig mappingConfig) {
    if (StringUtils.isBlank(mappingConfig.name)) {
        throw new IllegalArgumentException("Blank mapping name!");
    }/*from   w w w .ja  v  a2 s  .c o m*/

    Map<String, Locale> curMap = new TreeMap<String, Locale>(
            mappingConfig.casesensitive ? null : String.CASE_INSENSITIVE_ORDER);

    // Inherit all mappings from bases
    if (mappingConfig.extend != null) {
        for (String baseMappingName : mappingConfig.extend) {
            if (StringUtils.isBlank(baseMappingName) || !mappings.containsKey(baseMappingName)) {
                throw new IllegalStateException("Base mapping name '" + baseMappingName + "' does not exists!");
            }
            Mapping baseMapping = mappings.get(baseMappingName);
            baseMapping.getMapping().forEach(curMap::putIfAbsent);
        }
    }

    // Filter out unwanted languages
    if (StringUtils.isNotBlank(mappingConfig.filter)) {
        List<Locale.LanguageRange> priorityList = Locale.LanguageRange.parse(mappingConfig.filter);
        List<Locale> toKeep = Locale.filter(priorityList, curMap.values());
        curMap.entrySet().removeIf(e -> !toKeep.contains(e.getValue()));
    }

    // Add new values
    if (mappingConfig.add != null) {
        mappingConfig.add.forEach((lang, values) -> {
            Locale langLocale = LocaleUtils.toLocale(lang);
            String[] displayValues = values.split(",");
            for (String value : displayValues) {
                String cleanedValue = value.trim();
                if (!cleanedValue.isEmpty()) {
                    curMap.putIfAbsent(cleanedValue, langLocale);
                }
            }
        });
    }

    // Override values
    if (mappingConfig.override != null) {
        mappingConfig.override.forEach((lang, values) -> {
            Locale langLocale = LocaleUtils.toLocale(lang);

            // Remove all existing mappings
            String langTag = langLocale.toLanguageTag();
            curMap.entrySet().removeIf(e -> e.getValue().toLanguageTag().equals(langTag));

            // Add new mappings.
            String[] displayValues = values.split(",");
            for (String value : displayValues) {
                String cleanedValue = value.trim();
                if (!cleanedValue.isEmpty()) {
                    curMap.put(cleanedValue, langLocale);
                }
            }
        });
    }

    return new CustomMapping(mappingConfig.name.trim()).withCaseSensitive(mappingConfig.casesensitive)
            .withMapping(curMap);
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

public String generateLang() {

    StringBuilder lines = new StringBuilder();
    lines.append("var rubricsLang = {");

    Locale locale = rb.getLocale();
    Set properties = rb.keySet();
    lines.append("'" + locale.toLanguageTag() + "': {");
    Iterator keys = properties.iterator();
    while (keys.hasNext()) {
        String key = keys.next().toString();
        if (keys.hasNext()) {
            lines.append("'" + key + "': '" + rb.getString(key) + "',");
        } else {/*w  w  w .  ja va2s .  c om*/
            lines.append("'" + key + "': '" + rb.getString(key) + "'");
        }
    }

    lines.append("}");
    lines.append("}");

    log.debug(lines.toString());

    return lines.toString();
}