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.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  w  w .java 2 s  .com
            }
        }
    }

    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:tr.edu.gsu.peralab.mobilesensing.web.service.UserService.java

private void calculatePeriod(long hours, int index, Calendar startTime, Calendar endTime,
        ActivityMapResponse response) {/* www. j  av a2 s. c  o m*/
    if (hours <= 1) {
        startTime.add(Calendar.MINUTE, -(index * 10));
        endTime.add(Calendar.MONTH, 10 - (index * 10));
        response.setPeriod(String.valueOf(startTime.get(Calendar.MINUTE)));
    } else if (hours <= 6) {
        startTime.add(Calendar.HOUR, -index);
        endTime.add(Calendar.HOUR, 1 - index);
        response.setPeriod(String.valueOf(startTime.get(Calendar.HOUR)));
    } else if (hours <= 24) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("h:mm a", Locale.forLanguageTag("TR"));
        startTime.add(Calendar.HOUR, -(index * 4));
        endTime.add(Calendar.HOUR, 4 - (index * 4));
        response.setPeriod(
                dateFormat.format(startTime.getTime()) + " - " + dateFormat.format(endTime.getTime()));
    } else if (hours <= 144) {
        startTime.add(Calendar.DAY_OF_MONTH, -index);
        endTime.add(Calendar.DAY_OF_MONTH, 1 - index);
        response.setPeriod(
                new SimpleDateFormat("d MMM", Locale.forLanguageTag("TR")).format(startTime.getTime()));
    } else if (hours <= 720) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM", Locale.forLanguageTag("TR"));
        startTime.add(Calendar.DAY_OF_MONTH, -((index + 1) * 5));
        endTime.add(Calendar.DAY_OF_MONTH, 5 - ((index + 1) * 5));
        response.setPeriod(
                dateFormat.format(startTime.getTime()) + " - " + dateFormat.format(endTime.getTime()));
    } else {
        startTime.add(Calendar.MONTH, -(index + 1));
        endTime.add(Calendar.MONTH, -index);
        response.setPeriod(
                new SimpleDateFormat("MMM", Locale.forLanguageTag("TR")).format(startTime.getTime()));
    }
}

From source file:com.carlomicieli.jtrains.value.objects.LocalizedField.java

private static String sanitizeLanguage(String lang) {
    Locale l = Locale.forLanguageTag(lang);

    if (!ISOValidationUtils.countryIsValid(l.getCountry())) {
        throw new IllegalArgumentException("'" + lang + "' is not a valid locale code (country).");
    }//from w w w  .j av a 2s  .  co m
    if (!ISOValidationUtils.languageIsValid(l.getLanguage())) {
        throw new IllegalArgumentException("'" + lang + "' is not a valid locale code (language).");
    }

    return l.getLanguage();
}

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

/**
 * Check that the Card Generator correctly translates from American to
 * British English.//from   w  ww.  jav  a  2 s. c  om
 * 
 * @throws SAXException if an error occurs while building one of the test or
 *         control documents.
 * @throws IOException if an error occurs while reading one of the test or
 *         control documents.
 * @throws TransformerException is an unrecoverable error occurs during the
 *         transformation.
 * @throws ParserConfigurationException
 */
@Test
public void testCardGeneratorGenerate_translate_english()
        throws SAXException, IOException, TransformerException, ParserConfigurationException {

    // Retrieve the test card data for American CAH.
    File xml = this.getFile("/data/test/cards/usa.xml");

    // Build the cards
    Document result = this.getDocument(generator.generate(xml, Locale.forLanguageTag("en-gb"),
            this.getFile("/data/control/dictionaries/english.xml")));

    // Retrieve the test card data for British CAH.
    Document expected = this.getDocument("/data/control/cards/uk.html");

    // Check that the result is the same cards, translated into British
    // English (which is the default output language).
    assertXMLEqual(expected, result);

}

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

/**
 * Returns a UMS supported {@link java.util.Locale} from the given
 * <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
 * if it can be found (<code>en</code> is translated to <code>en-US</code>,
 * <code>zh</code> to <code>zh-Hant</code> etc.). Returns <code>null</code>
 * if a valid <code>Locale</code> cannot be found.
 * @param locale Source {@link java.util.Locale}.
 * @return Resulting {@link java.util.Locale}.
 *//*w w  w . ja va2 s . c om*/
