ResGen: Eigenbase Resource Generator

Julian Hyde; last updated September, 2005.


ResGen (the Eigenbase Resource Generator) helps you build and maintain internationalized applications in Java. From a simple XML file, it generates classes to access those resources in a type-safe manner. It is tightly integrated with ANT, to make the development process painless; and it supports a variety of schemes to determine the current locale.

Let's take a look at a simple example.

Example

The following example shows how you would define a simple resource file, generate resource classes from it, and use those classes in your own code.

Create a resource file

First, create a resource file like the following, BirthdayResource_en_US.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="Resource.xsl" ?>
<resourceBundle locale="en_US">
  <message name="HappyBirthday">
    <text>Happy Birthday, {0}! You don''t look {1,number}.</text>
  </message>
  <exception name="TooYoung" className="RuntimeException">
    <text>{0} has not been born yet.</text>
  </exception>
</resourceBundle>

The top-level element of a resource file is always a <resourceBundle>, and the only necessary property is the locale of the current file. Its children are a mixture of <message> and <exception> elements. Each must have a name attribute and a <text> child holding the message string.

Create ANT target

Now modify your ANT build-file, build.xml, as follows:

<taskdef name="resgen" classname="org.eigenbase.resgen.ResourceGenTask">
  <classpath path="lib/eigenbase-resgen.jar:lib/eigenbase-xom.jar"/>
</taskdef>

<target name="generate.resources">
  <resgen srcdir="source" locales="en_US">
    <include name="happy/BirthdayResource_en_US.xml"/>
  </resgen>
</target>

<target name="compile" depends="generate.resources">
  <javac srcdir="source" destdir="classes">
    <include name="happy/BirthdayResource*.java"/>
  </javac>
  <copy todir="classes">
    <fileset dir="source" includes="**/*.properties"/>
  </copy>
</target>

I have assumed that your Java source files are held in the "source" directory, and classes are compiled to classes directory, but this ought to be easy to change. If you already have a target to compile Java source files, you don't need the "compile" target; just add its contents to your own target.

Compile

Build as follows. (You need 'ant' on your path, and you will need to edit the project.classpath property in build.xml.)

$ ant
Buildfile: build.xml

generate.resources:
[resgen] Generating source\happy\BirthdayResource.java
[resgen] Generating source\happy\BirthdayResource_en_US.java
[resgen] Generating source\happy\BirthdayResource_en_US.properties

compile:
[javac] Compiling 2 source files to classes
[copy] Copying 1 files to classes

BUILD SUCCESSFUL

Total time: 3 seconds

Four files are generated.

source/happy/BirthdayResource.java:

package happy;

import java.io.IOException;
import java.util.Locale;
import org.eigenbase.resgen.*;

class BirthdayResource extends ShadowResourceBundle {
    public BirthdayResource() throws IOException {
    }
    private static String baseName = "happy.BirthdayResource";
    /**
      * Retrieves the singleton instance of {@link BirthdayResource}. If
      * the application has called {@link #setThreadLocale}, returns the
      * resource for the thread's locale.
      */
    public static synchronized BirthdayResource instance() {
        return (BirthdayResource) instance(baseName);
    }
    /**
      * Retrieves the instance of {@link BirthdayResource} for the given locale.
      */
    public static synchronized BirthdayResource instance(Locale locale) {
        return (BirthdayResource) instance(baseName, locale);
    }
    /** HappyBirthday is 'Happy Birthday, {0}! You don''t look {1,number} at all.' */
    public static final ResourceDefinition HappyBirthday = new ResourceDefinition("HappyBirthday", "Happy Birthday, {0}! You don''t look {1,number} at all.");
    public static String getHappyBirthday(String p0, Number p1) {
        return HappyBirthday.instantiate(
            getInstance(), new Object[] {p0, p1}).toString();
    }
    /** TooYoung is '{0} has not been born yet.' */
    public static final ResourceDefinition TooYoung = new ResourceDefinition("TooYoung", "{0} has not been born yet.");
    public static String getTooYoung(String p0) {
        return HappyBirthday.instantiate(
            getInstance(), new Object[] {p0}).toString();
    }
     public static RuntimeException newTooYoung(String p0) {
        return new RuntimeException(TooYoung.instantiate(
            getInstance(), new Object[] {p0}), null);
    }
    public static RuntimeException newTooYoung(String p0, Throwable err) {
        return new RuntimeException(TooYoung.instantiate(
            getInstance(), new Object[] {p0}), err);
    }
}

