Monday, September 17, 2007

Trinidad versus Tomahawk component architecture

I have been using Tomahawk quite a while and building several custom components with it. Relatively recently, I have incorporated Trinidad in a new project I am working on due to its AJAX support and large number of components.

Yesterday, I attempted to incorporate maven-faces-plugin into my project from the Trinidad code base. After trying it out, I have decided to back it out of my project, partially due to the amount of work, and mostly due to the architecture of Trinidad components.

Why is Tomahawk a better component development platform?

Yes, a bold statement, but I wanted to get your attention. Trinidad has a great offering, a lot of components, AJAX support and a good set of APIs, but there may be a large architectural flaw. This flaw is the architecture of Components and renderers around the FacesBean.

Comparison:

What I found is that Tomahawk follow an OO paradigm, but Trinidad breaks OOD standards. One of the major aspects of effective OOD is encapsulation. This basically means that the functionality an Object provides comes from the component itself. Tomahawk has a special map behind the getAttributes() method of each component. This map delegates the attributes to the property getter and setter methods of the component. Take for example:

// MyComponent comp; String value = comp.getMyProperty(); value = comp.getAttributes().get("myProperty");

These two lines of code are identical in terms of functionality, they both call "getMyProperty()" on MyComponent. This means that component developers know that the getter and setter methods of their component will be called, and they have the control to provide any functionality that is needed besides just storing and retrieving a value (they can manipulate values, check for illegal arguments, etc.). This illustrates a good comprehension of encapsulation, that the functions of MyComponent provide the functionality of MyComponent.

Trinidad works in a completely different way. Each UIXComponent has a FacesBean instance that is tied to a static Type that dictates what values are stored during state processing of the component. The getter and setter methods of the components retrieve and store values into this FacesBean. The break in encapsulation is that this FacesBean is made public. That means that people can access the FacesBean and get values without a reference to the component. Encapsulation is lost, the component no longer has any control over the functionality for its own properties. To make matters worse, all of the Trinidad JSP Tag classes and the Trinidad renders use this FacesBean directly, taking the component completely out of the picture.

Code generation

There were other issues that I had with the maven-faces-plugin. The biggest, is that this plugin drastically affects your project layout and architecture. Unlike the Tomahawk code generator which injects code into a component's source, Trinidad actually generates the entire component. This means that the Trinidad components have to be their own maven project. Furthermore, there is a two step process which requires a third project (i.e. trinidad-build, trinidad-api and trinidad-impl). After refactoring most of my code into this layout, the plugin still didn't work. It wasn't generating the taglib.xml files. Unfortunately the plugin is not documented

Conclusion

My conclusion from my research is to not use maven-faces-plugin for my project. For my custom components that extend Trinidad components, I am forced to use the FacesBean architecture or else risk breaking the Trinidad renderers, or at least not being compliant with the design.

To the Trinidad team:

Adam and the Trinidad team, what do you feel about inversing the FacesBean? What I mean by this, is that currently the get/set component methods store the values into the FacesBean. What about taking the design of the Tomahawk components and having the FacesBean call the get/set methods on the component to get their values and have the get/set methods of the component actually do the work? Since the code is generated, the cascade of the change shouldn't be too bad. Only people that have extended these components without using maven-faces-plugin would be affected.

Since this would break backwards-compatibility, Trinidad's major version could be bumped.


Updates and responses to comments

2007-09-17

Simon,

Yes, I know that the performance will be better and the generated code smaller, but is that a good reason for breaking standard OOD? With this model, the component's properties are reduced to the security and functionality of public fields.

I am a very strong believer in usage of OOD for Java objects and the current design forgoes the UIComponent design by having the renderers bypass the component and the component attributes by delegating component properties to the FacesBean.

Is the efficiency of FacesBean worth the cost of bypassing encapsulation and reducing a component's methods to not much more than a Map?

JDK 1.5 has made reflection much faster, and if the Method references were cached, it would be a much smaller performance hit. Take EJB3 for example, it uses reflection plus annotations to get and set values for database access. Even though there is a performance hit, the API remains viable for production use.

Instead of using FacesBean, renderers could use the attribute map instead, this would ensure that renderers remain component agnostic. For example:

public void encodeBegin(FacesContext facesContext, UIComponent comp) { Map attrs = comp.getAttributes(); Renderer delegate = getMyRendererDelegate(); delegate.renderStuff(facesContext, attrs); }

Or