public static Locale toLocale(String languageCode) {
    if (languageCode != null) {
        String code = languageCodeToLanguageCode(languageCode);
        if (isValid(code)) {
            return Locale.forLanguageTag(code);
        }
    }
    return null;
}

From source file:org.tsugi.jpa.LTIRequest.java

/**
 * Processes all the parameters in this request into populated internal variables in the LTI Request
 *
 * @param request an http servlet request
 * @return true if this is a complete LTI request (includes key, context, link, user) OR false otherwise
 *//*w  w w  .ja v  a  2  s .  c o  m*/
public boolean processRequestParameters(HttpServletRequest request) {
    if (request != null && this.httpServletRequest != request) {
        this.httpServletRequest = request;
    }
    assert this.httpServletRequest != null;

    ltiMessageType = getParam(LTI_MESSAGE_TYPE);
    ltiVersion = getParam(LTI_VERSION);
    // These 4 really need to be populated for this LTI request to make any sense...
    ltiConsumerKey = getParam(LTI_CONSUMER_KEY);
    ltiContextId = getParam(LTI_CONTEXT_ID);
    ltiLinkId = getParam(LTI_LINK_ID);
    ltiUserId = getParam(LTI_USER_ID);
    complete = checkCompleteLTIRequest(false);
    // OPTIONAL fields below
    ltiServiceId = getParam(LTI_SERVICE);
    ltiSourcedid = getParam(LTI_SOURCEDID);
    ltiUserEmail = getParam(LTI_USER_EMAIL);
    ltiUserImageUrl = getParam(LTI_USER_IMAGE_URL);
    ltiLinkTitle = getParam(LTI_LINK_TITLE);
    ltiLinkDescription = getParam(LTI_LINK_DESC);
    ltiContextTitle = getParam(LTI_CONTEXT_TITLE);
    ltiContextLabel = getParam(LTI_CONTEXT_LABEL);
    String localeStr = getParam(LTI_PRES_LOCALE);
    if (localeStr == null) {
        ltiPresLocale = Locale.getDefault();
    } else {
        ltiPresLocale = Locale.forLanguageTag(localeStr);
    }
    ltiPresTarget = getParam(LTI_PRES_TARGET);
    ltiPresWidth = NumberUtils.toInt(getParam(LTI_PRES_WIDTH), 0);
    ltiPresHeight = NumberUtils.toInt(getParam(LTI_PRES_HEIGHT), 0);
    ltiPresReturnUrl = getParam(LTI_PRES_RETURN_URL);
    ltiToolConsumerCode = getParam(LTI_TOOL_CONSUMER_CODE);
    ltiToolConsumerVersion = getParam(LTI_TOOL_CONSUMER_VERSION);
    ltiToolConsumerName = getParam(LTI_TOOL_CONSUMER_NAME);
    ltiToolConsumerEmail = getParam(LTI_TOOL_CONSUMER_EMAIL);
    rawUserRoles = getParam(LTI_USER_ROLES);
    userRoleNumber = makeUserRoleNum(rawUserRoles);
    String[] splitRoles = StringUtils.split(StringUtils.trimToEmpty(rawUserRoles), ",");
    ltiUserRoles = new HashSet<>(Arrays.asList(splitRoles));
    // user displayName requires some special processing
    if (getParam(LTI_USER_NAME_FULL) != null) {
        ltiUserDisplayName = getParam(LTI_USER_NAME_FULL);
    } else if (getParam(LIS_PERSON_PREFIX + "given") != null
            && getParam(LIS_PERSON_PREFIX + "family") != null) {
        ltiUserDisplayName = getParam(LIS_PERSON_PREFIX + "given") + " "
                + getParam(LIS_PERSON_PREFIX + "family");
    } else if (getParam(LIS_PERSON_PREFIX + "given") != null) {
        ltiUserDisplayName = getParam(LIS_PERSON_PREFIX + "given");
    } else if (getParam(LIS_PERSON_PREFIX + "family") != null) {
        ltiUserDisplayName = getParam(LIS_PERSON_PREFIX + "family");
    }
    return complete;
}

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

