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:com.haulmont.cuba.security.idp.IdpServiceBean.java

@Nonnull
@Override/*from   w w  w.ja  v a 2  s  .c om*/
public IdpLoginResult login(String login, String password, Locale locale,
        @Nullable Map<String, Object> parameters) throws LoginException {
    log.debug("Authenticating CUBA user for IDP");

    LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, password, locale, parameters);
    AuthenticationDetails sessionDetails = authenticationManager.authenticate(credentials);
    User user = sessionDetails.getSession().getUser();

    IdpSession session = new IdpSession(createIdpSessionId());
    session.setLogin(user.getLogin());
    session.setEmail(user.getEmail());

    Locale userLocale = locale;
    if (user.getLanguage() != null && !globalConfig.getLocaleSelectVisible()) {
        userLocale = LocaleUtils.toLocale(user.getLanguage());
    }

    session.setLocale(userLocale.toLanguageTag());

    String serviceProviderTicket = sessionStore.putSession(session);

    return new IdpLoginResult(session.getId(), serviceProviderTicket);
}

From source file:org.pdfsam.ui.dashboard.preference.PreferenceAppearencePaneTest.java

@Test
public void eventSentOnLocaleChange() {
    Listener<SetLocaleEvent> listener = mock(Listener.class);
    eventStudio().add(SetLocaleEvent.class, listener);
    Locale first = DefaultI18nContext.SUPPORTED_LOCALES.stream().findFirst().get();
    click("#localeCombo").click(StringUtils.capitalize(first.getDisplayName()));
    ArgumentCaptor<SetLocaleEvent> captor = ArgumentCaptor.forClass(SetLocaleEvent.class);
    verify(listener).onEvent(captor.capture());
    assertEquals(first.toLanguageTag(), captor.getValue().getLocaleString());
    verify(userContext).setStringPreference(eq(StringUserPreference.LOCALE), eq(first.toLanguageTag()));
}

From source file:org.lunifera.ecview.xtext.builder.participant.impl.I18nRegistry.java

/**
 * Creates the key for the fast access map access.
 * /* ww  w  .j ava  2 s  . c o  m*/
 * @param temp
 * @param key
 * @return
 */
private String createFastAccessKey(Locale temp, String key) {
    return temp.toLanguageTag() + ":" + key;
}

From source file:com.relicum.ipsum.Locale.PropertyManager.java

/**
 * Instantiates a new Property manager.// www .jav  a  2  s .c om
 * Creates a property list from the settings in the specified file.
 *
 * @param devMode the dev mode
 * @param path    the path
 * @param locale  the locale
 * @throws IOException the iO exception
 */
public PropertyManager(boolean devMode, String path, Locale locale) throws IOException {
    Validate.notNull(path, "The path to the directory when in development mode can not be null");

    defaultCountyCode = "_" + locale.toLanguageTag().replace('-', '_');
    log.info(defaultCountyCode);
    this.devMode = devMode;
    this.devPath = path;
    try {
        Files.createDirectories(Paths.get(devPath));
    } catch (IOException e) {
        log.severe(e.getMessage());
        throw e;
    }

    properties = new Properties();
}

From source file:com.haulmont.cuba.web.app.loginwindow.AppLoginWindow.java

