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.core.sys.remoting.CubaRemoteInvocationExecutor.java

@Override
public Object invoke(RemoteInvocation invocation, Object targetObject)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (invocation instanceof CubaRemoteInvocation) {
        CubaRemoteInvocation cubaInvocation = (CubaRemoteInvocation) invocation;

        UUID sessionId = cubaInvocation.getSessionId();
        if (sessionId != null) {
            UserSession session = userSessions.getAndRefresh(sessionId);
            if (session == null) {
                ServerConfig serverConfig = configuration.getConfig(ServerConfig.class);
                String sessionProviderUrl = serverConfig.getUserSessionProviderUrl();
                if (StringUtils.isNotBlank(sessionProviderUrl)) {
                    log.debug("User session {} not found, trying to get it from {}", sessionId,
                            sessionProviderUrl);
                    try {
                        HttpServiceProxy proxyFactory = new HttpServiceProxy(
                                getServerSelector(sessionProviderUrl));
                        proxyFactory.setServiceUrl("cuba_TrustedClientService");
                        proxyFactory.setServiceInterface(TrustedClientService.class);
                        proxyFactory.afterPropertiesSet();
                        TrustedClientService trustedClientService = (TrustedClientService) proxyFactory
                                .getObject();
                        if (trustedClientService != null) {
                            UserSession userSession = trustedClientService
                                    .findSession(serverConfig.getTrustedClientPassword(), sessionId);
                            if (userSession != null) {
                                userSessions.add(userSession);
                            } else {
                                log.debug("User session {} not found on {}", sessionId, sessionProviderUrl);
                            }//  w  ww  .j a  v a 2 s  .  com
                        }
                    } catch (Exception e) {
                        log.error("Error getting user session from {}", sessionProviderUrl, e);
                    }
                }
            }
            AppContext.setSecurityContext(new SecurityContext(sessionId));
        }

        if (cubaInvocation.getLocale() != null) {
            Locale requestLocale = Locale.forLanguageTag(cubaInvocation.getLocale());
            if (!globalConfig.getAvailableLocales().containsValue(requestLocale)) {
                requestLocale = null;
            }

            UserInvocationContext.setRequestScopeInfo(sessionId, requestLocale, cubaInvocation.getTimeZone(),
                    cubaInvocation.getAddress(), cubaInvocation.getClientInfo());
        }
    }

    Object result;
    try {
        result = invocation.invoke(targetObject);
    } finally {
        AppContext.setSecurityContext(null);
        UserInvocationContext.clearRequestScopeInfo();
    }

    return result;
}

From source file:org.apache.openmeetings.db.dao.label.LabelDao.java

public static void initLanguageMap() {
    SAXReader reader = new SAXReader();
    try {/*from  ww  w .  j  av  a  2 s  . c  o m*/
        getAppClass();
        Document document = reader.read(getLangFile());
        Element root = document.getRootElement();
        languages.clear();
        for (@SuppressWarnings("unchecked")
        Iterator<Element> it = root.elementIterator("lang"); it.hasNext();) {
            Element item = it.next();
            Long id = Long.valueOf(item.attributeValue("id"));
            String code = item.attributeValue("code");
            if (id == 3L) {
                continue;
            }
            languages.put(id, Locale.forLanguageTag(code));
        }
    } catch (Exception e) {
        log.error("Error while building language map");
    }
}

From source file:com.github.rvesse.airline.restrictions.factories.RangeRestrictionFactory.java

protected RangeRestriction createLexicalRange(Annotation annotation) {
    LexicalRange lRange = (LexicalRange) annotation;
    return new RangeRestriction(StringUtils.isEmpty(lRange.min()) ? null : lRange.min(), lRange.minInclusive(),
            StringUtils.isEmpty(lRange.max()) ? null : lRange.max(), lRange.maxInclusive(),
            new LexicalComparator(Locale.forLanguageTag(lRange.locale())));
}

From source file:com.amazon.alexa.avs.config.DeviceConfig.java