public void encodeBegin(FacesContext facesContext, UIComponent comp) { Map attrs = comp.getAttributes(); String styleClass = toString(attrs.get("styleClass")); } protected String toString(Object obj) { return obj == null ? null : obj.toString(); }

In these crude examples, the renderer doesn't care what the component is, only that the component may (or may not) provide a specific attributes. In the first example, the delegation renderer can access the attributes to get a styleClass for example. The second example shows a class accessing a property via the attributes

With this paradigm, a renderer developer may choose to access the component directly (cast the component to one it supports) or use the attributes. If it uses the attributes, it choose to be able to support behaviors rather than types. In this way, renderers that are used as delegates could simply rely on the attribute map.

In terms of performance, the attribute may could cache, in a transient variable, the Method to call for the get and/or set property accessors. The component could choose to use FacesBean, or just store the value in a member variable. I know there is some performance overhead, but this is a side effect of a good encapsulation with the flexibility that you desire from the loose-binding a.k.a. late binding you desire for renderers.

2007-09-17

Adam,

The reason FacesBean violates OOD is that it delegates the behavior of the UIComponent to the FacesBean. The UIComponent no longer has any control over its own properties and is no longer aware of external accesses to its own data. Also, the way that an object chooses to serialize its data (saveState, restoreState behaviors in JSF), is an internal, not external function.

With the FacesBean being a public object, a piece of code can easily change the value of a property to something illegal, and the component has no opportunity to validate the new value.

Lastly, the component has no control over removing attributes. With proper use of encapsulation, a component could remove an attribute, maintaining the get/set properties as deprecated but store the value elsewhere. With the FacesBean, the component now is permanently bound to the data that it serializes, as people now code against the PropertyKey names instead of the exposed properties. The way that the FacesBean architecture is made, the private fields of UIXComponent have been made public.

2007-09-17

Simon,

Good point on the sub-classing FacesBean, perhaps I should give that option more thought. If I have the incentive and time, I may decide to create a new blog entry on customizing the FacesBean to create validation methods, the ability to create access methods (handle set/get) as a proof of concept.

Saturday, November 18, 2006

Is JSF made for AJAX or does it just "play along"?

Before I begin, this post is meant as a discussion point, not a flame war. I decided to publish this as a blog instead of an email on one of the JSF mailing lists so that I could get comments and feedback from others.

I have been using JSF for almost two years now, one year as my full time job. It is by far, better than any other server side framework that I have used (C CGI, Perl CGI, PHP, ASP, ASP.NET, JSP and servlets)

Background

With this in mind, it doesn't mean there aren't issue in the JSF space. One of which is it's compatibility with AJAX. Several competitors are available to use AJAX with JSF:

  • AjaxAnywhere
  • Ajax4Jsf
  • G4Jsf
  • Trinidad
  • jsf-extensions/Avatar
  • ICEFaces
  • JBoss-Seam (in the works)
  • etc.

Each of them handle AJAX in their own way unfortunately for the learning user. The one large problem with them, is that they are all on top of JSF. Before you post your comment, here me out. JSF is a "hack" to bring a new technology on top of JSP. It was developed when Sun and Java developers realized that JSP was not succeeding and had fundemental flaws in the design that made ASP.NET, RoR and other languages more appealing. Many went the way of Struts with Java to gain so of that functionality. The problem with struts is that it never provided a good component framework.

The reason that JSF is a "hack" is that it is built from JSP pages. Although nice to those wishing to convert their projects from plain JSP to JSF with a JSP view handler, the combination is useless for large business applications. "The reason for this?" you ask, well it is the component tree. The single worst design of JSF is the saved component state of the UIViewRoot object. The component tree is made to be built once and then saved on the client or in the user's HttpSession object. This is more than just a serialized set of objects. It has methods for saving state and restoring state that custom components may override. Every time a view is restored, then entire component tree must be recursed and each of these methods are invoked. All the EL expressions (a.k.a. value bindings), component properties, attributes, etc. are all serialized into this component state. The overhead is gigantic.

To illustrate this point, let me bring up my companies application. It is just that an application, having dockabe frames, complex dialog box, complex layouts, etc. It actually makes Gmail and Google calendar look simplistic. Now I am not trying to pat myself or my company on the back, but let you know of the complexity of each view. There are hundreds if not thousands of components in this component tree. Each time I POST back to the view, the time it takes to restore this component tree is getting slower and slower as we add more functionality.

Luckily we use Facelets for our view handler not JSP (which I would never recommend as a long term solution). JSP should be though of only as a stepping stone until you convert your legacy application from JSP to JSF. Once you are completely in JSF, use facelets. It is the only way to achieve adequate performance for anything besides a Hello World application.

