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:io.wcm.testing.mock.aem.MockPageTest.java

@Test
public void testGetLanguage() {
    Page profilesPage = context.pageManager().getPage("/content/sample/en/toolbar/profiles");

    // set language in site root
    ModifiableValueMap props = this.page.getContentResource().adaptTo(ModifiableValueMap.class);
    props.put(JcrConstants.JCR_LANGUAGE, "fr_FR");

    // test get language from content
    Locale locale = profilesPage.getLanguage(false);
    assertEquals(Locale.forLanguageTag("fr-FR"), locale);

    // test get language from path
    locale = profilesPage.getLanguage(true);
    assertEquals(Locale.forLanguageTag("en"), locale);
}

From source file:alfio.controller.api.admin.AdminReservationApiController.java

private TicketReservationDescriptor toReservationDescriptor(String reservationId,
        Triple<TicketReservation, List<Ticket>, Event> triple) {
    List<SerializablePair<TicketCategory, List<Ticket>>> tickets = triple.getMiddle().stream()
            .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream()
            .map(entry -> SerializablePair.of(
                    eventManager.getTicketCategoryById(entry.getKey(), triple.getRight().getId()),
                    entry.getValue()))/*from w  w w  . ja  v a2s  . co  m*/
            .collect(Collectors.toList());
    TicketReservation reservation = triple.getLeft();
    return new TicketReservationDescriptor(reservation, ticketReservationManager.orderSummaryForReservationId(
            reservationId, triple.getRight(), Locale.forLanguageTag(reservation.getUserLanguage())), tickets);
}

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;
                }/*w  ww. j  a  v a2 s .  c o  m*/
            }
        }
    }

    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.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody/*from   w w  w . j a  v  a2 s.com*/
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:com.hurence.logisland.processor.ModifyId.java

@Override
public void init(ProcessContext context) {
    super.init(context);
    if (context.getPropertyValue(STRATEGY).isSet()) {
        if (context.getPropertyValue(STRATEGY).getRawValue().equals(RANDOM_UUID_STRATEGY.getValue())) {
            idBuilder = new IdBuilder() {
                @Override/*  ww w.j  a va  2 s  . c o  m*/
                public void buildId(Record record) {
                    record.setId(UUID.randomUUID().toString());
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue().equals(HASH_FIELDS_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));

            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            if (record.hasField(fieldName))
                                stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        record.setId(Hex.encodeHexString(digested));
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(JAVA_FORMAT_STRING_WITH_FIELDS_STRATEGY.getValue())) {
            final String[] fieldsForFormat = context.getPropertyValue(FIELDS_TO_USE).asString().split(",");
            final String format = context.getPropertyValue(JAVA_FORMAT_STRING).asString();
            final Locale local = Locale.forLanguageTag(context.getPropertyValue(LANGUAGE_TAG).asString());
            idBuilder = new IdBuilder() {
                @Override
                public void buildId(Record record) {
                    final Object[] valuesForFormat = new Object[fieldsForFormat.length];
                    for (int i = 0; i < valuesForFormat.length; i++) {
                        if (!record.hasField(fieldsForFormat[i])) {
                            List<String> fieldsName = Lists.newArrayList(fieldsForFormat);
                            record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(),
                                    String.format(
                                            "could not build id with format : '%s' \nfields: '%s' \n because "
                                                    + "field: '%s' does not exist",
                                            format, fieldsName, fieldsForFormat[i]));
                            return;
                        }
                        valuesForFormat[i] = record.getField(fieldsForFormat[i]).getRawValue();
                    }
                    try {
                        record.setId(String.format(local, format, valuesForFormat));
                    } catch (IllegalFormatException e) {
                        // If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments,
                        // insufficient arguments given the format string, or other illegal conditions.
                        // For specification of all possible formatting errors, see the Details section of the formatter class specification.
                        record.addError(ProcessError.STRING_FORMAT_ERROR.getName(), e.getMessage());
                    } catch (NullPointerException e) {//should not happen
                        record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(), e.getMessage());
                    }
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(TYPE_TIME_HASH_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));
            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        final String hashString = new String(digested, charset);
                        final String recordType = record.getField(FieldDictionary.RECORD_TYPE).asString();
                        final String recordTime = record.getField(FieldDictionary.RECORD_TIME).asString();
                        final String newId = String.format("%s-%s-%s", recordType, recordTime, hashString);
                        record.setId(newId);
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        }
    }
}

From source file:de.flashpixx.rrd_antlr4.CMain.java

/**
 * initialize all data//from   w w  w.ja va  2  s  .c o  m
 *
 * @param p_locale locale
 * @param p_outputdirectory output directory string
 * @param p_templates template string array
 * @param p_imports import string array
 * @param p_excludes exclude string array
 * @param p_docclean documentation clean array
 * @return 5-tuple with initialized and converted data
 */
