/** * Gets the NumberFormat to use to convert values * @param locale Locale to use * @return the numberFormat If a NumberFormat was specified using {@link #setNumberFormat(NumberFormat)}, this one * is returned. Otherwise, a NumberFormat is obtained using given Locale */ public NumberFormat getNumberFormat(Locale locale) { Locale lcl = (locale != null) ? locale : LocalizationContext.getCurrent().filter(l -> l.isLocalized()).flatMap(l -> l.getLocale()) .orElse(Locale.getDefault()); return (numberFormat != null) ? numberFormat : TypeUtils.isDecimalNumber(numberType) ? NumberFormat.getNumberInstance(lcl) : NumberFormat.getIntegerInstance(lcl); }
/** * Convert a {@link Localizable} value * @param value Value to convert * @return String value */ private static String convertLocalizable(Localizable value) { return LocalizationContext.translate(value, true); }
public void localization() { // tag::localization[] LocalizationContext ctx = LocalizationContext.builder() .withMessageProvider(MessageProvider.fromProperties("messages").build()).withInitialLocale(Locale.US) .build(); ctx.getLocale().ifPresent(l -> System.out.println(l)); // <1> String localizedMessage = ctx.getMessage("test.message", "defaultMessage"); // <2> localizedMessage = ctx .getMessage(Localizable.builder().message("defaultMessage").messageCode("test.message").build()); // <3> ctx.format(2.56); // <4> ctx.format(0.5, NumberFormatFeature.PERCENT_STYLE); // <5> ctx.format(5600.678, 2); // <6> NumberFormat nf = ctx.getNumberFormat(Integer.class); // <7> ctx.format(new Date(), TemporalType.DATE); // <8> ctx.format(new Date(), TemporalType.DATE_TIME, TemporalFormat.LONG, TemporalFormat.LONG); // <9> ctx.format(LocalDate.of(2017, Month.MARCH, 15)); // <10> ctx.format(LocalDateTime.of(2017, Month.MARCH, 15, 16, 48), TemporalFormat.FULL, TemporalFormat.SHORT); // <11> DateFormat df = ctx.getDateFormat(TemporalType.DATE); // <12> DateTimeFormatter dtf = ctx.getDateTimeFormatter(TemporalType.DATE_TIME); // <13> // end::localization[] }
/** * Convert a {@link Boolean} value * @param value Value to convert * @return String value */ private static String convertBoolean(Boolean value) { return LocalizationContext.getCurrent().flatMap(u -> u.getDefaultBooleanLocalization(value)) .map(m -> LocalizationContext.translate(m, true)).orElse(String.valueOf(value)); }
/** * Convert a {@link Date} value * @param value Value to convert * @param type Temporal type * @return String value */ private static String convertDate(Date value, TemporalType type) { if (value != null) { return LocalizationContext.getCurrent().filter(l -> l.isLocalized()).map((c) -> c.format(value, type)) .orElse(DateFormat.getDateInstance().format(value)); } return null; }
/** * Requires the current {@link LocalizationContext}, checking that it is localized. If not available using * {@link #getCurrent()}, an {@link IllegalStateException} is thrown. If not localized, a * {@link LocalizationException} is thrown instead. * @return Current LocalizationContext * @throws IllegalStateException LocalizationContext is not available as a {@link Context} resource * @throws LocalizationException A LocalizationContext is available as context resource but it is not localized * @see #isLocalized() */ static LocalizationContext requireLocalized() { LocalizationContext localizationContext = require(); if (!localizationContext.isLocalized()) { throw new LocalizationException("LocalizationContext is not localized"); } return localizationContext; }
/** * Renders a numeric value type Field * @param property Property to render * @return Field instance */ @SuppressWarnings("unchecked") protected Field<T> renderNumber(Property<? extends T> property) { // Number format Class<? extends Number> type = (Class<? extends Number>) property.getType(); int decimals = property.getConfiguration().getParameter(StringValuePresenter.DECIMAL_POSITIONS).orElse(-1); boolean disableGrouping = property.getConfiguration().getParameter(StringValuePresenter.DISABLE_GROUPING) .orElse(Boolean.FALSE); Locale locale = LocalizationContext.getCurrent().filter(l -> l.isLocalized()).flatMap(l -> l.getLocale()) .orElse(Locale.getDefault()); NumberFormat numberFormat = LocalizationContext.getCurrent().filter(l -> l.isLocalized()) .map((l) -> l.getNumberFormat(type, decimals, disableGrouping)) .orElse(TypeUtils.isDecimalNumber(property.getType()) ? NumberFormat.getNumberInstance(locale) : NumberFormat.getIntegerInstance(locale)); if (decimals > -1) { numberFormat.setMinimumFractionDigits(decimals); numberFormat.setMaximumFractionDigits(decimals); } if (disableGrouping) { numberFormat.setGroupingUsed(false); } return postProcessField(input.number(type).numberFormat(numberFormat).asField(), property); }
public void sessionscope() { // tag::sessionscope[] VaadinSession.getCurrent().setAttribute(LocalizationContext.CONTEXT_KEY, LocalizationContext.builder().withInitialLocale(Locale.US).build()); // <1> LocalizationContext.getCurrent().ifPresent(localizationContext -> { // <2> // LocalizationContext obtained from current Vaadin session }); // end::sessionscope[] }
public void localize() { // tag::localize[] LocalizationContext localizationContext = LocalizationContext.getCurrent() .orElseThrow(() -> new IllegalStateException("Missing LocalizationContext")); // <1> localizationContext.localize(Locale.US); // <2> boolean localized = localizationContext.isLocalized(); // <3> localizationContext.localize(Localization.builder(Locale.JAPAN).defaultDecimalPositions(2) .defaultDateTemporalFormat(TemporalFormat.FULL).build()); // <4> // end::localize[] }
/** * Try to translate given <code>localizable</code> using the {@link LocalizationContext} available as * {@link Context} resource through {@link LocalizationContext#getCurrent()}. The LocalizationContext must be * localized. * @param localizable Localizable to translate * @param lenient if <code>true</code> and a {@link LocalizationContext} is not available or it is not localized, * silently return default {@link Localizable#getMessage()}. If <code>false</code>, a * {@link LocalizationException} is thrown for that situation * @return The localized message, or default {@link Localizable#getMessage()} if a localized LocalizationContext is * not available and lenient is <code>true</code>, or {@link Localizable#getMessageCode()} is * <code>null</code>. */ static String translate(final Localizable localizable, final boolean lenient) { ObjectUtils.argumentNotNull(localizable, "Localizable must be not null"); Optional<LocalizationContext> lc = LocalizationContext.getCurrent().filter(l -> l.isLocalized()); if (!lc.isPresent() && !lenient) { throw new LocalizationException( "A LocalizationContext is not available from context or it is not localized"); } return lc.map(l -> l.getMessage(localizable, lenient)) .orElse(FormatUtils.resolveMessageArguments(MessageProvider.DEFAULT_MESSAGE_ARGUMENT_PLACEHOLDER, localizable.getMessage(), localizable.getMessageArguments())); }
@Override public Optional<Locale> getLocale() { // check UI final UI currentUi = UI.getCurrent(); Locale locale = currentUi == null ? null : currentUi.getLocale(); if (locale == null) { // check LocalizationContext locale = getLocalizationContext().filter(l -> l.isLocalized()).flatMap(l -> l.getLocale()).orElse(null); } if (locale == null) { // check I18NProvider locale = getI18nProvider().map(p -> { List<Locale> locales = p.getProvidedLocales(); if (locales != null && !locales.isEmpty()) { return locales.get(0); } return null; }).orElse(null); } return Optional.ofNullable(locale); }
/** * Get the {@link LocalizationContext} context to use. * @return The configured {@link LocalizationContext} or the context {@link LocalizationContext}, if available */ protected Optional<LocalizationContext> getLocalizationContext() { if (localizationContext != null) { return Optional.of(localizationContext); } return LocalizationContext.getCurrent(); }
.getCurrent().flatMap(l -> l.asMessageResolver().getMessage(locale, localizable.getMessageCode(), localizable.getMessageArguments())) .orElse(localizable.getMessage()));
public void missingLocalization() { // tag::missing[] LocalizationContext ctx = LocalizationContext.builder() .withMissingMessageLocalizationListener((locale, messageCode, defaultMessage) -> { // <1> LOGGER.warn("Missing message localization [" + messageCode + "] for locale [" + locale + "]"); }).build(); // end::missing[] }
/** * Get a {@link NumberFormat} for numbers formatting and set it up according to context {@link Locale} and * {@link Localization} settings. * @param numberType Number type * @return NumberFormat * @throws LocalizationException If context is not localized */ default NumberFormat getNumberFormat(Class<? extends Number> numberType) { return getNumberFormat(numberType, -1, false); }
/** * Format given {@link LocalDate} according to current Context {@link Locale} using given date format style. * @param temporal Date to format (may be null) * @param dateFormat Date format style * @return Formatted temporal, or <code>null</code> if given temporal was null * @throws LocalizationException If context is not localized */ default String format(LocalDate temporal, TemporalFormat dateFormat) { return format(temporal, dateFormat, TemporalFormat.DEFAULT); }
/** * Renders a numeric value type Field * @param property Property to render * @return Field instance */ @SuppressWarnings("unchecked") protected Field<T> renderNumber(Property<? extends T> property) { // Number format Class<? extends Number> type = (Class<? extends Number>) property.getType(); int decimals = property.getConfiguration().getParameter(StringValuePresenter.DECIMAL_POSITIONS).orElse(-1); boolean disableGrouping = property.getConfiguration().getParameter(StringValuePresenter.DISABLE_GROUPING) .orElse(Boolean.FALSE); Locale locale = LocalizationContext.getCurrent().filter(l -> l.isLocalized()).flatMap(l -> l.getLocale()) .orElse(Locale.getDefault()); NumberFormat numberFormat = LocalizationContext.getCurrent().filter(l -> l.isLocalized()) .map((l) -> l.getNumberFormat(type, decimals, disableGrouping)) .orElse(TypeUtils.isDecimalNumber(property.getType()) ? NumberFormat.getNumberInstance(locale) : NumberFormat.getIntegerInstance(locale)); if (decimals > -1) { numberFormat.setMinimumFractionDigits(decimals); numberFormat.setMaximumFractionDigits(decimals); } if (disableGrouping) { numberFormat.setGroupingUsed(false); } return postProcessField(input.number(type).numberFormat(numberFormat).asField(), property); }
/** * Convert a {@link Temporal} value * @param value Value to convert * @return String value */ private static String convertTemporal(Temporal value) { if (value != null) { return LocalizationContext.getCurrent().filter(l -> l.isLocalized()).map((c) -> c.format(value)) .orElse(convertTemporalWithDefaultLocale(value)); } return null; }
public void sessionscope() { // tag::sessionscope[] VaadinSession.getCurrent().setAttribute(LocalizationContext.CONTEXT_KEY, LocalizationContext.builder().withInitialLocale(Locale.US).build()); // <1> LocalizationContext.getCurrent().ifPresent(localizationContext -> { // <2> // LocalizationContext obtained from current Vaadin session }); // end::sessionscope[] }