|
| 1 | +package com.flowingcode.vaadin.addons.errorwindow; |
| 2 | + |
| 3 | +import com.vaadin.flow.i18n.I18NProvider; |
| 4 | +import java.text.MessageFormat; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Collections; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Locale; |
| 9 | +import java.util.MissingResourceException; |
| 10 | +import java.util.ResourceBundle; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | + |
| 13 | +public class TranslationProvider implements I18NProvider { |
| 14 | + |
| 15 | + public static final String BUNDLE_PREFIX = "messages"; |
| 16 | + |
| 17 | + public final Locale LOCALE_ES = new Locale("es"); |
| 18 | + public final Locale LOCALE_EN = new Locale("en"); |
| 19 | + |
| 20 | + private List<Locale> locales = Collections.unmodifiableList(Arrays.asList(LOCALE_ES, LOCALE_EN)); |
| 21 | + |
| 22 | + @Override |
| 23 | + public List<Locale> getProvidedLocales() { |
| 24 | + return locales; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public String getTranslation(String key, Locale locale, Object... params) { |
| 29 | + if (key == null) { |
| 30 | + LoggerFactory.getLogger(TranslationProvider.class.getName()) |
| 31 | + .warn("Got lang request for key with null value!"); |
| 32 | + return ""; |
| 33 | + } |
| 34 | + |
| 35 | + final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_PREFIX, locale); |
| 36 | + |
| 37 | + String value; |
| 38 | + try { |
| 39 | + value = bundle.getString(key); |
| 40 | + } catch (final MissingResourceException e) { |
| 41 | + LoggerFactory.getLogger(TranslationProvider.class.getName()).warn("Missing resource", e); |
| 42 | + return "!" + locale.getLanguage() + ": " + key; |
| 43 | + } |
| 44 | + if (params.length > 0) { |
| 45 | + value = MessageFormat.format(value, params); |
| 46 | + } |
| 47 | + return value; |
| 48 | + } |
| 49 | +} |
0 commit comments