Retrieve the first component in the base JSF Component's structure that is an instance of the passed in class. - Java JSF

Java examples for JSF:UIComponent

Description

Retrieve the first component in the base JSF Component's structure that is an instance of the passed in class.

Demo Code


import javax.faces.component.UIComponent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main{
    /**/*w  ww  .  j a v  a 2  s  .c  o m*/
     * Retrieve the first component in the baseComponent's structure that is
     * an instance of the passed in class.
     *
     * @param baseComponent
     * @param clazz
     * @param <S>
     * @return
     */
    public static <S extends UIComponent> S findFirstComponentOfType(
            UIComponent baseComponent, final Class<S> clazz) {
        final List<S> results = new ArrayList<>();
        recurseChildren(baseComponent, 0, new UIComponentVisitor() {
            @Override
            public boolean visit(UIComponent component, int depth) {

                if (clazz.isInstance(component)) {
                    results.add((S) component);
                    return false;
                }

                return true;
            }
        });

        // Return the first item in the list
        return (results.size() > 0 ? results.get(0) : null);
    }
    /**
     * Recursively traverse the passed in component structure and call the passed in visitor.
     *
     * @param baseComponent
     * @param depth
     * @param visitor
     * @return
     */
    public static boolean recurseChildren(UIComponent baseComponent,
            int depth, UIComponentVisitor visitor) {
        if (visitor.visit(baseComponent, depth) == false) {
            // Abort
            return false;
        }

        if (baseComponent.getFacetsAndChildren() != null) {

            Iterator<UIComponent> childComponentIterator = baseComponent
                    .getFacetsAndChildren();
            while (childComponentIterator.hasNext()) {
                UIComponent childComponent = childComponentIterator.next();
                if (recurseChildren(childComponent, depth + 1, visitor) == false) {
                    // Abort
                    return false;
                }
            }
        }

        // Keep going
        return true;
    }
}

Related Tutorials