/**
 * Creates a {@link DeviceConfig} object.
 *
 * @param productId//from w w  w.ja  v a2s  .  c o  m
 *            The productId of this device.
 * @param dsn
 *            The dsn of this device.
 * @param provisioningMethod
 *            The provisioningMethod to use. One of: {@value #COMPANION_APP},
 *            {@value #COMPANION_SERVICE}
 * @param wakeWordAgentEnabled
 *            Whether the wake word agent functionality is enabled.
 * @param languageTag
 *            The language tag representing the locale to initialize the app with.
 * @param companionAppInfo
 *            The information necessary for the Companion App method of provisioning.
 * @param companionServiceInfo
 *            The information necessary for the Companion Service method of provisioning.
 * @param avsHost
 *            (optional) AVS host override
 */
public DeviceConfig(String productId, String dsn, String provisioningMethod, boolean wakeWordAgentEnabled,
        String languageTag, CompanionAppInformation companionAppInfo,
        CompanionServiceInformation companionServiceInfo, String avsHost) {

    if (StringUtils.isBlank(productId)) {
        throw new MalformedConfigException(PRODUCT_ID + " is blank in your config file.");
    }

    if (StringUtils.isBlank(dsn)) {
        throw new MalformedConfigException(DSN + " is blank in your config file.");
    }

    if (StringUtils.isBlank(languageTag)) {
        throw new MalformedConfigException(LOCALE + " is blank in your config file. Supported locales are: "
                + SUPPORTED_LOCALES.stream().map(e -> e.toLanguageTag()).collect(Collectors.toList()));
    }

    Locale locale = Locale.forLanguageTag(languageTag);
    if (!SUPPORTED_LOCALES.contains(locale)) {
        throw new MalformedConfigException(
                LOCALE + ": " + locale + " is not a supported locale. Supported locales are: "
                        + SUPPORTED_LOCALES.stream().map(e -> e.toLanguageTag()).collect(Collectors.toList()));
    }

    ProvisioningMethod method;
    try {
        method = ProvisioningMethod.fromString(provisioningMethod);
    } catch (IllegalArgumentException e) {
        throw new MalformedConfigException(PROVISIONING_METHOD + " should be either \"" + COMPANION_APP
                + "\" or \"" + COMPANION_SERVICE + "\".");
    }

    if (method == ProvisioningMethod.COMPANION_APP
            && (companionAppInfo == null || !companionAppInfo.isValid())) {
        throw new MalformedConfigException("Your " + PROVISIONING_METHOD + " is set to \"" + COMPANION_APP
                + "\" but you do not have a valid \"" + COMPANION_APP + "\" section in your config file.");
    } else if (method == ProvisioningMethod.COMPANION_SERVICE
            && (companionServiceInfo == null || !companionServiceInfo.isValid())) {
        throw new MalformedConfigException("Your " + PROVISIONING_METHOD + " is set to \"" + COMPANION_SERVICE
                + "\" but you do not have a valid \"" + COMPANION_SERVICE + "\" section in your config file.");
    }

    this.provisioningMethod = method;
    this.productId = productId;
    this.dsn = dsn;
    this.locale = locale;
    this.companionServiceInfo = companionServiceInfo;
    this.companionAppInfo = companionAppInfo;
    avsHost = StringUtils.isBlank(avsHost) ? DEFAULT_HOST : avsHost;
    try {
        this.avsHost = new URL(avsHost);
    } catch (MalformedURLException e) {
        throw new MalformedConfigException(AVS_HOST + " is malformed in your config file.", e);
    }

    this.wakeWordAgentEnabled = wakeWordAgentEnabled;
}

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

@RequestMapping(value = "/overridable-template/{name}/{locale}", method = RequestMethod.GET)
public void getTemplate(@PathVariable("name") TemplateResource name, @PathVariable("locale") String locale,
        HttpServletResponse response) throws IOException {
    response.setContentType("text/plain");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (InputStream is = new ClassPathResource(name.classPath()).getInputStream()) {
        StreamUtils.copy(is, os);//from w  w  w. ja va2 s .co m
    }
    Locale loc = Locale.forLanguageTag(locale);
    String template = new String(os.toByteArray(), StandardCharsets.UTF_8);

    response.setContentType("text/plain");
    response.getWriter().print(TemplateManager.translate(template, loc, messageSource));
}

