I18N localization

To use localization and translation strings the application only needs to implement I18NProvider and define the fully qualified class name in the property i18n.provider.

Defining the i18n provider property

The i18n.provider property can be set from the command line as a system property, as a Servlet init parameter in the web.xml or using the @WebServlet annotation.

As a system property the parameter needs the vaadin prefix e.g.:

bash

  1. mvn jetty:run -Dvaadin.i18n.provider=com.vaadin.example.ui.TranslationProvider

When using the annotation you could have the servlet class as:

Java

  1. @WebServlet(urlPatterns = "/*", name = "slot", asyncSupported = true, initParams = {
  2. @WebInitParam(name = Constants.I18N_PROVIDER, value = "com.vaadin.example.ui.TranslationProvider") })
  3. public class ApplicationServlet extends VaadinServlet {
  4. }

Or when using the web.xml file:

XML

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app
  3. id="WebApp_ID" version="3.0"
  4. xmlns="http://java.sun.com/xml/ns/j2ee"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  7. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  8. <servlet>
  9. <servlet-name>myservlet</servlet-name>
  10. <servlet-class>
  11. com.vaadin.server.VaadinServlet
  12. </servlet-class>
  13. <init-param>
  14. <param-name>i18n.provider</param-name>
  15. <param-value>com.vaadin.example.ui.TranslationProvider</param-value>
  16. </init-param>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>myservlet</servlet-name>
  20. <url-pattern>/*</url-pattern>
  21. </servlet-mapping>
  22. </web-app>

You may provide a I18NProvider as a bean in case you are using Spring. All you need in this case it’s just annotate your implementation with @Component so it becomes available as a Spring bean. Spring add-on will automatically use it in case if it’s available. See the class SimpleI18NProvider.java implemented in the tutorial project as an example.

Locale selection for new session

The initial locale is decided by matching the locales provided by the I18NProvider against the Accept-Language header in the initial response from the client.

If an exact match (language + country) is found that will then be used, else we will try to match on only language. If neither is found the locale will be set to the first ‘supported’ locale from I18NProvider.getProvidedLocales() and if that is empty Locale.getDefault() will be used.

Provider sample for translation

For this example we enable Finnish and English to be used with Finnish being the “default” that is used if the user client doesn’t specify english as an accepted language.

In this sample the language .properties files start with “translate” e.g. translate.properties (for default), translate_fi_FI.properties and translate_en_GB.properties

The translation properties files are in the example loaded using the class loader so they should be located on the classpath for example in the resources folder e.g. src/main/resources for a default maven setup.

The LoadingCache used in the implementation is from the Google Guava package.

Sample i18n provider implementation

  1. public class TranslationProvider implements I18NProvider {
  2. public static final String BUNDLE_PREFIX = "translate";
  3. public final Locale LOCALE_FI = new Locale("fi", "FI");
  4. public final Locale LOCALE_EN = new Locale("en", "GB");
  5. private List<Locale> locales = Collections
  6. .unmodifiableList(Arrays.asList(LOCALE_FI, LOCALE_EN));
  7. private static final LoadingCache<Locale, ResourceBundle> bundleCache = CacheBuilder
  8. .newBuilder().expireAfterWrite(1, TimeUnit.DAYS)
  9. .build(new CacheLoader<Locale, ResourceBundle>() {
  10. @Override
  11. public ResourceBundle load(final Locale key) throws Exception {
  12. return initializeBundle(key);
  13. }
  14. });
  15. @Override
  16. public List<Locale> getProvidedLocales() {
  17. return locales;
  18. }
  19. @Override
  20. public String getTranslation(String key, Locale locale, Object... params) {
  21. if (key == null) {
  22. LoggerFactory.getLogger(TranslationProvider.class.getName())
  23. .warn("Got lang request for key with null value!");
  24. return "";
  25. }
  26. final ResourceBundle bundle = bundleCache.getUnchecked(locale);
  27. String value;
  28. try {
  29. value = bundle.getString(key);
  30. } catch (final MissingResourceException e) {
  31. LoggerFactory.getLogger(TranslationProvider.class.getName())
  32. .warn("Missing resource", e);
  33. return "!" + locale.getLanguage() + ": " + key;
  34. }
  35. if (params.length > 0) {
  36. value = MessageFormat.format(value, params);
  37. }
  38. return value;
  39. }
  40. private static ResourceBundle initializeBundle(final Locale locale) {
  41. return readProperties(locale);
  42. }
  43. protected static ResourceBundle readProperties(final Locale locale) {
  44. final ClassLoader cl = TranslationProvider.class.getClassLoader();
  45. ResourceBundle propertiesBundle = null;
  46. try {
  47. propertiesBundle = ResourceBundle.getBundle(BUNDLE_PREFIX, locale,
  48. cl);
  49. } catch (final MissingResourceException e) {
  50. LoggerFactory.getLogger(TranslationProvider.class.getName())
  51. .warn("Missing resource", e);
  52. }
  53. return propertiesBundle;
  54. }
  55. }

Using localization in the application

Using the internationalization in the application is a combination of using the I18NProvider and updating the translations on locale change.

To make this simple the application classes that control the captions and texts that are localized can implement the LocaleChangeObserver to receive events for locale change.

This observer will also be notified on navigation in the attach phase of before navigation after any url parameters are set, so that the state from a url parameter can be used.

Java

  1. public class LocaleObserver extends Div implements LocaleChangeObserver {
  2. @Override
  3. public void localeChange(LocaleChangeEvent event) {
  4. setText(getTranslation("my.translation", getUserId()));
  5. }
  6. }

Using localization without using LocaleChangeObserver

I18NProvider without LocaleChangeObserver

  1. public class MyLocale extends Div {
  2. public MyLocale() {
  3. setText(getTranslation("my.translation", getUserId()));
  4. }
  5. }