/**
 * @param reg//from  w  ww .j av  a 2s . c  o m
 * @param key 
 * @throws RegistrationException 
 */
private void sendConfirmationMail(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("confirmation.subject", null,
            Locale.forLanguageTag(reg.getLang()));
    sender.sendEmail(reg.getEmail(), "confirmation_" + lang, subject, vars);
}

From source file:org.xwiki.contrib.oidc.auth.internal.OIDCUserManager.java

private Principal updateUser(IDTokenClaimsSet idToken, UserInfo userInfo)
        throws XWikiException, QueryException {
    XWikiDocument userDocument = this.store.searchDocument(idToken.getIssuer().getValue(),
            userInfo.getSubject().toString());

    XWikiDocument modifiableDocument;/*  w  w w. j  a  v a 2 s  . c om*/
    boolean newUser;
    if (userDocument == null) {
        userDocument = getNewUserDocument(idToken, userInfo);

        newUser = true;
        modifiableDocument = userDocument;
    } else {
        // Don't change the document author to not change document execution right

        newUser = false;
        modifiableDocument = userDocument.clone();
    }

    XWikiContext xcontext = this.xcontextProvider.get();

    // Set user fields
    BaseObject userObject = modifiableDocument
            .getXObject(xcontext.getWiki().getUserClass(xcontext).getDocumentReference(), true, xcontext);

    // Address
    Address address = userInfo.getAddress();
    if (address != null) {
        userObject.set("address", address.getFormatted(), xcontext);
    }

    // Email
    if (userInfo.getEmail() != null) {
        userObject.set("email", userInfo.getEmail().toUnicodeString(), xcontext);
    }

    // Last name
    if (userInfo.getFamilyName() != null) {
        userObject.set("last_name", userInfo.getFamilyName(), xcontext);
    }

    // First name
    if (userInfo.getGivenName() != null) {
        userObject.set("first_name", userInfo.getGivenName(), xcontext);
    }

    // Phone
    if (userInfo.getPhoneNumber() != null) {
        userObject.set("phone", userInfo.getPhoneNumber(), xcontext);
    }

    // Default locale
    if (userInfo.getLocale() != null) {
        userObject.set("default_language", Locale.forLanguageTag(userInfo.getLocale()).toString(), xcontext);
    }

    // Time Zone
    if (userInfo.getZoneinfo() != null) {
        userObject.set("timezone", userInfo.getZoneinfo(), xcontext);
    }

    // Website
    if (userInfo.getWebsite() != null) {
        userObject.set("blog", userInfo.getWebsite().toString(), xcontext);
    }

    // Avatar
    if (userInfo.getPicture() != null) {
        try {
            String filename = FilenameUtils.getName(userInfo.getPicture().toString());
            URLConnection connection = userInfo.getPicture().toURL().openConnection();
            connection.setRequestProperty("User-Agent", this.getClass().getPackage().getImplementationTitle()
                    + '/' + this.getClass().getPackage().getImplementationVersion());
            try (InputStream content = connection.getInputStream()) {
                modifiableDocument.addAttachment(filename, content, xcontext);
            }
            userObject.set("avatar", filename, xcontext);
        } catch (IOException e) {
            this.logger.warn("Failed to get user avatar from URL [{}]: {}", userInfo.getPicture(),
                    ExceptionUtils.getRootCauseMessage(e));
        }
    }

    // XWiki claims
    updateXWikiClaims(modifiableDocument, userObject.getXClass(xcontext), userObject, userInfo, xcontext);

    // Set OIDC fields
    this.store.updateOIDCUser(modifiableDocument, idToken.getIssuer().getValue(),
            userInfo.getSubject().getValue());

    // Prevent data to send with the event
    OIDCUserEventData eventData = new OIDCUserEventData(new NimbusOIDCIdToken(idToken),
            new NimbusOIDCUserInfo(userInfo));

    // Notify
    this.observation.notify(new OIDCUserUpdating(modifiableDocument.getDocumentReference()), modifiableDocument,
            eventData);

    // Apply the modifications
    if (newUser || userDocument.apply(modifiableDocument)) {
        String comment;
        if (newUser) {
            comment = "Create user from OpenID Connect";
        } else {
            comment = "Update user from OpenID Connect";
        }

        xcontext.getWiki().saveDocument(userDocument, comment, xcontext);

        // Now let's add new the user to XWiki.XWikiAllGroup
        if (newUser) {
            xcontext.getWiki().setUserDefaultGroup(userDocument.getFullName(), xcontext);
        }

        // Notify
        this.observation.notify(new OIDCUserUpdated(userDocument.getDocumentReference()), userDocument,
                eventData);
    }

    return new SimplePrincipal(userDocument.getPrefixedFullName());
}

