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.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected Locale resolveLocale(HttpServletRequest req, Messages messages, GlobalConfig globalConfig) {
    Map<String, Locale> locales = globalConfig.getAvailableLocales();

    if (globalConfig.getLocaleSelectVisible()) {
        String lastLocale = getCookieValue(req, "LAST_LOCALE");
        if (lastLocale != null) {
            for (Locale locale : locales.values()) {
                if (locale.toLanguageTag().equals(lastLocale)) {
                    return locale;
                }/*  w  w  w  .j  av a 2 s  .c  om*/
            }
        }
    }

    Locale requestLocale = req.getLocale();
    if (requestLocale != null) {
        Locale requestTrimmedLocale = messages.getTools().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 messages.getTools().getDefaultLocale();
}

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

/**
 * initialize cookie data//from  w w  w .  j  av  a  2 s. co m
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                Locale locale = Locale.forLanguageTag(cookie.getValue());
                comboLanguage.setText(locale.getDisplayLanguage(locale));
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 3)
                return;
        }
    }

    // ? ? .
    comboLanguage.select(0);
    changeUILocale(comboLanguage.getText());
}

From source file:com.haulmont.cuba.core.global.MessageTools.java

/**
 * Trims locale to language-only if {@link #useLocaleLanguageOnly()} is true.
 * @param locale    a locale//from  ww w .  j  a va 2  s .  c  o  m
 * @return          the locale with the same language and empty country and variant
 */
public Locale trimLocale(Locale locale) {
    return useLocaleLanguageOnly() ? Locale.forLanguageTag(locale.getLanguage()) : locale;
}

From source file:alfio.manager.AdminReservationManager.java

private Result<Pair<TicketReservation, List<Ticket>>> createReservation(Result<List<TicketsInfo>> input,
        Event event, AdminReservationModification arm) {
    final TicketsInfo empty = new TicketsInfo(null, null, false, false);
    return input.flatMap(t -> {
        String reservationId = UUID.randomUUID().toString();
        String specialPriceSessionId = UUID.randomUUID().toString();
        Date validity = Date.from(arm.getExpiration().toZonedDateTime(event.getZoneId()).toInstant());
        ticketReservationRepository.createNewReservation(reservationId, validity, null, arm.getLanguage(),
                event.getId(), event.getVat(), event.isVatIncluded());
        AdminReservationModification.CustomerData customerData = arm.getCustomerData();
        ticketReservationRepository.updateTicketReservation(reservationId,
                TicketReservationStatus.PENDING.name(), customerData.getEmailAddress(),
                customerData.getFullName(), customerData.getFirstName(), customerData.getLastName(),
                arm.getLanguage(), null, null, null);

        Result<List<Ticket>> result = flattenTicketsInfo(event, empty, t)
                .map(pair -> reserveForTicketsInfo(event, arm, reservationId, specialPriceSessionId, pair))
                .reduce(this::reduceReservationResults)
                .orElseGet(() -> Result.error(ErrorCode.custom("", "unknown error")));

        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event,
                Locale.forLanguageTag(arm.getLanguage()));
        ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId,
                Json.toJson(orderSummary));

        return result
                .map(list -> Pair.of(ticketReservationRepository.findReservationById(reservationId), list));
    });/*from  www . j a v  a  2 s  . c  o  m*/
}

From source file:org.structr.common.SecurityContext.java

/**
 * Determine the effective locale for this request.
 *
 * Priority 1: URL parameter "locale" Priority 2: User locale  3: Browser locale  4: Default locale
 *
 * @return locale//from   www. jav a2  s . c  om
 */
public Locale getEffectiveLocale() {

    Locale locale = Locale.getDefault();
    boolean userHasLocaleString = false;

    if (cachedUser != null) {

        final String userLocaleString = cachedUser.getProperty(Principal.locale);

        if (userLocaleString != null) {
            userHasLocaleString = true;

            try {
                locale = LocaleUtils.toLocale(userLocaleString);
            } catch (IllegalArgumentException e) {
                locale = Locale.forLanguageTag(userLocaleString);
            }
        }

    }

    if (request != null) {

        if (!userHasLocaleString) {
            locale = request.getLocale();
        }

        // Overwrite locale if requested by URL parameter
        String requestedLocaleString = request.getParameter(LOCALE_KEY);
        if (StringUtils.isNotBlank(requestedLocaleString)) {
            try {
                locale = LocaleUtils.toLocale(requestedLocaleString);
            } catch (IllegalArgumentException e) {
                locale = Locale.forLanguageTag(requestedLocaleString);
            }
        }

    }

    return locale;
}

From source file:de.hybris.platform.print.facades.impl.DefaultPrintCollaborationFacadeTest.java

