2

Possible Duplicate:
Design question regarding Java EE entity with multiple language support

I'm working on i18n of JSF application. I need all standard jsf messages that are usually located in messages.properties to be taken from database. Is there some simple way to do it?

Thanks.

Community
  • 1
  • 1
Benjamin Harel
  • 2,906
  • 3
  • 24
  • 32

2 Answers2

2

I think I found the answer:

public class DBMessagesBundle extends ResourceBundle {
    @Override
    protected String handleGetObject(String key){
        ...
    }

    @Override
    public Enumeration<String> getKeys() {
        ...
    }
}

and in FacesConfig.xml

    <application>
...
        <message-bundle>mypackage.DBMessagesBundle</message-bundle>
    </application>

Thank You for help.

Benjamin Harel
  • 2,906
  • 3
  • 24
  • 32
0

First, you will need your own MessageSource. Take a look at AbstractMessageSource and extend it:

public class CustomResourceBundleMessageSource extends AbstractMessageSource {

    @Autowired
    LocalizationStore localizationStore;

    @Override
    protected MessageFormat resolveCode(String code, Locale locale){
        MessageFormat messageFormat = null;
        ResourceBundle bundle = localizationStore.getBundle(locale);
        try {
            messageFormat = getMessageFormat(bundle, code, locale);
        } catch (MissingResourceException | NullPointerException ex) {
            //Return just the code in case this is used for logging, or throw, your choice
            return createMessageFormat(code, locale);
        }
        return messageFormat;
    }

    protected MessageFormat getMessageFormat(ResourceBundle bundle, String code, Locale locale) throws MissingResourceException {
        String msg = bundle.getString(code);
        return createMessageFormat(msg, locale);
    }
}

Your store must return a ResourceBundle:

This will largely be based off your db model. I would recommend using @Cachable on the getBundle() method, as your localizations are not likely to change often, and depending on your DB model, it may be expensive. The object returned needs only to implement the following methods for ResourceBundle:

public class DBResourceBundle extends ResourceBundle {
    @Override
    protected String handleGetObject(String key){
        ...
    }

    @Override
    public Enumeration<String> getKeys() {
        ...
    }
}

Finally, you need to register your MessageSource bean in your configuration:

<bean id="messageSource" class="com.example.CustomResourceBundleMessageSource"/>
aweigold
  • 6,532
  • 2
  • 32
  • 46