protected void doLogin() {
    String login = loginField.getValue();
    String password = passwordField.getValue() != null ? passwordField.getValue() : "";

    if (StringUtils.isEmpty(login) || StringUtils.isEmpty(password)) {
        showNotification(messages.getMainMessage("loginWindow.emptyLoginOrPassword"), NotificationType.WARNING);
        return;/*from   ww w  .  j  a  v a  2s  . c o m*/
    }

    try {
        Locale selectedLocale = localesSelect.getValue();
        app.setLocale(selectedLocale);

        if (loginByRememberMe && webConfig.getRememberMeEnabled()) {
            doLogin(new RememberMeCredentials(login, password, selectedLocale));
        } else {
            doLogin(new LoginPasswordCredentials(login, password, selectedLocale));
        }

        // locale could be set on the server
        if (connection.getSession() != null) {
            Locale loggedInLocale = connection.getSession().getLocale();

            if (globalConfig.getLocaleSelectVisible()) {
                app.addCookie(App.COOKIE_LOCALE, loggedInLocale.toLanguageTag());
            }
        }
    } catch (InternalAuthenticationException e) {
        log.error("Internal error during login", e);

        showUnhandledExceptionOnLogin(e);
    } catch (LoginException e) {
        log.info("Login failed: {}", e.toString());

        String message = StringUtils.abbreviate(e.getMessage(), 1000);
        showLoginException(message);
    } catch (Exception e) {
        log.warn("Unable to login", e);

        showUnhandledExceptionOnLogin(e);
    }
}

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;
                }/*from www . j  a  v  a 2s  .com*/
            }
        }
    }

    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:de.flashpixx.rrd_antlr4.CMain.java

@Override
protected final void executeReport(final Locale p_locale) throws MavenReportException {
    if ((imports == null) || (imports.length == 0))
        throw new MavenReportException(CCommon.languagestring(this, "importempty"));

    final Tuple5<File, Set<ETemplate>, Set<File>, Set<String>, Set<String>> l_initdata = CMain
            .initialize(p_locale.toLanguageTag(), output, templates, imports, excludes, docclean);

    // --- run generator ---
    final IGenerator l_generator = new CPlugin(this, NAME, l_initdata.v1(), new File(grammarbasedir),
            l_initdata.v3(), l_initdata.v5(), l_initdata.v2());
    Arrays.stream(grammar).flatMap(i -> CMain.filelist(new File(i.trim()), l_initdata.v3(), l_initdata.v4()))
            .forEach(l_generator::generate);

    l_generator.finish();/*from   www  .  jav  a  2 s .  co  m*/
}

From source file:org.lunifera.ecview.xtext.builder.participant.impl.I18nRegistry.java

/**
 * Computes all locales that should be added to AccessPath
 * //from   ww  w . j  a  va 2s.com
 * @param locale
 * @return
 */
private List<Locale> computeLocales(Locale locale) {
    List<Locale> locales = new LinkedList<Locale>();

    // Add first locale
    locales.add(locale);

    Locale temp = locale;
    while (true) {
        String tag = temp.toLanguageTag();
        String[] segments = tag.split("-");
        if (segments.length > 1) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < segments.length - 1; i++) {
                if (builder.length() != 0) {
                    builder.append("-");
                }
                builder.append(segments[i]);
            }
            Locale moreGeneral = Locale.forLanguageTag(builder.toString());
            locales.add(moreGeneral);
            temp = moreGeneral;
        } else {
            break;
        }
    }

    locales.add(new Locale(""));

    return locales;
}

From source file:org.mayocat.context.RequestContextInitializer.java

