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:org.ldp4j.server.testing.ServerFrontendTestHelper.java

public Metadata httpRequest(final HttpUriRequest request) throws Exception {
    final Metadata metadata = new Metadata();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            metadata.status = response.getStatusLine().getStatusCode();
            metadata.body = responseBody;
            Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            if (etagHeader != null) {
                metadata.etag = etagHeader.getValue();
            }/*  w  w  w  . j ava2 s.c  om*/
            Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (lastModifiedHeader != null) {
                metadata.lastModified = lastModifiedHeader.getValue();
            }
            Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
            if (locationHeader != null) {
                metadata.location = locationHeader.getValue();
            }
            Header contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
            if (contentType != null) {
                metadata.contentType = contentType.getValue();
            }
            Header contentLanguage = response.getFirstHeader(HttpHeaders.CONTENT_LANGUAGE);
            if (contentLanguage != null) {
                metadata.language = Locale.forLanguageTag(contentLanguage.getValue());
            }
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return metadata;
}

From source file:org.springframework.web.servlet.i18n.LocaleChangeInterceptor.java

/**
 * Parse the given locale value as coming from a request parameter.
 * <p>The default implementation calls {@link StringUtils#parseLocaleString(String)}
 * or JDK 7's {@link Locale#forLanguageTag(String)}, depending on the
 * {@link #setLanguageTagCompliant "languageTagCompliant"} configuration property.
 * @param locale the locale value to parse
 * @return the corresponding {@code Locale} instance
 * @since 4.3//from  www  . j  a  va  2 s  .  c  o m
 */
@Nullable
protected Locale parseLocaleValue(String locale) {
    return (isLanguageTagCompliant() ? Locale.forLanguageTag(locale) : StringUtils.parseLocaleString(locale));
}

From source file:org.businessmanager.geodb.OpenGeoDBImpl.java

public List<Country> getListOfCountries(String language) {
    List<Country> countries = null;

    if (language == null) {
        countries = countryMap.get(Locale.getDefault().getLanguage());
    } else {/*from  w  w w  .  j a v  a2 s .  com*/
        countries = countryMap.get(language);
    }

    if (countries == null) {
        countries = new ArrayList<Country>();
    } else {
        return countries;
    }

    List<String> codes = new ArrayList<String>();
    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) {
        String code = locale.getCountry();

        // do not insert a country more than once
        if (codes.contains(code)) {
            continue;
        }

        String name = null;
        if (language != null) {
            name = locale.getDisplayCountry(Locale.forLanguageTag(language));
        } else {
            name = locale.getDisplayCountry();
        }

        if (!"".equals(code) && !"".equals(name)) {
            countries.add(new Country(code, name));
            codes.add(code);
        }
    }

    Collections.sort(countries, Country.getComparator());
    Country defaultCountry = findDefaultCountry(countries);
    if (defaultCountry != null) {
        countries.add(0, defaultCountry);
    }

    if (language == null) {
        countryMap.put(Locale.getDefault().getLanguage(), countries);
    } else {
        countryMap.put(language, countries);
    }

    return countries;
}

From source file:com.couchbase.devex.CSVConfig.java

public SimpleDateFormat getSimpleDateFormat() {
    if (sdf == null) {
        sdf = new SimpleDateFormat(getDateFormat(), Locale.forLanguageTag(languageTag));
    }//from  w  w  w .ja  v  a  2  s .  c  o  m
    return sdf;
}

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