@Test
public void testCreateReplyWithStateChange() {
    //create a job for this test case
    printCollaborationFacade.createJob(getCommentModel(), getDummyAttachment(), getUserModel());

    //get the beginning action and its comments
    final WorkflowActionModel startAction = printCollaborationFacade.getCurrentAction(getCommentModel());
    assertEquals("First action is not a ToDo.", "To be done", startAction.getName(Locale.forLanguageTag("en")));

    //ensure state can be changed
    userService.setCurrentUser((UserModel) startAction.getPrincipalAssigned());

    //switch to the first decision we will find
    final Collection<WorkflowDecisionModel> decisions = startAction.getDecisions();

    final WorkflowDecisionModel decision = decisions.iterator().next();
    workflowProcessingService.decideAction(startAction, decision);

    //call function to test with the selected decision
    printCollaborationFacade.createReply(getCommentModel(), userService.getCurrentUser(),
            "reply with state change", decision);

    //get the created reply
    final List<ReplyModel> replies = getCommentModel().getReplies();

    assertThat(replies).isNotEmpty();//from ww  w .j  a v a  2s .  co  m

    final ReplyModel reply = Iterables.getFirst(replies, null);

    //does the reply contain the correct text?
    if (!"reply with state change".equals(reply.getText())) {
        fail("reply has wrong text");
    }

    //reply should not be deletable...
    assertThat(printCollaborationFacade.isDeleteAllowed(reply)).isFalse();
}

From source file:com.marklogic.semantics.sesame.client.MarkLogicClientImpl.java

/**
 * bind object//from   w ww  .  jav a2s .  c om
 *
 * @param qdef
 * @param variableName
 * @param object
 * @return
 * @throws MarkLogicSesameException
 */
private static SPARQLQueryDefinition bindObject(SPARQLQueryDefinition qdef, String variableName, Value object)
        throws MarkLogicSesameException {
    SPARQLBindings bindings = qdef.getBindings();
    if (object != null) {
        if (object instanceof URI) {
            bindings.bind(variableName, object.stringValue());
        } else if (object instanceof Literal) {
            Literal lit = (Literal) object;
            if (lit.getLanguage() != null) {
                String languageTag = lit.getLanguage();
                bindings.bind(variableName, lit.getLabel(), Locale.forLanguageTag(languageTag));
            } else if (((Literal) object).getDatatype() != null) {
                try {
                    String xsdType = lit.getDatatype().toString();
                    String fragment = new java.net.URI(xsdType).getFragment();
                    bindings.bind(variableName, lit.getLabel(), RDFTypes.valueOf(fragment.toUpperCase()));
                } catch (URISyntaxException e) {
                    logger.error(e.getLocalizedMessage());
                    throw new MarkLogicSesameException("Problem with object datatype.");
                }
            } else {
                // assume we have a string value
                bindings.bind(variableName, lit.getLabel(), RDFTypes.STRING);
            }
        }
        qdef.setBindings(bindings);
    }
    return qdef;
}

From source file:org.alfresco.solr.query.AbstractQParser.java

