/** * Get the localized message for given {@link Localizable}. * @param localizable Localizable message * @return Localized message, or default {@link Localizable#getMessage()} if {@link Localizable#getMessageCode()} is * null * @throws LocalizationException If context is not localized */ default String getMessage(Localizable localizable) { return getMessage(localizable, false); }
/** * 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())); }
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[] }