@RequestMapping(value = "/overridable-template/{name}/{locale}/preview", method = RequestMethod.POST)
public void previewTemplate(@PathVariable("name") TemplateResource name, @PathVariable("locale") String locale,
        @RequestParam(required = false, value = "organizationId") Integer organizationId,
        @RequestParam(required = false, value = "eventId") Integer eventId,
        @RequestBody UploadBase64FileModification template, Principal principal, HttpServletResponse response)
        throws IOException {

    Locale loc = Locale.forLanguageTag(locale);

    if (organizationId != null && eventId != null) {
        checkAccess(organizationId, eventId, principal);
        Event event = eventRepository.findById(eventId);
        Organization organization = organizationRepository.getById(organizationId);
        Optional<TemplateResource.ImageData> image = TemplateProcessor.extractImageModel(event,
                fileUploadManager);//from  ww  w. ja v  a 2s. co m
        Map<String, Object> model = name.prepareSampleModel(organization, event, image);
        String renderedTemplate = templateManager.renderString(template.getFileAsString(), model, loc,
                name.getTemplateOutput());
        if ("text/plain".equals(name.getRenderedContentType())) {
            response.addHeader("Content-Disposition", "attachment; filename=" + name.name() + ".txt");
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            try (OutputStream os = response.getOutputStream()) {
                StreamUtils.copy(renderedTemplate, StandardCharsets.UTF_8, os);
            }
        } else if ("application/pdf".equals(name.getRenderedContentType())) {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + name.name() + ".pdf");
            try (OutputStream os = response.getOutputStream()) {
                TemplateProcessor.prepareItextRenderer(renderedTemplate).createPDF(os);
            }
        } else {
            throw new IllegalStateException("cannot enter here!");
        }
    }
}

From source file:meta.proyecto.base.ProyectoJava.java

private static Locale defaultLocale() {
    String tag = getString("locale.tag");
    return tag == null ? Locale.getDefault() : Locale.forLanguageTag(tag);
}

From source file:nu.yona.server.ThymeleafConfigurationTest.java

@Test
public void emailTemplateEngine_processBuddyInvitationBodyDutch_dutchTemplateFoundAndExpanded() {
    String buddyFirstName = "Richard";
    String buddyLastName = "Quin";
    String inviteUrl = "http://www.this.that?includePrivateData=false";
    String personalInvitationMessage = "Shall we?";
    String requestingUserFirstName = "Bob";
    String requestingUserLastName = "Dunn";
    String requestingUserMobileNumber = "+31687654321";
    String requestingUserNickname = "BD";

    String result = buildEmailBuddy(Optional.of(Locale.forLanguageTag("nl-NL")), buddyFirstName, buddyLastName,
            inviteUrl, personalInvitationMessage, requestingUserFirstName, requestingUserLastName,
            requestingUserMobileNumber, requestingUserNickname);

    assertThat(result, containsString(MessageFormat.format("<a href=\"{0}\"", inviteUrl)));
    assertThat(result, containsString(MessageFormat.format(
            "<strong>Belangrijk</strong>: Let op of de uitnodiging werkelijk van {0} {1} komt en check het mobiele nummer: <a href=\"tel:{2}\" style=\"color: #2678bf; text-decoration: none;\">{2}</a>.",
            requestingUserFirstName, requestingUserLastName, requestingUserMobileNumber)));
    assertThat(result, containsString("Ga terug naar deze mail en klik op <a href=\"http"));
    assertThat(result, containsString("https://app.prd.yona.nu/media/img/nl_NL/header.jpg"));
}

From source file:alfio.manager.SpecialPriceManager.java

public boolean sendCodeToAssignee(List<SendCodeModification> input, String eventName, int categoryId,
        String username) {/*from w ww . j av a  2s  . co  m*/
    final Event event = eventManager.getSingleEvent(eventName, username);
    final Organization organization = eventManager.loadOrganizer(event, username);
    Set<SendCodeModification> set = new LinkedHashSet<>(input);
    checkCodeAssignment(set, categoryId, event, username);
    Validate.isTrue(set.stream().allMatch(IS_CODE_PRESENT),
            "There are missing codes. Please check input file.");
    List<ContentLanguage> eventLanguages = i18nManager.getEventLanguages(event.getLocales());
    Validate.isTrue(!eventLanguages.isEmpty(),
            "No locales have been defined for the event. Please check the configuration");
    ContentLanguage defaultLocale = eventLanguages.contains(ContentLanguage.ENGLISH) ? ContentLanguage.ENGLISH
            : eventLanguages.get(0);
    set.forEach(m -> {
        Locale locale = Locale.forLanguageTag(StringUtils.defaultString(StringUtils.trimToNull(m.getLanguage()),
                defaultLocale.getLanguage()));
        Map<String, Object> model = TemplateResource.prepareModelForSendReservedCode(organization, event, m,
                eventManager.getEventUrl(event));
        notificationManager.sendSimpleEmail(event, m.getEmail(),
                messageSource.getMessage("email-code.subject", new Object[] { event.getDisplayName() }, locale),
                () -> templateManager.renderTemplate(event, TemplateResource.SEND_RESERVED_CODE, model,
                        locale));
        int marked = specialPriceRepository.markAsSent(ZonedDateTime.now(event.getZoneId()),
                m.getAssignee().trim(), m.getEmail().trim(), m.getCode().trim());
        Validate.isTrue(marked == 1, "Expected exactly one row updated, got " + marked);
    });
    return true;
}