protected Pair<SearchParameters, Boolean> getSearchParameters() {
    SearchParameters searchParameters = new SearchParameters();

    Boolean isFilter = Boolean.FALSE;

    Iterable<ContentStream> streams = req.getContentStreams();

    JSONObject json = (JSONObject) req.getContext().get(ALFRESCO_JSON);

    if (json == null) {
        if (streams != null) {

            try {
                Reader reader = null;
                for (ContentStream stream : streams) {
                    reader = new BufferedReader(new InputStreamReader(stream.getStream(), "UTF-8"));
                }//from   w  w  w  .  j av a  2 s  . co  m

                // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
                if (reader != null) {
                    json = new JSONObject(new JSONTokener(reader));
                    req.getContext().put(ALFRESCO_JSON, json);
                }
            } catch (JSONException e) {
                // This is expected when there is no json element to the request
            } catch (IOException e) {
                throw new AlfrescoRuntimeException("IO Error parsing query parameters", e);
            }
        }
    }

    if (json != null) {
        try {
            if (getString() != null) {
                if (getString().equals(AUTHORITY_FILTER_FROM_JSON)) {
                    isFilter = Boolean.TRUE;

                    ArrayList<String> tenantList = new ArrayList<String>(1);
                    JSONArray tenants = json.getJSONArray("tenants");
                    for (int i = 0; i < tenants.length(); i++) {
                        String tenantString = tenants.getString(i);
                        tenantList.add(tenantString);
                    }

                    ArrayList<String> authorityList = new ArrayList<String>(1);
                    JSONArray authorities = json.getJSONArray("authorities");
                    for (int i = 0; i < authorities.length(); i++) {
                        String authorityString = authorities.getString(i);
                        authorityList.add(authorityString);
                    }

                    char separator = getSeparator(authorityList);

                    StringBuilder authQuery = new StringBuilder();
                    StringBuilder denyQuery = new StringBuilder();

                    for (String tenant : tenantList) {
                        for (String authority : authorityList) {
                            if (separator == 0) {
                                if (authQuery.length() > 0) {
                                    authQuery.append(" ");
                                    denyQuery.append(" ");
                                }
                                switch (AuthorityType.getAuthorityType(authority)) {
                                case USER:
                                    authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                    denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                    break;
                                case GROUP:
                                case EVERYONE:
                                case GUEST:
                                    if (tenant.length() == 0) {
                                        // Default tenant matches 4.0
                                        authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                        denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                    } else {
                                        authQuery.append("|AUTHORITY:\"").append(authority).append("@")
                                                .append(tenant).append("\"");
                                        denyQuery.append("|DENIED:\"").append(authority).append("@")
                                                .append(tenant).append("\"");
                                    }
                                    break;
                                default:
                                    authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                    denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                    break;
                                }
                            } else {
                                if (authQuery.length() == 0) {
                                    authset = true;
                                    authQuery.append("|AUTHSET:\"");
                                    denyQuery.append("|DENYSET:\"");
                                }

                                switch (AuthorityType.getAuthorityType(authority)) {
                                case USER:
                                    authQuery.append(separator).append(authority);
                                    denyQuery.append(separator).append(authority);
                                    break;
                                case GROUP:
                                case EVERYONE:
                                case GUEST:
                                    if (tenant.length() == 0) {
                                        // Default tenant matches 4.0
                                        authQuery.append(separator).append(authority);
                                        denyQuery.append(separator).append(authority);
                                    } else {
                                        authQuery.append(separator).append(authority).append("@")
                                                .append(tenant);
                                        denyQuery.append(separator).append(authority).append("@")
                                                .append(tenant);
                                    }
                                    break;
                                default:
                                    authQuery.append(separator).append(authority);
                                    denyQuery.append(separator).append(authority);
                                    break;
                                }
                            }

                        }
                    }
                    if (separator != 0) {
                        authQuery.append("\"");
                        denyQuery.append("\"");
                    }

                    if (authQuery.length() > 0) {
                        // Default to true for safety reasons.
                        final boolean anyDenyDenies = json.optBoolean("anyDenyDenies", true);

                        if (anyDenyDenies) {
                            authQuery.insert(0, "(").append(") AND NOT (").append(denyQuery).append(")");
                            // Record that the clause has been added.
                            // We only ever set this to true for solr4+
                            req.getContext().put("processedDenies", Boolean.TRUE);
                        }
                        searchParameters.setQuery(authQuery.toString());
                    }
                } else if (getString().equals(TENANT_FILTER_FROM_JSON)) {
                    isFilter = Boolean.TRUE;

                    ArrayList<String> tenantList = new ArrayList<String>(1);
                    JSONArray tenants = json.getJSONArray("tenants");
                    for (int i = 0; i < tenants.length(); i++) {
                        String tenantString = tenants.getString(i);
                        tenantList.add(tenantString);
                    }

                    StringBuilder tenantQuery = new StringBuilder();
                    for (String tenant : tenantList) {
                        if (tenantQuery.length() > 0) {
                            tenantQuery.append(" ");
                        }

                        if (tenant.length() > 0)

                        {
                            tenantQuery.append("|TENANT:\"").append(tenant).append("\"");
                        } else {
                            // TODO: Need to check for the default tenant or no tenant (4.0) or we force a reindex
                            // requirement later ...
                            // Better to add default tenant to the 4.0 index
                            tenantQuery.append("|TENANT:\"").append("_DEFAULT_").append("\"");
                            // tenantQuery.append(" |(+ISNODE:T -TENANT:*)");
                        }

                    }
                    searchParameters.setQuery(tenantQuery.toString());
                } else if (getString().equals(RERANK_QUERY_FROM_CONTEXT)) {
                    String searchTerm = getParam("spellcheck.q");
                    searchParameters.setQuery(searchTerm);
                }
            } else {
                String query = json.getString("query");
                if (query != null) {
                    searchParameters.setQuery(query);
                }
            }

            JSONArray locales = json.getJSONArray("locales");
            for (int i = 0; i < locales.length(); i++) {
                String localeString = locales.getString(i);
                Locale locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, localeString);
                searchParameters.addLocale(locale);
            }

            JSONArray templates = json.getJSONArray("templates");
            for (int i = 0; i < templates.length(); i++) {
                JSONObject template = templates.getJSONObject(i);
                String name = template.getString("name");
                String queryTemplate = template.getString("template");
                searchParameters.addQueryTemplate(name, queryTemplate);
            }

            JSONArray allAttributes = json.getJSONArray("allAttributes");
            for (int i = 0; i < allAttributes.length(); i++) {
                String allAttribute = allAttributes.getString(i);
                searchParameters.addAllAttribute(allAttribute);
            }

            searchParameters.setDefaultFTSOperator(Operator.valueOf(json.getString("defaultFTSOperator")));
            searchParameters
                    .setDefaultFTSFieldConnective(Operator.valueOf(json.getString("defaultFTSFieldOperator")));
            if (json.has("mlAnalaysisMode")) {
                searchParameters.setMlAnalaysisMode(MLAnalysisMode.valueOf(json.getString("mlAnalaysisMode")));
            }
            searchParameters.setNamespace(json.getString("defaultNamespace"));

            JSONArray textAttributes = json.getJSONArray("textAttributes");
            for (int i = 0; i < textAttributes.length(); i++) {
                String textAttribute = textAttributes.getString(i);
                searchParameters.addAllAttribute(textAttribute);
            }

            searchParameters.setQueryConsistency(QueryConsistency.valueOf(json.getString("queryConsistency")));

        } catch (JSONException e) {
            // This is expected when there is no json element to the request
        }
    }

    if (json != null) {
        if (log.isDebugEnabled()) {
            log.debug(json.toString());
        }
    }

    if (searchParameters.getQuery() == null) {
        searchParameters.setQuery(getString());
    }

    if (searchParameters.getLocales().size() == 0) {
        searchParameters.addLocale(I18NUtil.getLocale());
    }

    String defaultField = getParam(CommonParams.DF);
    if (defaultField != null) {
        searchParameters.setDefaultFieldName(defaultField);
    }

    if (autoDetectQueryLocale) {
        String searchTerm = getParam("spellcheck.q");
        if (searchTerm != null) {
            searchParameters.setSearchTerm(searchTerm);
            List<DetectedLanguage> detetcted = detectLanguage(searchTerm);
            if ((detetcted != null) && (detetcted.size() > 0)) {
                Locale detectedLocale = Locale.forLanguageTag(detetcted.get(0).getLangCode());
                if (localeIsNotIncluded(searchParameters, detectedLocale)) {
                    searchParameters.addLocale(Locale.forLanguageTag(detectedLocale.getLanguage()));
                }
            }

        }
    }

    if (fixedQueryLocales.size() > 0) {
        for (String locale : fixedQueryLocales) {
            searchParameters.addLocale(Locale.forLanguageTag(locale));
        }
    }

    // searchParameters.setMlAnalaysisMode(getMLAnalysisMode());
    searchParameters.setNamespace(NamespaceService.CONTENT_MODEL_1_0_URI);

    return new Pair<SearchParameters, Boolean>(searchParameters, isFilter);
}

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

