Wednesday, April 28, 2010

ADF/JSF way of finding all UIComponents in a DOM Recusrively

CAUTION:This is expensive and must be done only when the UIComponents are static, i.e rendered property is not EL expressed.

public static HashMap<String, UIComponent> viewCompMap =  new HashMap<String, UIComponent>();


public static HashMap<String, UIComponent> populateViewComponentsMap(HashMap<String, UIComponent> compMap) {
FacesContext fc = FacesContext.getCurrentInstance();
//Gets the ui view root component.
UIComponent uiComp = (UIComponent)fc.getViewRoot();
//Puts the ui view root component into static map.
compMap.put(uiComp.getId(), uiComp);
//Calls the recursive method which walks down the view tree and populates them in the static map.
populateChildrenInMap(uiComp, compMap);
return compMap;
}

public static void populateChildrenInMap(UIComponent uiComp,
HashMap<String, UIComponent> compMap) {
//Checks if the compMap is not null.
if (uiComp != null) {
//Gets all the children of the ui component as an iterator.
Iterator<UIComponent> uiCompChildren =
uiComp.getFacetsAndChildren();
if (uiCompChildren != null) {
//Iterates through the children.
while (uiCompChildren.hasNext()) {
UIComponent child = uiCompChildren.next();
if (child != null) {
//puts the child component in the map.
compMap.put(child.getId(), child);
}
//Calls the recursive method for each of the child component.
populateChildrenInMap(child, compMap);

}
}

}
}

No comments: