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

Java examples for JSF:FacesContext

Description

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

Demo Code

/**/*w w  w . j a v  a 2s.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(getApplicationBean(cls));
    }
    private static Logger logger = Logger.getLogger(BeanHelper.class);
    /**
     * Return any bean stored in application scope under the specified name.
     * 
     * @param cls The bean class.
     * @return the actual or new bean instance
     */
    public static Object getApplicationBean(final Class<?> cls) {
        String name = null;
        name = cls.getSimpleName();
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getApplicationMap().get(name);
        logger.debug("Getting bean " + name + ": " + result);
        if (result == null) {
            result = addApplicationBean(cls, name);
        }
        return result;
    }
    /**
     * Add a class to the application map
     * 
     * @param cls
     * @param name
     * @return
     */
    private static synchronized Object addApplicationBean(
            final Class<?> cls, String name) {
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getApplicationMap().get(name);
        if (result != null)
            return result;
        try {
            logger.debug("Creating new session bean: " + name);
            Object newBean = cls.newInstance();
            FacesContext.getCurrentInstance().getExternalContext()
                    .getApplicationMap().put(name, newBean);
            return newBean;
        } catch (Exception e) {
            throw new RuntimeException("Error creating new bean of type "
                    + cls, e);
        }
    }
}

Related Tutorials