@GET
@Path("/languages")
@Timed//from   www  .  j  a  va 2  s .  c  o  m
@RequiresAuthentication
public Map<String, String> getAvailableLanguages(@QueryParam("locale") @DefaultValue("en") String languageTag) {
    Locale locale = Locale.forLanguageTag(languageTag);
    return Arrays.stream(Locale.getISOLanguages())
            .collect(Collectors.toMap(lang -> lang, lang -> new Locale(lang).getDisplayLanguage(locale)));
}

From source file:org.apache.marmotta.kiwi.io.KiWiIO.java

/**
 * Read a KiWiStringLiteral serialized with writeStringLiteral from a DataInput source
 *
 * @param input the source/*from  w  ww  .j  a  v a  2s. c om*/
 * @return the de-serialized KiWiStringLiteral
 * @throws IOException
 */
public static KiWiStringLiteral readStringLiteral(DataInput input) throws IOException {
    long id = input.readLong();

    if (id == -1) {
        return null;
    } else {
        String content = readContent(input);
        byte langB = input.readByte();
        String lang;

        switch (langB) {
        case LANG_EN:
            lang = "en";
            break;
        case LANG_DE:
            lang = "de";
            break;
        case LANG_FR:
            lang = "fr";
            break;
        case LANG_ES:
            lang = "es";
            break;
        case LANG_IT:
            lang = "it";
            break;
        case LANG_PT:
            lang = "pt";
            break;
        case LANG_NL:
            lang = "nl";
            break;
        case LANG_SV:
            lang = "sv";
            break;
        case LANG_NO:
            lang = "no";
            break;
        case LANG_FI:
            lang = "fi";
            break;
        case LANG_RU:
            lang = "ru";
            break;
        case LANG_DK:
            lang = "dk";
            break;
        case LANG_PL:
            lang = "pl";
            break;
        default:
            lang = DataIO.readString(input);
        }

        KiWiUriResource dtype = readURI(input);

        Date created = new Date(input.readLong());

        KiWiStringLiteral r = new KiWiStringLiteral(content, lang != null ? Locale.forLanguageTag(lang) : null,
                dtype, created);
        r.setId(id);

        return r;
    }
}