XPages Localization Setter

package ch.hasselba.xpages.jsf.core;

import javax.faces.context.FacesContext;
import javax.faces.application.Application;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.component.UIViewRoot;
import java.util.Locale;
import java.util.Map;

public class LocalizationSetter implements PhaseListener {

    private static final long serialVersionUID = -1L;
    private static final String scopeVarName = "Language";
    private static final String scopeName = "sessionScope"; 

    public void afterPhase(PhaseEvent event) {}

    public void beforePhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();
        UIViewRoot view = facesContext.getViewRoot();
        view.setLocale( getLanguage(facesContext) ) ;
    }

    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

    private Locale getLanguage( FacesContext facesContext ){
        try{
            Application app = facesContext.getApplication();
            Object obj = app.getVariableResolver().resolveVariable(facesContext, scopeName );
            Object lang = ((Map) obj).get( scopeVarName );
            if( lang != null ){
                return new Locale((String) lang);
            }
        }catch(Exception e){}

        return Locale.getDefault();
    }
}





XPages Localization Setter allows to switch language in a XPage on the fly, including ressource bundles, dojo config etc.

You can f.e. add a simple combox box to your XPage to allow users to switch the language:

<xp:comboBox id="comboBox1" value="#{sessionScope.Language}">
   <xp:selectItem itemLabel="Chinese" itemValue="zh"></xp:selectItem>
   <xp:selectItem itemLabel="German" itemValue="de"></xp:selectItem>
   <xp:selectItem itemLabel="Turkish" itemValue="tr"></xp:selectItem>
   <xp:eventHandler event="onchange" submit="true" refreshMode="complete" />
</xp:comboBox>

The itemValue is the language code the XPage can be switched to, and can be easily modified to fullify your requirements. The locale to use is stored in a sessionScope variable named "Language".

To activate the XSnippet you have to modify the faces-config.xml of your XPages application by adding these lines:

<faces-config>
  <lifecycle>
     <phase-listener>ch.hasselba.xpages.jsf.core.LocalizationSetter</phase-listener>
  </lifecycle>
</faces-config>

More details can be found here:
http://stackoverflow.com/questions/9715393/how-to-set-resource-bundle-on-the-fly

Java
Sven Hasselbach
April 17, 2012 8:03 AM
Rating
221

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...