Monday, February 8, 2016

Recursive tree in JSF and Faces

A tree structure, such as a menu, a discussion or a list of comments, needs recursion: each node renders its children, which render their children, and so on. This article shows why a recursive composite component of Jakarta Faces (formerly known as JSF) is a bad idea, and what works instead. It targets Faces 4.0 and newer. The differences for older versions are at the bottom. All examples were tested on Mojarra 4.1.21 (WildFly 42) and MyFaces 4.1.4 (Tomcat 11).

The examples use the TreeModel of OmniFaces as the model, but any class with a list of children of its own type works the same:

@Named
@RequestScoped
public class Bean {

    private final TreeModel<String> tree = new ListTreeModel<>();

    @PostConstruct
    public void init() {
        TreeModel<String> one = tree.addChild("one");
        one.addChild("one.one");
        one.addChild("one.two");
        TreeModel<String> two = tree.addChild("two");
        two.addChild("two.one").addChild("two.one.one");
    }

    public TreeModel<String> getTree() {
        return tree;
    }
}

A recursive composite component

The obvious attempt is a composite component which nests itself for the children of each node, as in <my:tree node="#{bean.tree}">. It uses <c:forEach> and <c:if>, not <ui:repeat>, because the recursion must stop while the view is built. <ui:repeat> runs only while the view is rendered, so the view would be built endlessly:

<cc:interface>
    <cc:attribute name="node" type="org.omnifaces.model.tree.TreeModel" />
</cc:interface>
<cc:implementation>
    <c:if test="#{not empty cc.attrs.node.children}">
        <ul>
            <c:forEach items="#{cc.attrs.node.children}" var="node">
                <li>
                    #{node.data}
                    <my:tree node="#{node}" />
                </li>
            </c:forEach>
        </ul>
    </c:if>
</cc:implementation>

On Mojarra, this fails with a stack overflow. The repeating part is, without the module prefixes of WildFly:

java.lang.StackOverflowError
    ...
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:364)
    at org.glassfish.expressly.parser.AstValue.getValue(AstValue.java:302)
    at org.glassfish.expressly.parser.AstValue.getValue(AstValue.java:144)
    at org.glassfish.expressly.ValueExpressionImpl.getValue(ValueExpressionImpl.java:138)
    at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.ContextualCompositeValueExpression.getValue(ContextualCompositeValueExpression.java:111)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:73)
    at com.sun.faces.facelets.tag.jstl.core.IterationBaseCache.getValue(IterationBaseCache.java:70)
    at com.sun.faces.facelets.tag.jstl.core.IndexedValueExpression.getValue(IndexedValueExpression.java:51)
    at org.glassfish.expressly.parser.AstIdentifier.getValue(AstIdentifier.java:92)
    at org.glassfish.expressly.ValueExpressionImpl.getValue(ValueExpressionImpl.java:138)
    at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:73)
    at jakarta.faces.component.UIComponentBase$AttributesMap.get(UIComponentBase.java:2438)
    at com.sun.faces.el.CompositeComponentAttributesELResolver$ExpressionEvalMap.get(CompositeComponentAttributesELResolver.java:313)
    at jakarta.el.MapELResolver.getValue(MapELResolver.java:150)
    at com.sun.faces.el.DemuxCompositeELResolver._getPropertyValue(DemuxCompositeELResolver.java:420)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:364)
    ... [repeat]

When you pass #{node} to the nested composite, you're technically passing #{cc.attrs.node.children[index]} to it. The nested composite then evaluates its #{cc.attrs.node} as exactly that. But in the context of the nested composite, #{cc} refers to the nested composite itself, not to its parent. So #{cc.attrs.node} refers to its own node, which refers to its own node, and so on. This never ends.

Referring to the parent via #{cc.parent}, which is just UIComponent#getParent(), looks like the fix:

<cc:interface>
    <cc:attribute name="node" type="org.omnifaces.model.tree.TreeModel" />
</cc:interface>
<cc:implementation>
    <c:if test="#{not empty cc.attrs.node.children}">
        <ul>
            <c:forEach items="#{cc.attrs.node.children}" var="node" varStatus="loop">
                <li>
                    #{node.data}
                    <my:tree node="#{cc.parent.attrs.node.children[loop.index]}" />
                </li>
            </c:forEach>
        </ul>
    </c:if>
</cc:implementation>

Mojarra still fails with a stack overflow. The attributes of a composite component are stored as deferred value expressions, not as values. The parent gives back #{cc.attrs.node} as a ValueExpression, and the child evaluates it in its own context, where #{cc} is again the child itself.

So the attribute must be evaluated right away, and stored in the component as a value. A backing component can do that by overriding setValueExpression():

@FacesComponent("treeComposite")
public class TreeComposite extends UINamingContainer {

    private TreeModel<?> node;

    @Override
    public void setValueExpression(String name, ValueExpression expression) {
        if ("node".equals(name)) {
            setNode((TreeModel<?>) expression.getValue(getFacesContext().getELContext()));
        }
        else {
            super.setValueExpression(name, expression);
        }
    }