From source file:at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

public String start() {
    try {//from  w  w  w  .  j av  a2s.c om
        populateBasicInformations();

    } catch (BasicActionException e) {
        return Constants.STRUTS_ERROR;

    }

    pvp2LoginActiv = configuration.isPVP2LoginActive();

    if (session.getAttribute(Constants.SESSION_I18n) == null)
        session.setAttribute(Constants.SESSION_I18n, Locale.forLanguageTag(configuration.getDefaultLanguage()));

    if (configuration.isLoginDeaktivated()) {
        return "loginWithOutAuth";

    } else {
        return Constants.STRUTS_SUCCESS;

    }
}

From source file:alfio.controller.api.ReservationApiController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/vat-validation", method = RequestMethod.POST)
@Transactional//  ww w. j ava 2s  .c  om
public ResponseEntity<VatDetail> validateEUVat(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, Locale locale,
        HttpServletRequest request) {

    String country = paymentForm.getVatCountryCode();
    Optional<Triple<Event, TicketReservation, VatDetail>> vatDetail = eventRepository
            .findOptionalByShortName(eventName)
            .flatMap(e -> ticketReservationRepository.findOptionalReservationById(reservationId)
                    .map(r -> Pair.of(e, r)))
            .filter(e -> EnumSet.of(INCLUDED, NOT_INCLUDED).contains(e.getKey().getVatStatus()))
            .filter(e -> vatChecker.isVatCheckingEnabledFor(e.getKey().getOrganizationId()))
            .flatMap(e -> vatChecker.checkVat(paymentForm.getVatNr(), country, e.getKey().getOrganizationId())
                    .map(vd -> Triple.of(e.getLeft(), e.getRight(), vd)));

    vatDetail.filter(t -> t.getRight().isValid()).ifPresent(t -> {
        VatDetail vd = t.getRight();
        String billingAddress = vd.getName() + "\n" + vd.getAddress();
        PriceContainer.VatStatus vatStatus = determineVatStatus(t.getLeft().getVatStatus(),
                t.getRight().isVatExempt());
        ticketReservationRepository.updateBillingData(vatStatus, vd.getVatNr(), country,
                paymentForm.isInvoiceRequested(), reservationId);
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId,
                t.getLeft(), Locale.forLanguageTag(t.getMiddle().getUserLanguage()));
        ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId,
                Json.toJson(orderSummary));
        ticketReservationRepository.updateTicketReservation(reservationId, t.getMiddle().getStatus().name(),
                paymentForm.getEmail(), paymentForm.getFullName(), paymentForm.getFirstName(),
                paymentForm.getLastName(), locale.getLanguage(), billingAddress, null,
                Optional.ofNullable(paymentForm.getPaymentMethod()).map(PaymentProxy::name).orElse(null));
        paymentForm.getTickets().forEach((ticketId, owner) -> {
            if (isNotEmpty(owner.getEmail())
                    && ((isNotEmpty(owner.getFirstName()) && isNotEmpty(owner.getLastName()))
                            || isNotEmpty(owner.getFullName()))) {
                ticketHelper.preAssignTicket(eventName, reservationId, ticketId, owner, Optional.empty(),
                        request, (tr) -> {
                        }, Optional.empty());
            }
        });
    });

    return vatDetail.map(Triple::getRight).map(vd -> {
        if (vd.isValid()) {
            return ResponseEntity.ok(vd);
        } else {
            return new ResponseEntity<VatDetail>(HttpStatus.BAD_REQUEST);
        }
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}