private static Tuple5<File, Set<ETemplate>, Set<File>, Set<String>, Set<String>> initialize(
        final String p_locale, final String p_outputdirectory, final String[] p_templates,
        final String[] p_imports, final String[] p_excludes, final String[] p_docclean) {
    CCommon.language(
            (p_locale == null) || (p_locale.isEmpty()) ? Locale.getDefault() : Locale.forLanguageTag(p_locale));

    return new Tuple5<>(new File(p_outputdirectory),

            (p_templates == null) || (p_templates.length == 0) ? Collections.<ETemplate>emptySet()
                    : Collections.unmodifiableSet(Arrays.stream(p_templates)
                            .map(i -> ETemplate.valueOf(i.trim().toUpperCase())).collect(Collectors.toSet())),

            (p_imports == null) || (p_imports.length == 0) ? Collections.<File>emptySet()
                    : Collections.unmodifiableSet(
                            Arrays.stream(p_imports).map(String::trim).filter(i -> !i.isEmpty()).map(File::new)
                                    .flatMap(i -> CMain.filelist(i, Collections.<File>emptySet(),
                                            Collections.<String>emptySet()))
                                    .collect(Collectors.toSet())),

            (p_excludes == null) || (p_excludes.length == 0) ? Collections.<String>emptySet()
                    : Collections.unmodifiableSet(Arrays.stream(p_excludes).map(String::trim)
                            .filter(i -> !i.isEmpty()).collect(Collectors.toSet())),

            (p_docclean == null) || (p_docclean.length == 0) ? Collections.<String>emptySet()
                    : Collections.unmodifiableSet(Arrays.stream(p_docclean).flatMap(i -> {
                        try {
                            return FileUtils.readLines(new File(i), Charset.defaultCharset()).stream();
                        } catch (final IOException l_exception) {
                            return Stream.of("");
                        }
                    }).map(String::trim).filter(i -> !i.isEmpty()).collect(Collectors.toSet())));
}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.RegistrationManager.java

/**
 * @param existing//from   w ww  . ja  v a  2 s  .c om
 * @param key
 * @throws RegistrationException 
 */
private void sendResetMail(Registration reg, String key) throws RegistrationException {
    RegistrationBean user = new RegistrationBean(reg.getEmail(), reg.getName(), reg.getSurname());
    String lang = reg.getLang();
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("user", user);
    vars.put("url", applicationURL + "/internal/confirm?confirmationCode=" + key);
    String subject = messageSource.getMessage("reset.subject", null, Locale.forLanguageTag(reg.getLang()));
    sender.sendEmail(reg.getEmail(), "reset_" + lang, subject, vars);
}

From source file:org.obiba.mica.access.service.DataAccessRequestService.java

public byte[] getRequestPdf(String id, String lang) {
    DataAccessRequest dataAccessRequest = findById(id);
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    Object content = defaultConfiguration().jsonProvider().parse(dataAccessRequest.getContent());
    try {//from   w  ww.  j a  v  a  2 s. com
        fillPdfTemplateFromRequest(getTemplate(Locale.forLanguageTag(lang)), ba, content);
    } catch (IOException | DocumentException e) {
        throw Throwables.propagate(e);
    }

    return ba.toByteArray();
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * {@link ResourceBundle} correspondente a uma {@link Locale}.<br>
 * {@link ResourceBundle#getBaseBundleName()} == {@link #getPropriedade(String) propriedade} "ResourceBundle.BaseName"<br>
 * {@link PropertyResourceBundle}'s (arquivos ".properties") devem estar codificados conforme {@link #getPropriedade(String) propriedade} "ResourceBundle.Charset". Veja {@link ResourceBundleCharsetControl}.
 * @param linguagem Formato IETF BCP 47. Veja {@link Locale#toLanguageTag()}. {@code null} ou {@code vazio} == {@link IpeRoxo#getPropriedade(String) propriedade} "ResourceBundle.Locale.Default".
 * @see #getMensagem(String, String, Object...)
 *///from   w w w . j a  v a 2  s  . c o  m
public static ResourceBundle getResourceBundle(String linguagem) throws IOException {

    final boolean padrao = StringUtil.tamanho(linguagem) == 0;

    if (padrao)
        linguagem = getPropriedade("ResourceBundle.Locale.Default", "pt");
    else
        linguagem = linguagem.replace('_', '-');

    ResourceBundle rb = mensagens.get(linguagem);
    if (rb != null)
        return rb;

    String baseName = getPropriedade("ResourceBundle.BaseName", "Mensagens");

    try {

        rb = ResourceBundle.getBundle(baseName, Locale.forLanguageTag(linguagem),
                new ResourceBundleCharsetControl(getPropriedade("ResourceBundle.Charset", "UTF-8")));

        mensagens.put(linguagem, rb);
        return rb;

    } catch (MissingResourceException e) {

        if (padrao) {
            throw new IOException(e);
        } else {
            return getResourceBundle(null);
        }

    }

}

From source file:alfio.manager.AdminReservationManager.java

@Transactional
public Result<Boolean> notify(String eventName, String reservationId, AdminReservationModification arm,
        String username) {/*from ww w. j  ava2 s . c o  m*/
    AdminReservationModification.Notification notification = arm.getNotification();
    return eventRepository.findOptionalByShortName(eventName).flatMap(e -> optionally(() -> {
        eventManager.checkOwnership(e, username, e.getOrganizationId());
        return e;
    }).flatMap(ev -> ticketReservationRepository.findOptionalReservationById(reservationId)
            .map(r -> Pair.of(e, r)))).map(pair -> {
                Event event = pair.getLeft();
                TicketReservation reservation = pair.getRight();
                if (notification.isCustomer()) {
                    ticketReservationManager.sendConfirmationEmail(event, reservation,
                            Locale.forLanguageTag(reservation.getUserLanguage()));
                }
                if (notification.isAttendees()) {
                    ticketRepository.findTicketsInReservation(reservationId).stream()
                            .filter(Ticket::getAssigned).forEach(t -> {
                                Locale locale = Locale.forLanguageTag(t.getUserLanguage());
                                ticketReservationManager.sendTicketByEmail(t, locale, event,
                                        ticketReservationManager.getTicketEmailGenerator(event, reservation,
                                                locale));
                            });
                }
                return Result.success(true);
            }).orElseGet(() -> Result.error(ErrorCode.EventError.NOT_FOUND));

}