Tuesday, June 27, 2006

MyFaces Tree2 - Creating a lazy loading tree

My blog has moved, please update your links. You can find this article here
Note: this code is hosted at http://sourceforge.net/projects/jsf-comp under the AjaxAnywhere download. As a result, this blog post's content may be out of date compared to that source.

Although the MyFaces Tree2 WIKI discusses lazy loading children tree nodes, it does not cover the use case of if you don't know if there are children or not. Recently, I had a use case where I was loading children using a WebService that would return me contents of a node per-call. Obviously for performance reasons, I wanted to keep the number of calls to a minumum.

My approach:
Use AJAX via AjaxAnywhere and server-side toggling with Tree2 to lazy load the tree nodes. When asked for the children of a node that isn't loaded, I would load the nodes then and there.

My use case was wrapped around a content management solution, so it was file/directory based nodes.

What was needed:
  • Custom tree node for "directory nodes"
  • Custom tree nodes for "file nodes" that could be selected
Note: this blog will not discuss AJAX and enabling the tree in server side mode, that would be another discussion entirely

Step 1: create a "lazy loading" tree node that we can extend:

public class BaseTreeNode implements TreeNode { private BaseTreeNode parent; private String identifier; private String name; private String type; protected List<BaseTreeNode> children; protected TreeModel model; public BaseTreeNode() {} public BaseTreeNode(TreeModel model, BaseTreeNode parent, String type, String identifier, String name, boolean leaf) { this.model = model; this.type = type; this.parent = parent; this.identifier = identifier; this.name = name; if (leaf) children = Collections.emptyList(); } /** * @return Returns the parent. */ public BaseTreeNode getParent() { return this.parent; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#isLeaf() */ public boolean isLeaf() { return getChildCount() == 0; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#setLeaf(boolean) */ public void setLeaf(boolean leaf) {} /** * @see org.apache.myfaces.custom.tree2.TreeNode#getChildren() */ public List<BaseTreeNode> getChildren() { if (children == null) children = loadChildren(); return children; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#getType() */ public String getType() { return type; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#setType(java.lang.String) */ public void setType(String type) { this.type = type; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#getDescription() */ public String getDescription() { return name; } /** * @see org.apache.myfaces.custom.tree2.TreeNode#setDescription(java.lang.String) */ public void setDescription(String description) {} /** * @see org.apache.myfaces.custom.tree2.TreeNode#setIdentifier(java.lang.String) */ public void setIdentifier(String identifier) {} /** * @see org.apache.myfaces.custom.tree2.TreeNode#getIdentifier() */ public String getIdentifier() { return identifier; } public int getIndex() { return (parent == null) ? 0 : parent.getChildren().indexOf(this); } /** * @return Returns the name. */ public String getName() { return this.name; } public String getFullPath() { StringBuilder sb = new StringBuilder(name); for (BaseTreeNode node = getParent(); node != null; node = node.getParent()) sb.insert(0, '/').insert(0, node.getName()); return sb.toString(); } public String getNodePath() { StringBuilder sb = new StringBuilder(Integer.toString(getIndex())); for (BaseTreeNode node = getParent(); node != null; node = node.getParent()) sb.insert(0, TreeModel.SEPARATOR).insert(0, node.getIndex()); return sb.toString(); } public boolean isExpanded() { if (model == null) return true; return model.getTreeState() .isNodeExpanded(getNodePath()); } /** * @see org.apache.myfaces.custom.tree2.TreeNode#getChildCount() */ public int getChildCount() { if (children == null && !isExpanded()) return 1; if (children == null) children = loadChildren(); if (children == null) return 0; return children.size(); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return name; } protected List<BaseTreeNode> loadChildren() { return null; } }

This base class takes most of the tedious work away from having to create the lazy loading functionality. In the constructor, a "lazy" parameter is provided for nodes that the user knows will not have children (like a file node in this example). This node also includes code for working with the Tree2 default TreeModel and TreeState by implementing a "getNodePath" function that works with node indexes instead of just node IDs.

Step 2: create the directory node (inner class):

public class FolderNode extends BaseTreeNode { FolderNode(TreeModel model, BaseTreeNode parent, String name) { super(model, parent, "folder", name, name, false); } @Override protected List<BaseTreeNode> loadChildren() { return <Your business code class here>.loadChildren(this); } }

The implementation of the folder is simple. I have not shown my code, but I have this node in my code as an inner class that I have this "loadChildren" method that calls my Web service. In that method, I simply create new nodes an add them to the parent node.

The key here is how the tree2 works and how the renderer works (this is source code specific, so if Tree2 was changed drastically enough, this may break). The tree2 renderer looks only at the getChildCount method, not the getChildren method when rendering. Meaning that if getChildCount should return 0, getChildren will never be called unless the node is expanded. In my base node, you will see that I am returning 1 child as the child count if the children have not been loaded and the node is not expanded. This will cause tree2 to render a plus sign icon next to my node (indicating that there are children).

If the node is expanded, and the children are not loaded, my base node then calls the load children method. This will force the accurate count of nodes to be returned for this node. If I were to only put my loading code in the getChildren, the tree would not render correctly, as getChildCount is always called first in the renderer.

What ends up being the result is that when the plus sign is clicked, the node is exanded in the tree model's tree state. Then the tree is rendered (having the getChildCount method called). I load the children, and return the correct count to the renderer which then proceeds in calling getChildren and building the HTML.

This will work if there are actually no children (the plus sign simply dissappears), or if there are many children (not the "1" that was originally reported as the number of children).

FYI, here is the "file" node code:

public class FileNode extends BaseTreeNode { FileNode(TreeModel model, BaseTreeNode parent, String name) { super(model, parent, "file", name, name, true); } }
The XHTML is as follows:
<aa:zoneJSF id="treeZone"> <my:ajaxTree value="#{contentMgmtBean.treeModel}" ajaxZone="treeZone" var="_node" clientSideToggle="false" varNodeToggler="t" showRootNode="false"> <f:facet name="folder"> <t:panelGroup> <t:graphicImage styleClass="treeNodeIcon" url="#{_node.expanded ? '/images/contentMgmt/openfolder.gif' : '/images/contentMgmt/closedfolder.gif'}" /> <t:outputText styleClass="folderNodeText" value="#{_node.name}" /> </t:panelGroup> </f:facet> <f:facet name="file"> <my:ajaxCommandLink ajaxZone="treeZone,myResultZone" actionListener="#{contentMgmtBean.nodeSelected}" styleClass="fileNodeLink#{ contentMgmtBean.currentFileName eq _node.name ? ' selectedNode' : ''}"> <t:updateActionListener property="#{contentMgmtBean.currentFileName}" value="#{_node.name}" /> <t:graphicImage styleClass="treeNodeIcon" url="/images/contentMgmt/file.gif" /> <t:outputText styleClass="fileNodeText" value="#{_node.name}" /> </ost:ajaxCommandLink> </f:facet> </my:ajaxTree> </aa:zoneJSF>

Example of using the node as an inner class:

public class BeanClass { private TreeModel treeModel; public List<BaseTreeNode> loadChildren(FolderNode parent) { List<BaseTreeNode> children = new ArrayList(); List<String> folders = ; // load from web service for (String folder : folders) children.add(new FolderNode(treeModel, parent, folder)); List<String> files = ; // load from web service for (String file : files) children.add(new FileNode(treeModel, parent, file)); return children; } public class FolderNode extends BaseTreeNode { ... protected List<BaseTreeNode> loadChildren() { return loadChildren(this); } } }

Update This code has been moved to a jsf-comp component. Go to http://sf.net/projects/jsf-comp to download. An example war file is included in the release

© Copyright 2006 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license (http://www.gnu.org/licenses/lgpl.html).

Sunday, June 18, 2006

Running actions despite validation errors

My blog has moved, please update your links. You can find this article here

Recently, I was developing a page that had 3 data tables. Each table had an 'add' button and each row in the table had 'delete' buttons. The problem was that I ended up fighting the JSF specification trying to accomplish this simple task.

The functionality that I wanted for my users was to add or remove rows from these tables regardless of if the data on the rest of the page was valid.

Table of contents:
  1. Immediate
  2. Action validation
  3. Tomahawk sandbox subForm
  4. Optional validator framework
  5. New component (solution)

First I tried the immediate attribute on my command links. Although this technically worked, I lost all my data in the data table input components. Due to the way the UIData component works, the submitted values will not be correctly processed unless the validation phase is run.

After that, I looked into using only action validation (no validators or required flags). Once again I didn't get the functionality that I desired. It was not possible, while maintaining a clean Object-Oriented design to be able to correctly assign component IDs to the validation messages for the components in the tables (I would have to hard-code the indexes into the messages as well as the view IDs - not an elegant solution).

The third attempt led me to the subForm Tomahawk component from MyFaces. First problem was that the all the components in the form had to be within a subForm. Then I had to create a dummy sub-form that I would submit:

<f:form> <s:subForm id="mainForm"> <-- Other input componenets here --> <t:commandLink action="#{userBean.addEmail}" actionFor="dummyForm" /> </subForm> <s:subForm id="dummyForm" />

Once again this worked only half-way. My action was run, but like with the immediate attribute, the values were lost in the data tables.

Forth attempt was a look at the Optional validator framework from http://jsf-comp.sf.net. This would have worked but it didn't have the functionality I needed. For one, only validators with IDs were supported (no attributes could be passed, so I would not be able to use validators like validate length which takes a maximum and minimum value. It is also not able to handle required validators on child components of data tables.

Seeing as how my problem again and again was the phase in which my action was executed, I need a different solution in terms of JSF phase. If immediate was set to true, the action would run but the validation phase would be skipped. The validation phase is needed for the submitted values of data tables though. Having the action fire during model update meant that the validation phase had to be skipped or there had to be a way to skip validation errors.

My fifth and final attempt ended up being my solution. It is perhaps not too pretty, but it got the job done. I needed to get the action event to fire during the process validators phase (in between when immediate fires it and non-immediate). I couldn't just extend command link though because UICommand always sets the phase ID of action events during queueEvent. I could have made a special action event that just disabled the setPhaseId funciton (by doing nothing in the method body), but I thought that more of a hack than my final solution.

My solution was to create a component thats sole purpose in life would be to alter the phase ID of an action event. It would need no renderer either. In the queueEvent I would simple set any ActionEvent's phase IDs to process validation. Then, placing this new component as the parent of an action component (or components), I would make sure my action would run during validation.

Using facelets, I needed no tag, so I just wrote the component and gave it an active attribute in case I ever want to disable the behavior using EL:

import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import javax.faces.event.ActionEvent; import javax.faces.event.FacesEvent; import javax.faces.event.PhaseId; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author Andrew Robinson (andrew) */ public class UIValidationActionPhase extends UIComponentBase { private static final Log log = LogFactory.getLog( UIValidationActionPhase.class); public static final String COMPONENT_FAMILY = "-- set family here --"; public static final String COMPONENT_TYPE = "-- set component type here --"; private Boolean active; /** * @return Returns the active. */ public boolean isActive() { if (active != null) return this.active; ValueBinding vb = getValueBinding("active"); return (vb == null) || (Boolean)vb.getValue(getFacesContext()); } /** * @param active The active to set. */ public void setActive(boolean active) { this.active = active; } /** * @see javax.faces.component.UIComponent#getFamily() */ @Override public String getFamily() { return COMPONENT_FAMILY; } /** * @see javax.faces.component.UIComponentBase#getRendererType() */ @Override public String getRendererType() { return null; } /** * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent) */ @Override public void queueEvent(FacesEvent event) { if (event instanceof ActionEvent && isActive()) { log.debug("Changing Phase ID of action event " + event); event.setPhaseId(PhaseId.PROCESS_VALIDATIONS); } super.queueEvent(event); } /** * @see javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext) */ @Override public Object saveState(FacesContext context) { return new Object[] { super.saveState(context), active, }; } /** * @see javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext, java.lang.Object) */ @Override public void restoreState(FacesContext context, Object state) { Object[] array = (Object[])state; int index = -1; super.restoreState(context, array[++index]); active = (Boolean)array[++index]; } }
The usage in my XHTML file was simple:
<f:form> <my:validationAction> <t:commandLink action="#{userBean.addEmail}" /> </my:validationAction> </f:form>

Now the user is able to see validation errors and get feedback on bad input data and my action was still able to run with the validation errors. Luckily my actions (add and delete) did not depend on the model being updated. This solution will not work for those that would need data from the user to be applied to the model.

© Copyright 2006 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license
(http://www.gnu.org/licenses/lgpl.html).
Updates/Change log
Date Description
2007.03.07 Fixed some of the code in the component that was a result of pasting the code into the blog incorrectly.
2007.04.22 Reformatting of HTML in blog.