public void requestInitialized(ServletRequestEvent servletRequestEvent) {
    if (isStaticPath(this.getRequestURI(servletRequestEvent))) {
        return;/* w ww .  jav  a  2s .  co m*/
    }

    DefaultWebRequestBuilder requestBuilder = new DefaultWebRequestBuilder();

    // 1. Tenant

    String host = getHost(servletRequestEvent);
    String path = getPath(servletRequestEvent);

    Tenant tenant = this.tenantResolver.get().resolve(host, path);
    DefaultWebContext context = new DefaultWebContext(tenant, null);

    // Set the context in the context already, even if we haven't figured out if there is a valid user yet.
    // The context tenant is actually needed to find out the context user and to initialize tenant configurations
    ((ThreadLocalWebContext) this.context).setContext(context);

    if (tenant != null) {
        requestBuilder.tenantRequest(true);
        if (path.indexOf("/tenant/" + tenant.getSlug()) == 0) {
            path = StringUtils.substringAfter(path, "/tenant/" + tenant.getSlug());
            requestBuilder.tenantPrefix("/tenant/" + tenant.getSlug());
        }
    } else {
        requestBuilder.tenantRequest(false);
    }

    requestBuilder.apiRequest(path.indexOf("/api/") == 0);

    // 2. Configurations

    Map<Class, Serializable> configurations = configurationService.getSettings();
    context.setSettings(configurations);

    // 3. User

    Optional<User> user = Optional.absent();
    for (String headerName : Lists.newArrayList("Authorization", "Cookie")) {
        final String headerValue = Strings.nullToEmpty(this.getHeaderValue(servletRequestEvent, headerName));
        for (Authenticator authenticator : this.authenticators.values()) {
            if (authenticator.respondTo(headerName, headerValue)) {
                user = authenticator.verify(headerValue, tenant);
            }
        }
    }

    context.setUser(user.orNull());

    if (tenant != null) {
        // 4. ThemeDefinition
        context.setTheme(themeManager.getTheme());
    }
    // 5. Locale
    LocalesSettings localesSettings = configurationService.getSettings(GeneralSettings.class).getLocales();
    boolean localeSet = false;
    List<Locale> alternativeLocales = FluentIterable.from(localesSettings.getOtherLocales().getValue())
            .filter(Predicates.notNull()).toList();

    String canonicalPath = path;
    if (!alternativeLocales.isEmpty()) {
        for (Locale locale : alternativeLocales) {
            List<String> fragments = ImmutableList.copyOf(
                    Collections2.filter(Arrays.asList(path.split("/")), Predicates.not(IS_NULL_OR_BLANK)));
            if (fragments.size() > 0 && fragments.get(0).equals(locale.toLanguageTag())) {
                context.setLocale(locale);
                context.setAlternativeLocale(true);
                canonicalPath = StringUtils.substringAfter(canonicalPath, "/" + locale);
                localeSet = true;
                break;
            }
        }
    }
    if (!localeSet) {
        context.setLocale(localesSettings.getMainLocale().getValue());
        context.setAlternativeLocale(false);
    }

    if (context.isAlternativeLocale()) {
        path = StringUtils.substringAfter(path, context.getLocale().toLanguageTag());
    }

    // 6. Request
    Optional<Breakpoint> breakpoint = this.breakpointDetector.getBreakpoint(getUserAgent(servletRequestEvent));

    requestBuilder.baseURI(getBaseURI(servletRequestEvent)).canonicalPath(canonicalPath).path(path)
            .breakpoint(breakpoint);

    requestBuilder.secure(isSecure(servletRequestEvent));

    context.setRequest(requestBuilder.build());
}

From source file:org.mayocat.rest.resources.LocalesResource.java

@GET
public Response getLocales() {
    if (localesRepresentations == null) {
        Set<LocaleRepresentation> locales = Sets.newHashSet();
        List<Locale> availableLocales = LocaleUtils.availableLocaleList();
        for (final Locale locale : availableLocales) {
            StringBuilder nameBuilder = new StringBuilder();
            nameBuilder.append(locale.getDisplayLanguage());
            if (!Strings.isNullOrEmpty(locale.getDisplayCountry())) {
                nameBuilder.append(" (");
                nameBuilder.append(locale.getDisplayCountry());
                nameBuilder.append(")");
            }/* w w  w  .  ja va  2 s . com*/
            final String name = nameBuilder.toString();
            locales.add(new LocaleRepresentation(locale.toLanguageTag(), name));
        }
        Ordering<LocaleRepresentation> nameOrdering = Ordering.natural()
                .onResultOf(new Function<LocaleRepresentation, String>() {
                    public String apply(LocaleRepresentation from) {
                        return from.getName();
                    }
                });

        localesRepresentations = ImmutableSortedSet.orderedBy(nameOrdering).addAll(locales).build();
    }

    return Response.ok(localesRepresentations).build();
}