From source file:org.egov.infra.config.core.LocalizationSettings.java

public static Locale locale() {
    return Locale.forLanguageTag(defaultIfBlank(getProperty(DEFAULT_LOCALE_KEY), DEFAULT_LOCALE));
}

From source file:org.ng200.openolympus.Application.java

@Bean
public SessionLocaleResolver localeResolver() {
    final SessionLocaleResolver resolver = new SessionLocaleResolver();
    resolver.setDefaultLocale(Locale.forLanguageTag("ru"));
    return resolver;
}

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

/**
 * Computes all locales that should be added to AccessPath
 * /*  ww  w.j  a v a2s  .  c  o m*/
 * @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:alfio.manager.NotificationManager.java

private static Function<Map<String, String>, byte[]> generateTicketPDF(EventRepository eventRepository,
        OrganizationRepository organizationRepository, ConfigurationManager configurationManager,
        FileUploadManager fileUploadManager, TemplateManager templateManager,
        TicketReservationRepository ticketReservationRepository) {
    return (model) -> {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Ticket ticket = Json.fromJson(model.get("ticket"), Ticket.class);
        try {/*from  w  ww .  j  a  v a2  s.co m*/
            TicketReservation reservation = ticketReservationRepository
                    .findReservationById(ticket.getTicketsReservationId());
            TicketCategory ticketCategory = Json.fromJson(model.get("ticketCategory"), TicketCategory.class);
            Event event = eventRepository.findById(ticket.getEventId());
            Organization organization = organizationRepository
                    .getById(Integer.valueOf(model.get("organizationId"), 10));
            PDFTemplateGenerator pdfTemplateGenerator = TemplateProcessor.buildPDFTicket(
                    Locale.forLanguageTag(ticket.getUserLanguage()), event, reservation, ticket, ticketCategory,
                    organization, templateManager, fileUploadManager,
                    configurationManager.getShortReservationID(event, ticket.getTicketsReservationId()));
            pdfTemplateGenerator.generate().createPDF(baos);
        } catch (IOException e) {
            log.warn("was not able to generate ticket pdf for ticket with id" + ticket.getId(), e);
        }
        return baos.toByteArray();
    };
}

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

@Test
public void testToLocale() {
    assertEquals("enIsen-US", Languages.toLocale(Locale.forLanguageTag("en")), Locale.forLanguageTag("en-US"));
    assertEquals("en-USIsen-US", Languages.toLocale(Locale.forLanguageTag("en-US")),
            Locale.forLanguageTag("en-US"));
    assertEquals("en-GBIsen-GB", Languages.toLocale(Locale.forLanguageTag("en-GB")),
            Locale.forLanguageTag("en-GB"));
    assertEquals("zh-HansIszh-Hans", Languages.toLocale(Locale.forLanguageTag("zh-Hans")),
            Locale.forLanguageTag("zh-Hans"));
    assertEquals("cmn-HantIszh-Hant", Languages.toLocale(Locale.forLanguageTag("cmn-Hant")),
            Locale.forLanguageTag("zh-Hant"));
    assertEquals("zh-CNIszh-Hans", Languages.toLocale(Locale.forLanguageTag("zh-CN")),
            Locale.forLanguageTag("zh-Hans"));
    assertEquals("zh-SGIszh-Hans", Languages.toLocale(Locale.forLanguageTag("zh-SG")),
            Locale.forLanguageTag("zh-Hans"));
    assertEquals("zh-TWIszh-Hant", Languages.toLocale(Locale.forLanguageTag("zh-TW")),
            Locale.forLanguageTag("zh-Hant"));
    assertEquals("pt-PTIspt", Languages.toLocale(Locale.forLanguageTag("pt-PT")), Locale.forLanguageTag("pt"));
    assertEquals("no-NOIsno", Languages.toLocale(Locale.forLanguageTag("no-NO")), Locale.forLanguageTag("no"));
    assertNull("EmptyIsNull", Languages.toLocale(Locale.forLanguageTag("")));
    Locale locale = null;/*  ww  w .j  ava 2s . c o  m*/
    assertNull("NullIsNull", Languages.toLocale(locale));
}