From source file:net.sf.markov4jmeter.testplangenerator.TestPlanGenerator.java

/**
 * Initializes the Test Plan Generator by loading the specified
 * configuration file and setting its properties accordingly.
 *
 * @param configurationFile//from w w  w.j  a va2  s.  c o m
 *     properties file which provides required or optional properties.
 * @param testPlanProperties
 *     file with Test Plan default properties.
 */
public void init(final String configurationFile, final String testPlanProperties) {

    // read the configuration and give an error message, if reading fails;
    // in that case, null will be returned;
    final Configuration configuration = this.readConfiguration(configurationFile);

    if (configuration != null) { // could configuration be read?

        final boolean useForcedArguments = configuration
                .getBoolean(TestPlanGenerator.PKEY_USE_FORCED_ARGUMENTS);

        final String jMeterHome = configuration.getString(TestPlanGenerator.PKEY_JMETER__HOME);

        final String jMeterProperties = configuration.getString(TestPlanGenerator.PKEY_JMETER__PROPERTIES);

        final String jMeterLanguageTag = configuration.getString(TestPlanGenerator.PKEY_JMETER__LANGUAGE_TAG);

        final Locale jMeterLocale = Locale.forLanguageTag(jMeterLanguageTag);

        final boolean success = JMeterEngineGateway.getInstance().initJMeter(jMeterHome, jMeterProperties,
                jMeterLocale);

        if (success) {

            // create a factory which builds Test Plan elements according
            // to the specified properties.
            this.testPlanElementFactory = this.createTestPlanFactory(testPlanProperties, useForcedArguments);

            if (this.testPlanElementFactory != null) {

                this.logInfo(TestPlanGenerator.INFO_INITIALIZATION_SUCCESSFUL);

                return;
            }
        }

    }

    this.logError(TestPlanGenerator.ERROR_INITIALIZATION_FAILED);
}

From source file:org.jivesoftware.openfire.websocket.XmppWebSocket.java

private void initiateSession(Element stanza) {

    String host = stanza.attributeValue("to");
    StreamError streamError = null;//from   ww  w  . j ava 2  s  .  c  o  m
    Locale language = Locale
            .forLanguageTag(stanza.attributeValue(QName.get("lang", XMLConstants.XML_NS_URI), "en"));
    if (STREAM_FOOTER.equals(stanza.getName())) {
        // an error occurred while setting up the session
        Log.warn("Client closed stream before session was established");
    } else if (!STREAM_HEADER.equals(stanza.getName())) {
        streamError = new StreamError(StreamError.Condition.unsupported_stanza_type);
        Log.warn("Closing session due to incorrect stream header. Tag: " + stanza.getName());
    } else if (!FRAMING_NAMESPACE.equals(stanza.getNamespace().getURI())) {
        // Validate the stream namespace (https://tools.ietf.org/html/rfc7395#section-3.3.2)
        streamError = new StreamError(StreamError.Condition.invalid_namespace);
        Log.warn("Closing session due to invalid namespace in stream header. Namespace: "
                + stanza.getNamespace().getURI());
    } else if (!validateHost(host)) {
        streamError = new StreamError(StreamError.Condition.host_unknown);
        Log.warn("Closing session due to incorrect hostname in stream header. Host: " + host);
    } else {
        // valid stream; initiate session
        xmppSession = SessionManager.getInstance().createClientSession(wsConnection, language);
        xmppSession.setSessionData("ws", Boolean.TRUE);
    }

    if (xmppSession == null) {
        closeStream(streamError);
    } else {
        openStream(language.toLanguageTag(), stanza.attributeValue("from"));
        configureStream();
    }
}