Table of contents
1.
Introduction
2.
Defining the i18n.provider Property
2.1.
Using Servlet Class
2.2.
Using Web.xml
3.
Locale Selection for New Session
4.
Example of Using I18NProvider for Translation
5.
Using Localization in the Application
5.1.
With Using LocaleChangeObserver
5.2.
Without Using LocaleChangeObserve
5.3.
Supporting Right-to-Left Mode
6.
Adding RTL Support
7.
Frequently Asked Questions
7.1.
What is Vaadin?
7.2.
How to install vaadin add-ons?
7.3.
What is DirMixin?
8.
Conclusion
Last Updated: Mar 27, 2024

Localization

Author Rhythm Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Vaadin is a web development framework that is free source. It has built-in support for Java scripts and AJAX. You may also use Google Web Toolkit to incorporate external features. Vaadin saves developers time by rendering rich content in the browser without using markup files.

To use localization and translation strings, the application must implement I18NProvider and specify the fully qualified class name in the i18n.provider field.

Defining the i18n.provider Property

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

The parameter requires the vaadin prefix as a system attribute, for example:

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

Using Servlet Class

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

Using Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
 id="WebApp_ID" version="3.0"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>
       com.vaadin.flow.server.VaadinServlet
   </servlet-class>
   <init-param>
     <param-name>i18n.provider</param-name>
     <param-value>com.vaadin.example.ui.TranslationProvider</param-value>
   </init-param>
 </servlet>
 <servlet-mapping>
   <servlet-name>myservlet</servlet-name>
   <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

Locale Selection for New Session

The first locale is determined by comparing the locales given by the I18NProvider to the Accept-Language header in the client's initial response.

This will be utilized if an exact match (language + country) is identified. Otherwise, it tries to match based just on language. If none is available, the locale is set to the first 'supported' locale returned by I18NProvider.getProvidedLocales (). Locale.getDefault() will be used if it is not specified.

Example of Using I18NProvider for Translation

This example uses the class loader to load the translation properties files. As a result, they should be placed on the classpath, such as in the resources folder. This would be src/main/resources in a standard Maven configuration.

public class TranslationProvider implements I18NProvider {
   public static final String BUNDLE_PREFIX = "translate";
   public final Locale LOCALE_FI = new Locale("fi", "FI");
   public final Locale LOCALE_EN = new Locale("en", "GB");
   private List<Locale> locales = Collections
           .unmodifiableList(Arrays.asList(LOCALE_FI, LOCALE_EN));
   @Override
   public List<Locale> getProvidedLocales() {
       return locales;
   }
   @Override
   public String getTranslation(String key, Locale locale, Object... params) {
       if (key == null) {
           LoggerFactory.getLogger(TranslationProvider.class.getName())
                   .warn("Got lang request for key with null value!");
           return "";
       }
       final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_PREFIX, locale);
       String value;
       try {
           value = bundle.getString(key);
       } catch (final MissingResourceException e) {
           LoggerFactory.getLogger(TranslationProvider.class.getName())
                   .warn("Missing resource", e);
           return "!" + locale.getLanguage() + ": " + key;
       }
       if (params.length > 0) {
           value = MessageFormat.format(value, params);
       }
       return value;
   }
}

Using Localization in the Application

Internationalization in the application is accomplished by the use of I18NProvider and the update of translations when the locale changes. To simplify things, the application classes that manage the translated captions and texts can implement LocaleChangeObserver to receive events related to locale change.

This observer will be informed when the component is attached before onAttach() is executed. The navigation's URL parameters are configured so that they may be utilized to identify the state.

With Using LocaleChangeObserver

public class LocaleObserver extends Div implements LocaleChangeObserver {


    @Override
    public void localeChange(LocaleChangeEvent event) {
        setText(getTranslation("my.translation", getUserId()));
    }
}

Without Using LocaleChangeObserve

public class MyLocale extends Div {
   public MyLocale() {
       setText(getTranslation("my.translation", getUserId()));
   }
}

Supporting Right-to-Left Mode

Vaadin components support right-to-left languages. The members will operate in this mode out of the box, but you will need to make a few adjustments to allow your application to support both left-to-right and right-to-left modes.

public class MainLayout extends VerticalLayout {


    public MainLayout() {
        // ...
        final UI ui = UI.getCurrent();
        if (ui.getLocale().getLanguage() == "ar") {
            ui.setDirection(Direction.RIGHT_TO_LEFT);
        }
    }
}


You may have your main layout implement the LocaleChangeObserver interface if the user can select their language, for example, on your application's settings page. As a result, it will receive changes in locale, allowing you to modify the text direction based on the provided site:

public class MainLayout extends VerticalLayout implements LocaleChangeObserver {
   @Override
   public void localeChange(LocaleChangeEvent event) {
       if (event.getLocale().getLanguage() == "ar") {
           event.getUI().setDirection(Direction.RIGHT_TO_LEFT);
       } else {
           event.getUI().setDirection(Direction.LEFT_TO_RIGHT);
       }
   }
}

Adding RTL Support

If you have your custom components or your application has unique styles, you must take the following steps to provide right-to-left support to them:

  1. There are no modifications required if your element extends Vaadin's ElementMixin. Otherwise, you may have the element, extend it, or use DirMixin.
     
  2. Make sure your styles are correctly adjusted for right-to-left mode.
     
  3. ​​If your element defines direction with icons or Unicode symbols, you may need to use the correct icons or logos for right-to-left mode.
     
  4. If you utilize keyboard interactions, such as arrow keys to traverse between things, be sure to verify whether dir is rtl and use this to specify the movement's direction.
     
  5. Whether your custom element depends on a JavaScript calculation for scaling, location, and horizontal scroll, see if it needs to be adjusted for right-to-left navigation.
     
  6. If you have visual tests, you may wish to create new ones or change existing ones to run in right-to-left mode.

Frequently Asked Questions

What is Vaadin?

Vaadin is an open-source web application development platform for Java. Vaadin has a set of Web Components, a Java web framework, and tools that allow developers to execute modern web graphical user interfaces using the Java language only, TypeScript only, or a combination of both.

How to install vaadin add-ons?

​​Installing add-ons from the Vaadin Directory is as simple as adding a Maven or Ivy dependency or downloading the JAR file and dumping it in the project's web library folder.

What is DirMixin?

The DirMixin registers the element to respond to document-level changes in the dir attribute and keeps it in sync with the element's dir attribute. This is useful for quickly checking the text-direction state in both CSS and JS code.

Conclusion

We hope this blog has helped you enhance your Knowledge about Vaadin Localization.

To learn more about machine learning, you can visit Machine Learning.

See Basics of C++ with Data StructureDBMSOperating System by Coding Ninjas, and keep practicing on our platform Coding Ninjas Studio.

If you think you are ready for the tech giants company, check out the mock test series on code studio.

You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in domains like Data Structures and AlgorithmsCompetitive ProgrammingAptitude, and many more! You can also prepare for tech giants companies like Amazon, Microsoft, Uber, etc., by looking for the questions asked by them in recent interviews. If you want to prepare for placements, refer to the interview bundle. If you are nervous about your interviews, you can see interview experiences to get ideas about these companies' questions.

Nevertheless, you may consider our premium courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Thank you image

 

Live masterclass