    public TreeModel<?> getNode() {
        return node;
    }

    public void setNode(TreeModel<?> node) {
        this.node = node;
    }
}
<cc:interface componentType="treeComposite">
    <cc:attribute name="node" type="org.omnifaces.model.tree.TreeModel" />
</cc:interface>
<cc:implementation>
    <c:if test="#{not empty cc.node.children}">
        <ul>
            <c:forEach items="#{cc.node.children}" var="node" varStatus="loop">
                <li>
                    #{node.data}
                    <my:tree node="#{cc.parent.node.children[loop.index]}" />
                </li>
            </c:forEach>
        </ul>
    </c:if>
</cc:implementation>

This finally works on Mojarra. But not on MyFaces: there, it renders only the first level of the tree. And the other way around, the first and simplest attempt works on MyFaces, but not on Mojarra. A recursive composite component which works on both implementations doesn't seem to exist.

It isn't needed either. As explained in Composite component with multiple input fields in JSF and Faces, a composite component is relatively expensive, and its best use case is several input components bound to a single model value. A tree is just a reusable piece of markup. That's the job of a tag file.

A recursive tag file

Save this as /WEB-INF/tags/tree.xhtml:

<ui:composition
    xmlns:ui="jakarta.faces.facelets"
    xmlns:c="jakarta.tags.core"
    xmlns:t="example"
>
    <c:if test="#{not empty node.children}">
        <ul>
            <c:forEach items="#{node.children}" var="child">
                <li>
                    #{child.data}
                    <t:tree node="#{child}" />
                </li>
            </c:forEach>
        </ul>
    </c:if>
</ui:composition>

Register it in /WEB-INF/example.taglib.xml:

<facelet-taglib xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-facelettaglibrary_4_0.xsd"
    version="4.0">
    <namespace>example</namespace>
    <tag>
        <tag-name>tree</tag-name>
        <source>tags/tree.xhtml</source>
    </tag>
</facelet-taglib>

And register the taglib in web.xml:

<context-param>
    <param-name>jakarta.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/example.taglib.xml</param-value>
</context-param>

Use it as below:

<html ... xmlns:t="example">
...
<t:tree node="#{bean.tree}" />

The generated HTML is, on both Mojarra and MyFaces:

<ul>
    <li>
        one
        <ul>
            <li>one.one</li>
            <li>one.two</li>
        </ul>
    </li>
    <li>
        two
        <ul>
            <li>
                two.one
                <ul>
                    <li>two.one.one</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

A tag file has no #{cc} of its own: its attributes are just EL variables in the scope of the tag file. So #{child} is passed as node to the nested tag file, and there's nothing which can refer to itself. The same works with a plain include file and <ui:param>, saved as /WEB-INF/includes/tree.xhtml:

<ui:composition
    xmlns:ui="jakarta.faces.facelets"
    xmlns:c="jakarta.tags.core"
>
    <c:if test="#{not empty node.children}">
        <ul>
            <c:forEach items="#{node.children}" var="child">
                <li>
                    #{child.data}
                    <ui:include src="/WEB-INF/includes/tree.xhtml">
                        <ui:param name="node" value="#{child}" />
                    </ui:include>
                </li>
            </c:forEach>
        </ul>
    </c:if>
</ui:composition>
<ui:include src="/WEB-INF/includes/tree.xhtml">
    <ui:param name="node" value="#{bean.tree}" />
</ui:include>

This generates the same HTML. Prefer the tag file: the usage is shorter, and once you need more than one or two parameters, a tag file is clearer anyway.

OmniFaces o:tree

When you need more control, such as different markup per level, or components with an ID inside the nodes, use the <o:tree> of OmniFaces. It's a single component which renders the TreeModel by itself, without any recursion in the view:

<o:tree value="#{bean.tree}" var="data">
    <o:treeNode>
        <ul>
            <o:treeNodeItem>
                <li>
                    #{data}
                    <o:treeInsertChildren />
                </li>
            </o:treeNodeItem>
        </ul>
    </o:treeNode>
</o:tree>

This generates the same HTML as well. <o:treeNode> defines the markup around the children of a node, <o:treeNodeItem> the markup of each child, and <o:treeInsertChildren> the place where the children of the child go. With the level attribute of <o:treeNode>, each level can get its own markup.

JSF 2.x

On JSF 2.x, the namespaces start with http://xmlns.jcp.org/jsf/ on JSF 2.2 and 2.3, and with http://java.sun.com/jsf/ on JSF 2.0 and 2.1. The JSTL namespace is http://xmlns.jcp.org/jsp/jstl/core or http://java.sun.com/jsp/jstl/core, and the taglib uses the http://xmlns.jcp.org/xml/ns/javaee schema with version 2.2, or the http://java.sun.com/xml/ns/javaee schema with version 2.0. The context parameter is javax.faces.FACELETS_LIBRARIES. Recursive tag files and include files work since JSF 2.0, and <o:tree> exists since OmniFaces 1.0.