Return any JSF bean stored in session scope under the specified name. - Java JSF

Java examples for JSF:FacesContext

Description

Return any JSF bean stored in session scope under the specified name.

Demo Code

/**/*from  w w  w .  j  a v  a2  s.  c  o m*/
 * License: src/main/resources/license/escidoc.license
 */
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        Class cls = String.class;
        System.out.println(getSessionBean(cls));
    }
    private static Logger logger = Logger.getLogger(BeanHelper.class);
    /**
     * Return any bean stored in session scope under the specified name.
     * 
     * @param cls The bean class.
     * @return the actual or new bean instance
     */
    public static Object getSessionBean(final Class<?> cls) {
        String name = null;
        name = cls.getSimpleName();
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get(name);
        logger.debug("Getting bean " + name + ": " + result);
        if (result == null) {
            result = addSessionBean(cls, name);
        }
        return result;
    }
    /**
     * Add a class to the session map
     * 
     * @param cls
     * @param name
     * @return
     */
    private static synchronized Object addSessionBean(final Class<?> cls,
            String name) {
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get(name);
        if (result != null)
            return result;
        try {
            logger.debug("Creating new session bean: " + name);
            Object newBean = cls.newInstance();
            FacesContext.getCurrentInstance().getExternalContext()
                    .getSessionMap().put(name, newBean);
            return newBean;
        } catch (Exception e) {
            throw new RuntimeException("Error creating new bean of type "
                    + cls, e);
        }
    }
}

Related Tutorials