On my previous posts I introduced GNU gettext utilities and showed how to setup Gettext Commons library for Java. In this new post, I’ll focus on how to use Gettext Commons library for i18n Java files.

The result of  tagging and post-processing source code using GNU gettext utilities is generally a binary file which can later be used from a target programming language. In Java, this binary file is called a resource bundle, with extension .class. There are as many resource bundle files as locale.po files exist in our application. For each locale, there’s a Messages_XX.class file. Basically, a resource bundle is a collection of msgids and its corresponding locale translations. Let’s see how it works:

class MyClass {
   I18n i18n = I18NFactory.getI18n(this.getClass(),
         new Locale("Es", "es"),
         org.xnap.commons.i18n.I18nFactory.FALLBACK);

   public void render() {
      Listheader listheader = new Listheader(i18n.tr("Header"));
   }
}

For i18n a text string in source code, we need to instantiate a I18n object before by calling I18NFactory.getI18(). This static method returns a specific resource bundle, depending on the calling paremeters. In the example above, I asked for a resource bundle for locale es_ES (Spanish language, Spanish dialect from Spain). The third parameter is a flag sign indicating that in case such resource bundle doesn’t exist a default resource bundle will be returned. A default resource bundle does actually nothing, it simply returns i18n marked strings as they are.

On the render() method, I wrapped “Resource” *within a i18n.tr function. This function is used to mark texts to be internationalized. Later we should parametrized gettext command properly so it can recognize *tr as a marker, and fetch msgids from it. On the other hand, typing i18n.tr every time we need to mark a text, plus instantiating a i18n object for every* .java *file,  can be tedious and repetitive. Fortunately, this can be improved:

public class I18nHelper {
I18n i18n = I18nFactory.getI18n(I18nHelper.class,
new Locale("Es", "es"),
 org.xnap.commons.i18n.I18nFactory.FALLBACK);

 public static String _(String str) {
 return i18n.tr(str);
}

So, later we just need to add a static import of _ from other Java file, and we’re ready to go (in case of using _ as marker, call xgettext with* -k _*)

import static org.navalplanner.web.I18nHelper._;

class MyClass {
   public void render() {
      Listheader listheader = new Listheader(_("Header"));
   }
}

In this post, I have reviewed how to use Gettext Commons java library for i18n strings spread across source code. On my next post, I will focus on the more specific case of i18n ZUL pages, UI XML files from ZK framework, using Gettext, of course 😉