source/happy/BirthdayResource_en_US.java:

package happy;
import java.io.IOException;

public class BirthdayResource_en_US extends BirthdayResource {
    public BirthdayResource_en_US() throws IOException {}
}

source/happy/BirthdayResource.properties:

HappyBirthday=Happy Birthday, {0}! You don''t look {1,number}.
TooYoung={0} has not been born yet.

source/happy/BirthdayResource_en_US.properties:

# This file is intentionally blank. Add property values
# to this file to override the translations in the base
# properties file, BirthdayResource.properties.

For each resource, a getXxx() method is generated to retrieve that resource in the current locale, substituting parameters appropriately. For exception resources, an additional two newXxx() methods are generated to create (but not throw) an exception.

Tokens such as {0} and {1,number} in the message are automatically converted to method parameters of the right type. This means that if you ever change the parameters in your error message, or accidentally delete it, you code will no longer build. (If your code doesn't compile, you can fix the problem immediately; better that than getting a phone call, "I just got this really weird error...", in a few months time.)

Here's how you might use it in your code:

import happy.BirthdayResource;

public class Birthday {
    static void wishHappyBirthday(String name, int age) {
        if (age < 0) {
            throw BirthdayResource.newTooYoung(name);
        }
        System.out.println(BirthdayResource.getHappyBirthday(name, age));
    }
    public static void main(String[] args) {
        wishHappyBirthday("Fred", 33);
        wishHappyBirthday("Wilma", -3);
    }
}

This produces the following output.

Happy Birthday, Fred! You don't look 33.
RuntimeException: Wilma has not been born yet.

So there are the basics. That was easy, wasn't it? Now let's look at how you can tell the system to switch to another locale, and how you go about producing resource files for that locale.

Of locales and threads

When you ask for a message, the system needs to know the locale in order to get the right translation. There are several strategies for this.

The simplest strategy is to do nothing. Most applications run in the same locale as their host machine, and so when the system calls Locale.getDefault(), it will return the right answer.

You can switch locale by calling Locale.getDefault(Locale newLocale), but this call will affect other applications running in the same Java Virtual Machine, and is not allowed in some application server environments.

ResGen provides a method ShadowResourceBundle.setThreadLocale(Locale) to allow threads to have different locales. Threads which are working in a different locale should call this method at their entry point. For example:

System.out.println(BirthdayResource.getHappyBirthday("Fred", 33));
ShadowResourceBundle.setThreadLocale(Locale.FR);
System.out.println(BirthdayResource.getHappyBirthday("Pierre", 22));

produces the output

Happy Birthday, Fred! You don't look 33.
Bon anniversaire, Pièrre! 22, quel bon âge.

Threads which have not made this call will remain in the default locale.

This strategy may not be possible if the threading model is complex. Here, you should use an explicit resource bundle object:

BirthdayResource myResource = BirthdayResource.instance();
System.out.println(myResource.getHappyBirthday("Fred", 33));
myResource = BirthdayResource.instance(Locale.FR);
System.out.println(myResource.getHappyBirthday("Pierre", 22));

The problem is that the accessor methods (getHappyBirthday, and so forth) are static. To make them non-static, change add static="false" to the <resgen> ANT task:

<target name="generate.resources">
  <resgen srcdir="source" style="dynamic">
    <include name="happy/BirthdayResource_en_US.xml"/>
  </resgen>
</target>

Translation

So far, we've just been dealing with one resource file, and you're probably wondering why you went to all the trouble of extracting your messages and exception strings! Have no fear, there will be more. A typical development process goes as follows.

First, you develop your application for a single locale, referred to as the base locale. I have been assuming that this American English (en_US), but you can develop in any locale you choose.

You create an XML file for this language containing all the messages and exceptions used by your application. Developers are often tempted to put in hard-coded strings, but ResGen's tight integration with ANT makes it painless to modify the XML file and re-generate the wrapper as you go.

So now you have an application in the beta stage. You're written most of the code, are getting through the pile of bugs, and would like to translate the product into French (fr_FR). Recall that in the above example, we were dealing with the following set of files.

Source files happy/BirthdayResource_en_US.xml
Generated files happy/BirthdayResource.java
happy/BirthdayResource.properties
happy/BirthdayResource_en_US.java
happy/BirthdayResource_en_US.properties
Runtime files happy/BirthdayResource.class
happy/BirthdayResource.properties
happy/BirthdayResource_en_US.class
happy/BirthdayResource_en_US.properties

Do the following steps:

  1. Copy happy/BirthdayResource.properties  to happy/BirthdayResource_fr_FR.properties, and translate the messages as appropriate for the new locale:
    HappyBirthday=Bon anniversaire, {0}! {1,number}, c'est un bon age.
    TooYoung={0} n'est pas encore né(e).

     

  2. Add happy/BirthdayResource_fr_FR.properties to the ANT task:
    <target name="generate.resources">
      <resgen srcdir="source" locales="en_US,fr_FR">
        <include name="happy/BirthdayResource_en_US.xml"/>
        <include name="happy/BirthdayResource_fr_FR.properties"/>
       </resgen>
    </target>
  3. Build.

ResGen treats happy/BirthdayResource_fr_FR.properties as a source file. It generates happy/BirthdayResource_fr_FR.java from it, and validates that every resource in happy/BirthdayResource_fr_FR.properties exists in happy/BirthdayResource_en_US.xml, and has the same number and types of parameters.

In this multi-language scenario, the source and generated files are as follows (new files are shown in italic):

Source files happy/BirthdayResource_en_US.xml
happy/BirthdayResource_fr_FR.properties
Generated files happy/BirthdayResource.java
happy/BirthdayResource.properties
happy/BirthdayResource_en_US.java
happy/BirthdayResource_en_US.properties
happy/BirthdayResource_fr_FR.java
Runtime files happy/BirthdayResource.class
happy/BirthdayResource.properties
happy/BirthdayResource_en_US.class
happy/BirthdayResource_en_US.properties
happy/BirthdayResource_fr_FR.class
happy/BirthdayResource_fr_FR.properties

(Validation is not implemented yet. As well as detecting modified and deleted messages, it should also have a mode which reminds us to add new messages.)

Styles of generated code

ResGen can generate Java code in three styles: static, dynamic and functor.

Static style

In the static style, the generated Java resource class contains a resource member and several methods for each resource. In the example, the TooYoung resource had a data member and three methods:

To change style, add an attribute to your ant target:

<resgen srcdir="source" style="functor" locales="en_US">
    <include name="happy/BirthdayResource_en_US.xml"/>
</resgen>

Dynamic style

In the dynamic style, the same data member and methods are generated, but they are not static. For example,

Because the methods are not static, they have different behavior if they are invoked on different objects. Typically you have an instance of the resource bundle for each locale. These instances are accessed via the instance() and instance(Locale) methods in the resource bundle:

Here's the same code example using dynamic resources:

import happy.BirthdayResource;

public class Birthday {
    static void wishHappyBirthday(String name, int age) {
        if (age < 0) {
            throw BirthdayResource.instance().newTooYoung(name);
        }
        System.out.println(BirthdayResource.instance().getHappyBirthday(name, age));
    }
    public static void main(String[] args) {
        wishHappyBirthday("Fred", 33);
        wishHappyBirthday("Wilma", -3);
    }
}

 

Functor style

In the functor style, only one data member is generated per resource, but the data member belongs to a class which has all of the necessary accessor methods. For example,

The accessor methods have the same purpose as the generated methods in static or dynamic style, but have different names. The str accessor method corresponds to getTooYoung, and ex corresponds newTooYoung.

Let's see how the code example looks when rewritten to use functors.

import happy.BirthdayResource;

public class Birthday {
    static void wishHappyBirthday(String name, int age) {
        if (age < 0) {
            throw BirthdayResource.instance().TooYoung.ex(name);
        }
        System.out.println(BirthdayResource.instance().HappyBirthday.str(name, age));
    }
    public static void main(String[] args) {
        wishHappyBirthday("Fred", 33);
        wishHappyBirthday("Wilma", -3);
    }
}

The code is slightly more verbose, but functors have two advantages. First, functors are genuine objects, so can be passed as callbacks. Suppose that you are designing a library method which is to create, populate, and throw an exception if it encounters an error, but which cannot be dependent upon a particular resource file. You could design the method to receive a functor, and the method could call the functor's ex() method if it has an error.

Second, they make it easy to figure out which pieces of code are using a particular resource, because there is only one access point to that resource. For example, every piece of code which uses the TooYoung resource must do so via the BirthdayResource.TooYoung data member. If no code is using the data member, you can safely obsolete the resource.

C++ Resource Support

ResGen also includes support for building and maintaining internationalized applications in C++.

Resource file format

Element Attributes
<resourceBundle>

The top-level element.

Attributes:

name description
locale The locale of resources in this file. Required.
style If dynamic (the default), generate several accessor methods per resource; if functor, generate one member per resource, with several methods.
exceptionClassName The default class of exception to generate. Must be qualified by package name, unless it is in the package java.lang. Not required; default value is "java.lang.RuntimeException". The className attribute of <exception> overrides this for a specific exception.
cppNamespace The namespace used for generated C++ files. Only used if resources are generated in C++ mode. Optional.
cppCommonInclude The name of a header file to include at the start of all generated C++ files. Optional. Only used if resources are generated in C++ mode.
cppExceptionClassName The name of the exception class to be returned by exception resources. Optional. Only used if resources are generated in C++ mode.
cppExceptionClassLocation The name of the header file to include. Should define the class referred to in cppExceptionClassName. Required if cppExceptionClassName is given.

Children:

  • Zero or more <message> or <exception> elements.
<message>

Defines a localizable message.

Attributes:

name description
name The identifier of the message. Becomes the name of the property in the generated .properties file. Required, must be unique within the resource file, and must be a valid Java identifer.

Children:

  • Zero or more <property> elements, defining properties of the resource. These properties will be accessible at runtime via the ResourceDefinition.getProperties() method.
  • A single <text> element, holding the text of the message.
<exception> Defines an exception and its associated message.

Attributes:

name description
name The identifier of the exception. Becomes the name of the property in the generated .properties file. Required, must be unique within the resource file, and must be a valid Java identifer.
className The type of exception to generate. Must be fully qualified, unless it is in the package java.lang. If not
specified, the resource bundle's default exception class is used.
cppClassName The name of the C++ exception class returned by this exception. Either this attribute or <resourceBundle>'s cppExceptionClassName must be defined.
cppClassLocation The name of a C++ header file to be included. Required if cppClassName is used.
cppChainExceptions If false (the default), only a basic constructor is need. If true the basic and chained constructors are required (see the section on C++ resources.

Children:

  • A single <text> element, holding the text of the message.
<text> The text of the message or exception. Should be in Java message format (see class java.text.MessageFormat for more details).

If the message contains XML special characters such as '<' and '&', you may find it easier to enclose the message in <![CDATA[ ... ]]>.

<property> Property of a resource.

Attributes:

name description
name The name of the property.

Children:

  • The value of the property.

API

For details on the ResGen interfaces, please see the javadoc.

Conclusion

ResGen helps you build and maintain an internationalized application. Code generation helps to leverage the power of the compiler: it detects parameters which are missing or of the wrong type, spelling mistakes, and informational messages which are being used to describe error conditions.

About ResGen

ResGen is an Eigenbase utility package, and was derived from the MonRG utility in the Mondrian project (an open-source OLAP server). Packaged distributions are available from the Eigenbase project home page at SourceForge.net. For more information, email John Sichi.


Home | This file is $Id: //open/util/resgen/doc/index.html#3 $ (log) SourceForge.net Logo