Enter AJAX

We are using AjaxAnywhere right now. It is very stable in 1.1.0.6 and does the job nicely. If I were to do it all again, I would probably use Ajax4Jsf due to its tight integration with JSF and the fact that it is the closest in design to Avatar (the future of AJAX in JSF from Sun).

The problem

For each AJAX request, the "JSF integrated" technologies must post back to JSF. They then execute the standard JSF lifecycle. This includes the restoring of the component tree. Yes, this is the single worst part of JSF for AJAX. If I simply want to update 2 components on the page, I have to restore the entire tree, counting possibly into the 1000s of components. Sound like a bottleneck? It is!

I can witness this problem when I use JBoss-Seam remoting. Remoting is independent of JSF and therefore does not restore the component tree or the view. I have extended it in my use to integrate with the FacesContext so that I can access & update my backing beans as well. The performance? -- instant. That is right, it doesn't even appear to go back to the server it is so fast. The difference between this and the page POST of AjaxAnywhere back to JSF is huge. Unfortunately, using Java methods on the server to generate HTML feels like the days of pre-JSP servlet development, so while it is good for sending & getting data, it is not a good fit for generating HTML (unless you love JavaScript and you build the entire page via document.createElement() calls -- see my discussion on GWT below).

What can be done? Well many of these technologies "hack and slash" their way into the JSF APIs to try to speed performance. They skip phases such as validation, updating of the model, etc. for components that do not need to change, but the component tree is still always restored. The one solution is that the component tree must go! That is right, in order for JSF to have adequate performance the JSF specifications must be completely changed to mostly remove the component tree. If I want to update 2 components using AJAX, only those two components should be reloaded from the view, no more. This is problematic as the API is not built for this.

Jacob Hookom has had some really good insights on this issue:

Is the grass greener?

I was looking at GWT the other day as it came up when I was looking for some good JavaScript libraries for layouts. In doing so, I started to read more and more, liking it quite a bit. Wondering if this is better for business applications than JSF, I found G4Jsf, an attempt at integration of JSF and GWT. The problem is that I could not find any documentation and the demo is extremely simplistic (no forms, no validation or updating of the JSF model, no JSF navigation, and almost no Views, just GWT code). I will be quite anxious to see where this project goes.

From what I understand in my initial look, GWT is interesting in that it stores the component state in the DOM of the browser using HTML + JavaScript. This means that when calls are made to the server, there is no component tree to update, no view to restore. The client is almost a thick client (and almost getting the performance of one). It's "magic" is to convert Java code into JavaScript, hiding the complexity of writing JavaScript DOM manipulation code by hand.

On the other hand GWT doesn't look like a good tool to create web pages though. There is no HTML for developers, only Java code. WYSIWYG is next to impossible from what I see for complex applications. The ease of using the JSF view and the Facelets templates, just doesn't seem to be there.

What Now?

As I mentioned, the whole point of this blog is simply to start a discussion. I would love to hear what the JSF experts have to say and if they know if future releases beyond 1.2 will start to address these issues (I even wonder if 1.2 will ever take off as ppl. aren't even fully embracing 1.1 yet).

Is there something I missed with these JSF AJAX libraries to get around the component tree performance issue?

Please keep the comments to Java based technologies as they apply to JSF, this is not meant to be language war.

Update: 2007-04-22

Since I created this post, I have had the opportunity to convert my company's software over from AjaxAnywhere to Ajax4Jsf and I wanted to report my findings so far. After some initial issues on converting some very large (and nested) templates over and converting some complex in-house components to A4J, we are now running on A4J with only some minor patching.

Even with a very large component tree, I am seeing ~300-600ms per AJAX request (calculated using FireBug in Firefox). I am using ajaxSingle="true", limitToList="true" and a4j:region tags where possible to enhance performance (it make a significant performance impact). With time permitting, I think I can get performance better by working on our in-house JavaScript code that runs per-AJAX request that is part of the issue.

So even though JSF needs some large improvements to the specification to make AJAX fit better, the performance is definitely dependent on the AJAX tools used. Hopefully we see JSF more stream-lined and less JSP dependent (or hopefully completely separate from JSP) in JSF 2.0 with some improvements to component creation and state saving (letting the view handler take more of the burden on and less on the component develeper).

Tuesday, June 27, 2006

MyFaces Tree2 - Creating a lazy loading tree

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).