Uncategorized

Display all managed-beans in JSF at runtime

Sometimes we like to see whats going on under the hood of jsf application (Checkout my JSFConsole). One such task is being able to display all the registered managed-beans during runtime.
Here we can see all registered beans, including implicit object(cookie,header,param etc…)

Result

     a4j
     a4jSkin
     ajaxContext
     ajaxHandler
     application
     applicationScope
     beeHive       --- My Managed bean
     cookie
     facesContext
     header
     headerValues
     initParam
     param
     paramValues
     request
     requestScope
     richSkin
     session
     sessionScope
     view

Source

/**
	 * Retrieve all registered beans for given {@link ScopeType}
	 * @param scopeType to search in
	 * @return List of beanNames
	 */
	public static List<String> getRegisteredBeans(ScopeType scopeType){
		FacesContext facesContext=FacesContext.getCurrentInstance();
		ApplicationAssociate application = ApplicationAssociate.getInstance(facesContext.getExternalContext());
		BeanManager  beanManager = application.getBeanManager();
		Map<String, BeanBuilder> beanMap=beanManager.getRegisteredBeans();
		Set<Entry<String, BeanBuilder>>beanEntries=beanMap.entrySet();
		List<String> registeredBeans=new ArrayList<String>();
		for(Entry<String, BeanBuilder> bean:beanEntries){
			String beanName=bean.getKey();
			if(!beanManager.isManaged(beanName)){
				continue;
			}			
			BeanBuilder builder=bean.getValue();
			Scope bScope=builder.getScope();
			if(scopeType==ScopeType.ALL || bScope.toString().equals(scopeType.toString())){
				registeredBeans.add(beanName+":"+bScope.toString());
			}
		}
 
		if(scopeType==ScopeType.ALL || scopeType==ScopeType.IMPLICIT){
			List<String> implicitList=getProperties(new ImplicitObjectELResolver(), null);
			for(String implicitBeanName:implicitList){
				registeredBeans.add(implicitBeanName+":"+ScopeType.IMPLICIT.toString());
			}
		}
 
		Collections.sort(registeredBeans);
		return registeredBeans;
	}

ScopeType is nothing more than an emun wrapper

 
/**
 * Scope type with additional properties for all/implicit
 * @author devil
 *
 */
public enum ScopeType {
	//Really not a scope but a marker
	ALL("all"),
	IMPLICIT("implicit"),
 
	REQUEST("request"),
	SESSION("session"),
	APPLICATION("application");
 
	String scope;
	ScopeType(String scope) {
		this.scope = scope;
	}
 
	public String toString() {
		return scope;
	}
 
 
	/**
	 * Get Enum from value
	 * @param name
	 * @return
	 */
	public static ScopeType fromValue(String name) {
		name=name!=null?name.toUpperCase():"";
		for(ScopeType v:values()){
			if(v.name().equals(name)){
				return v;
			}
		}
		//By default return all scoped objects
		return ScopeType.ALL;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *