Search code examples
javajsfbundle

Override order of resource bundles


How can I override the order that Java takes when searching for a label in the resource bundles? Taken from the docs, the default order is this:

ButtonLabel_fr_CA_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

However I want to override this order by having variants taken first, like this:

ButtonLabel_fr_CA_UNIX
ButtonLabel_en_US_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

I defined a new class extending ResourceBundle class where you can set the parent bundle but I don't know when this class is being instantiated and what happens when I change the language in the FacesContext. Is it possible to override the order somehow?


Solution

  • I needed to extend class ResourceBundle.Control and override method getCandidateLocales where you can specify the order of used locales.

    Instance of this class is then passed to the getBundle method - I called this in the constructor of the class that extends ResourceBundle like this:

    final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
    final CustomControl control = new CustomControl();
    setParent(getBundle("MyBundle", locale, control));
    

    This class can be used as <resource-bundle> in faces-config.xml or loaded with <f:loadBundle ...>

    <resource-bundle>
        <base-name>com.package.MyBundle</base-name>
        <var>bundle</var>
    </resource-bundle>