Simple Java based JSF 2.2 custom component

11 May 2013

In JSF components play a central role, it being a component based framework after all.

As mentioned in a previous blog posting, creating custom components was a lot of effort in JSF 1.x, but became significantly easier in JSF 2.0.

Nevertheless, there were a few tedious things left that needed to be done if the component was needed to be used on a Facelet (which is the overwhelmingly common case); having a -taglib.xml file where a tag for the component is declared, and when the component’s Java code resides directly in a web project (as opposed to a jar) an entry in web.xml to point to the -taglib.xml file.

In JSF 2.2 these two tedious things are not needed anymore as the Facelets component tag can be declared using the existing @FacesComponent annotation.

As an update to the original blog posting, a simple Java based custom component can be created as follows:

components/CustomComponent.java

@FacesComponent(value = "components.CustomComponent", createTag = true)
public class CustomComponent extends UIComponentBase {
 
    @Override
    public String getFamily() {        
        return "my.custom.component";
    }
 
    @Override
    public void encodeBegin(FacesContext context) throws IOException {
 
        String value = (String) getAttributes().get("value");
 
        if (value != null) {        
            ResponseWriter writer = context.getResponseWriter();
            writer.write(value.toUpperCase());
        }
    }
}

This is all there is to it. The above fully defines a Java based JSF custom component. There is not a single extra registration and not a single XML file needed to use this on a Facelet, e.g.

page.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:test="http://xmlns.jcp.org/jsf/component"
>
    <h:body>
        <test:customComponent value="test"/>        
    </h:body>
</html>

Just these two files (and only these two files) fully constitute a Java EE/JSF application. The .java file does need to be compiled to a .class of course, but then just these two can be deployed to a Java EE 7 server. There’s not a single extra (XML) file, manifest, lib, or whatever else needed as shown in the image below:

custom_component_deploy

Using GlassFish 4.0 b88, requesting http://localhost:8080/customcomponent/page.jsf will simply result in a page displaying:

TEST

So can this be made any simpler? Well, maybe there’s still some room for improvement. What about the getFamily method that still needs to be implemented? It would be great if that too could be defaulted to something. Likewise, the component name could be defaulted to something as well, and while we’re at it, let’s give createTag a default value of true in case the component name is defaulted (only in that case such as not to cause backwards compatibility issues).

Another improvement would be if component attributes could be declared JPA-style via annotations. That way tools can learn about their existence and the code could become a tiny but simpler. E.g.

@FacesComponent
public class CustomComponent extends UIComponentBase {
 
    @Attribute
    String value;
 
    @Override
    public void encodeBegin(FacesContext context) throws IOException { 
        if (value != null) {        
            ResponseWriter writer = context.getResponseWriter();
            writer.write(value.toUpperCase());
        }
    }
}

The above version is not reality yet, but the version at the beginning of this article is and that one is really pretty simple already.


Arjan Tijms

Eclipse 4.2 SR2 released!

2 March 2013

Today the Eclipse organization released the second maintenance release of Eclipse 4.2; Eclipse 4.2.2 aka Eclipse Juno SR2.

This time around the event is actually noted on the main homepage at eclipse.org, where it briefly says:

The packages for the Juno SR2 release are now available for download.

Lists of bugs that were resolved can be found when clicking on the details link for a specific Eclipse variant on the above mentioned download page.

I didn’t see a complete list anywhere, but some fiddling with Bugzilla again revealed a list of 162 bugs that are fixed in core packages.

For the second time in a row the WTP project also posted about this event on their homepage. Following the Eclipse 4.2.2 release train, WTP was upgraded from 3.4.1 to 3.4.2. There’s again no release specific “new and noteworthy”, but there are release notes, which point to a matrix that shows no less than 77 bugs were fixed.

Community reporting about 4.2 SR2 is a little underwhelming again. DZone has a highly voted Eclipse 4.2 sr2 news blurb, and there’s the lone tweet on twitter, but that seems to be about it.

Of course the highlight of this release is the much awaited answer to the abysmal performance that has plagued the 4.2 series since it was released last year. A separate patch has been available for some time, but this has now been integrated into the ready-to-download official release.

Reports about the patch have been largely positive, so it’s to be expected that Eclipse 4.2 SR2 will indeed perform better. Further performance improvements are promised for Eclipse 4.3 (Kepler).

Eclipse 4.2 SR1 silently released!

30 September 2012

Rather silently, the Eclipse organization 2 days ago released the first maintenance release of Eclipse 4.2; Eclipse 4.2.1 aka Eclipse Juno SR1.

Surprisingly, this event isn’t noted on the main homepage at eclipse.org or at the recent activity tracker. There also don’t seem to be any release notes, like the ones we had for the 4.2 release.

Fiddling with Bugzilla gave me a list of 80 bugs that are fixed in core packages.

This time around, the WTP project did feel obliged to post about this event on their homepage. Following the Eclipse 4.2.1 release train, WTP was upgraded from 3.4.0 to 3.4.1. The famous “new and noteworthy” of WTP 3.4.1 unfortunately still points to the previous 3.4.0 release, but there is a list of fixed bugs available that luckily does point to the right version.

Community reporting about 4.2 SR1 has been equally underwhelming, although just today Steffen Schäfer posted about this release focussing on the new JGit/Git 2.1 versions. Besides him there’s a Chinese post about 4.2.1, which just says the following:

To enhance performance, fixed many bug and the export of war with java source code bug fixes!

Is it perhaps so that with the increasing size, complexity and sheer number of plug-ins and projects on eclipse.org, the one thing that we all simply call “Eclipse” becomes more and more difficult to identify as a specific product on that site and as such harder to report about?

And what about the adoption of the Eclipse 4.2 platform? There has been much debate recently about the abysmal performance of the new platform. Is SR1 a step in the right direction, or do we have to wait for 4.2 SR2, or possibly even 4.3?

What’s new in JSF 2.2?

1 September 2012

JSF 2.2 is final! The proposed final draft was posted on March 15, 2013 and the final vote was passed on April 17, 2013.

Originally it had an anticipated release of the final draft of the spec in Q4 2011 (see Jsf 2 2-bof, slide 3 and JSR 344: JavaServer Faces 2.2). This date slipped, and was first delayed to the first half of 2012 and then finally a date was set for the end of 2012, but that too proved to be insufficient. Following the delay of Java EE 7 itself, JSF 2.2 is now scheduled for 27/mar/2013.

So what’s going to be in 2.2? The JSR gave an overview of ideas, but explicitly made the reservation that not all of those would be in the final spec. In May 2012, the sped lead Ed Burns identified the first 3 so-called ‘Big Ticket Features‘ for JSF 2.2:

  1. Faces Flows
  2. Multi-Templating Deferred to later release
  3. Sensible HTML5 support

During JavaOne 2012, 3 more features were designated as Big Tickets Features, and a JIRA list was created for them:

  1. Cross Site Request Forgery Protection
  2. Loading Facelets via ResourceHandler
  3. File Upload Component

Later the list was changed once again, and the proposed final list of Big Ticket Features became:

  1. Sensible HTML5 support
  2. Resource Library Contracts (a toned down Multi-Templating)
  3. Faces Flows
  4. Stateless views

As can be seen, the originally planned BIG-3 are mainly preserved (although Multi-Templating was severely reduced in scope), while the latter BIG-3 all had their “Big Ticket”-designation sacrificed in favor of Stateless views (implementation wise a minor last minute addition, but with a rather large impact).

One source worth looking at was the actual trunk of the reference implementation and its associated implementation JIRA as well as that of the public specification JIRA.

In this post I’ve highlighted some items from that activity that I found interesting. The full list of all changes and the exact description of them can be found in the official JSF 2.2 specification.

Download

Latest 2.2 snapshot: implementation jar, source jar

New features

Cancelled

With the final release data of JSF 2.2 coming closer, a couple of features that were initially worked on where cancelled and removed for various reasons. Sometimes because a main stakeholder went off to do something else, sometimes because the end result wasn’t satisfactory and more times was needed, etc.

GET Support


View Actions (spec issue 758) (mentioned in JSR)

JSF 2.0 made GET requests a first class citizen in JSF and brought it almost on par with the existing POST support. Just as after a post-back, request values from a GET request can be bound to a model and converters and validators can be applied to that binding.

However, JSF 2.0 didn’t specify an associated action method. A preRenderView event listener can be used instead and that actually does work for a lot of use-cases, but it’s not at the same level as normal action methods that are invoked after a POST request. Users have to manually interact with the NavigationHandler and since the listener is invoked before every rendering, users have to programmatically check if the request was a GET request or a post-back.

View actions are going to allow the same kind of action methods that are used for post-backs to be useable via a new metadata element called <f:viewAction>. The Seam 3 component with the same name was an important inspiration for this.

An additional advantage of a view action is that it can be processed before the entire component tree is being build. Only the meta data needs to be present, which is normally build separately from the rest of the tree.

A very simple example:

  1. <f:metadata>    
  2.     <f:viewAction action="#{someBean.someAction}" />
  3. </f:metadata>

Further reading:

Commits for this feature have been done between 16/jun/11 and 31/jan/13.

Navigation


Faces Flow (spec issue 730) (mentioned in JSR) (Big Ticket Feature)

In web applications, and in applications in general actually, there is often the concept of a “flow” that takes the user through a series of screens. Such flows includes wizards, multi-screen subscriptions, bookings, etc.

Common for such flows is that they are not a random selection of pages linked to each other, but there is clear starting point and a goal where the user comes closer to after each successive step in the flow.

Implementing such flows has in the past been done with ad-hoc techniques, like simply linking full pages to each other and using the session scope to pass information between pages. The problem here is that this makes the result difficult to re-use and not safe when the user opens the same flow in more than one window.

For the last use case CDI already presented a solution via the conversation scope (@ConversationScoped), but this is just a part of the equation and by itself doesn’t enable truly reusable flows. Inspired by Spring Web Flow and ADF Task Flows , JSF 2.2 will directly add support for this concept using the name Faces Flow.

Faces Flow is a so-called Big Ticket Feature, which brings with it quite an amount of new concepts and terminology in JSF. This is explained in much more detail in the official proposal.

Part of this feature will be a new annotation, @FlowScoped, which in the draft implementation has the following JavaDoc:

FlowScoped is a CDI scope that causes the runtime to consider classes with this annotation to be in the scope of the specified flow. The implementation must provide an implementation of javax.enterprise.inject.spi.Extension that implements the semantics such that beans with this annotation are created when the user enters into the specified flow, and de-allocated when the user exits the specified flow.

(A remarkable detail is that JSF 2.2 thus introduces a dependency on CDI here, which might be indicative of JSF moving closer to CDI for other aspects as well)

A flow scoped bean is thus a bean that can be used to back a flow instead of just a single view (page). Unlike a session scoped bean it can only be accessed from views inside the flow (called ViewNodes), and like the view scope for a single view it exists for an instance of the flow, meaning two of the same flows in a different tab or window won’t interfere with each other. To realize this, Faces Flow heavily leans on the new Client Id feature (previously called Window Id).

A flow scoped bean looks as follows:

@Named
@FlowScoped(id = "someFlowName")
public class SomBean {
    public String someReturn() {
        return "/somePage.xhtml";
    }
}

The id someFlowName references the flow this bean will back, and which can be defined on an start node (aka the flow defining view) of a flow via JSF’s meta-data facility as follows:

/someFlowName/someFlowName.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:j="http://java.sun.com/jsf/flow"
>
    <f:metadata>
        <j:faces-flow-definition>
            <j:faces-flow-return id="someReturnName">
                <j:navigation-case>
                    <j:from-outcome>#{someBean.someReturn}</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
        </j:faces-flow-definition>
    </f:metadata>
 
    <!-- Rest of view -->
</html>

(Notice the addition of a new taglib URI in core JSF: http://java.sun.com/jsf/flow)

By convention, creating a directory with the same name as the flow id and putting a view in it with again the same name (without the suffix), automatically designates it as the start node. (optionally, the id attribute of the j:faces-flow-definition element can be used if this structure can’t be met)

Via the j:initializer and j:finalizer sub-elements of the j:faces-flow-definition method expressions can be given that will be executed when the user enters respectively exits the flow, and thus function as a kind of constructor and destructor of a flow.

Intermediate nodes (aka member views) have to declare that they are part of the flow using the same j:faces-flow-definition element that we’ve seen in the start node, but via some at the moment of writing unknown convention (maybe again the name of the directory they reside in?) an id does not have to be explicitly specified. The following shows an example of an intermediate node:

/someFlowName/intermediateNode.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:j="http://java.sun.com/jsf/flow"
>
    <f:metadata>
        <j:faces-flow-definition/>
    </f:metadata>
 
    <!-- Rest of view -->
</html>

To enter and exit flows, JSF’s navigation system has been made aware of flows by allowing the flow- and exit ids to be used at all places where actions are allowed (this is a bit similar to how the Faces Views feature in OmniFaces has extended navigation to support extensionless URLs). To enter the above flow with id someFlowName we could use the following:

    <h:commandLink value="Enter flow" action="someFlowName" />

To exit from the flow we could use the following from any page that’s within the flow:

    <h:commandLink value="Exit flow" action="someReturnName" />

(remember that someReturnName was defined as the id of the j:faces-flow-return return element)

Following the established convention in Java EE that annotations (metadata in case of views) can be overridden by XML in deployment descriptors, everything that can be defined in the metadata section of the views can also alternatively be specified in faces-config.xml.

Besides an @FlowScoped bean, there’s also a new implicit EL variable introduced that’s associated with the current flow: facesFlowScope. This is a simple object-to-object map that can be used for storing arbitrary values. Being a map, input components can directly bind to it, e.g.:

    <h:inputText value="#{facesFlowScope.someKey}" />

The value stored here can be easily referenced on the same or another view of the flow, simply by referencing the expression, e.g.:

    The value that was submitted: <br/>
    #{facesFlowScope.someKey}

One important thing that really sets Faces Flows apart from ye olde navigation rules is that nodes in a graph do not only have to be views, but can be other things as well. The Javadoc on FlowHandler currently mentions the following:

  • View – A regular page like foo.xhtml in Facelets
  • Switch – One or more EL expressions of which the first that returns true determines the next node.
  • Return – Outcome to be returned to the caller of the flow
  • Method Call – An arbitrary method that just like a regular action method can return an outcome on which navigation can take place.
  • Faces Flow Call – A call to another flow, starting a nested flow (keeps the calling flow active until it returns)

The following shows an example utilizing a few more Faces Flow features:

    <f:metadata>
        <j:faces-flow-definition>
 
            <j:initializer>#{someBean.init}</j:initializer>
            <j:start-node>startNode</j:start-node>
 
            <j:switch id="startNode">
                <j:navigation-case>
                    <j:if>#{someBean.someCondition}</j:if>
                    <j:from-outcome>fooView</j:from-outcome>
                </j:navigation-case>
            </j:switch>
 
            <j:view id="barFlow">
                <j:vdl-document>barFlow.xhtml</j:vdl-document>
            </j:view>
            <j:view id="fooView">
                <j:vdl-document>create-customer.xhtml</j:vdl-document>
            </j:view>
 
            <j:faces-flow-return id="exit">
                <j:navigation-case>
                    <j:from-outcome>/exit</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
            <j:faces-flow-return id="error">
                <j:navigation-case>
                    <j:from-outcome>/error</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
 
            <j:finalizer>#{someBean.finish}</j:finalizer>
 
        </j:faces-flow-definition>
    </f:metadata>

Quite a few new methods have been added to the Java API, for instance javax.faces.application.Application has a new method FlowHandler getFlowHandler(). A FlowHandler can be used to obtain the current Flow, transition to a new point in the flow, get a reference to the map behind the facesFlowScope and even to dynamically add a complete new flow. Note though that it does not allow to dynamically manipulate existing flows, which are immutable after being created.

An instance of the Flow class is basically the run-time representation of the faces-flow-definition element, and can be used to obtain the initializer, finalizer, returns, switches, start node id and all view nodes that are part of the given flow. It can also be asked for the Id relative to the current client window. This currently consists of the Client Id and the Flow Id separated by an underscore.

At the time of writing, the implementation is very much a work in progress and various things are still changing on a day to day basis. According to the spec lead Ed Burns, “there will be big changes” in how the Faces Flow elements in the metadata section of a view can be used. The metadata way will most likely be completely removed and flows will be defined in an external file.

Commits for this feature have been done between 29/mar/12 and 07/jun/12.

HTML 5


Pass-through attributes (spec issue 1089) (Big Ticket Feature)

Among the many new features in HTML 5 are a series of new attributes for existing elements. Those attributes includes things like the type attribute for input elements, supporting values such as text, search, email, url, tel, range, number, date.

Additionally there are the so-called custom data attributes, also known as data-* attributes. These are attributes that don’t have a fixed name, but all start with data-, e.g. data-foo. Their purpose is to attach (small) amounts of data to HTML elements, which aren’t rendered but instead can be read by using JavaScript.

The problem is that existing JSF components don’t automatically support these new attributes and have to be updated in order to recognize them. This would be rather logical, if only those components really had to “support” them. But as a matter of fact, they actually don’t explicitly have to support them at all and just have to pass them through to the main rendered element (this is the only catch, for some components it might not be clear what that main element really is).

People have solved this problem in the past by using e.g. wrapped response renderers or custom HTML 5 render kits.

JSF 2.2 takes a universal approach to solve this problem and officially introduces the concept of pass-through attributes. These are a separate collection of attributes next to the existing attribute collection of a component. They are explicitly intended to be rendered directly to the client as opposed of being consumed/processed by the component itself.

From a Facelet, pass-through attributes can be set in 3 ways:

  1. Via a name-spaced attribute on the component tag
  2. Using the child TagHandler f:passThroughAttribute that sets a single attribute
  3. Using the child TagHandler f:passThroughAttributes that sets multiple attributes

Name-spaced attributes are an XML feature that wasn’t previously used by Facelets, but proves to be pretty convenient here to distinguish between two sets of tag attributes. The namespace for the pass-through attributes is http://java.sun.com/jsf/passthrough with the perhaps somewhat unfortunate default short name p (which is already commonly used by the popular PrimeFaces).

Using a name-spaced pass-through attribute looks as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://java.sun.com/jsf/passthrough"
>
    <h:form>
        <h:inputText value="#{bean.value}" p:placeholder="Enter text"/>
    </h:form>
 
</html>

Alternatively a TagHandler can be used as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
>
    <h:form>
        <h:inputText value="#{bean.value}" >
            <f:passThroughAttribute name="placeholder" value="Enter text" />
        </h:outputText>
    </h:form>
 
</html>

Note that this exactly mimics normal attributes vs f:attribute

Setting multiple attributes looks as follows:

<h:outputText value="Something" >
    <f:passThroughAttributes value="#{bean.manyAttributes}" />
</h:outputText>

Where #{bean.manyAttributes} refers to a Map<String, Object> where the values can be either literals or a value expression.

Using Expression Language 3 (part of Java EE 7, just like JSF 2.2), multiple attributes can also be directly defined using an EL expression:

<h:outputText value="Something" >
    <f:passThroughAttributes value="{"one":1, "two":2, "three":3}" />
</h:outputText>

One use-case for this last syntax variant would be when surrounding it by a c:if tag to conditionally set multiple attributes via a fairly terse syntax.

Attributes can also be set in Java via the new getPassThroughAttributes() and getPassThroughAttributes(boolean create) methods in UIComponent. Via the latter method one can test if there are any pass-through attributes without triggering any on-demand creation of data-structures, which is roughly equivalent to how HttpServlet#getSession(boolean create) works.

Setting a pass-through attribute from Java looks as follows:

UIComponent component = new SomeComponent();
Map passThrough = component.getPassThroughAttributes();
passThrough.put("placeholder", "Enter text");

As a bonus, to mimic f:passThroughAttributes a new f:attributes TagHandler was introduced as well, which with not surprisingly we can set multiple regular attributes via map.

Commits for this feature have been done between 22/jun/12 and 17/jul/12 and the associated issue has been marked as resolved.

AJAX


Queue control for AJAX requests (spec issue 1050)

The standard AJAX support in JSF causes AJAX requests to be queued client-side to make sure a page has only 1 such request in transit at the same time.

This is normally beneficial, as it prevents the server from being overloaded and responses arriving out of order. Typical features here are specifying the maximum size of the queue or the amount of time a request is allowed to sit waiting in the queue.

However, JSF lacked those features. Werner Punz wrote about this recently: Apache MyFaces jsf.js queue control.

JSF will add support for controlling the queue by means of a delay attribute on the <f:ajax> tag. This attribute takes a value in milliseconds and signals that if multiple requests arrive within this delay period, only the most recent one is sent to the server. The default is 300 milliseconds, but the special value of none can be specified to disable this mechanism.

Commits for this feature have been done on 10/jun/11 and the associated issue has been marked as resolved.


AJAX file upload component (spec issue 802) (mentioned in JSR)

Having a (AJAX) file upload component in JSF goes back a long time. There is much existing discussion on this issue, and many component libraries have in the mean time implemented something themselves.

An AJAX variant is even more difficult, not in the least since it’s not directly supported in HTML. The so-called XHR level 2 (aka XMLHttpRequest 2) does support this, but at the moment it’s still a working draft and only the very latest versions of the major browsers support it. Therefor it’s not yet a viable option to use in a specification.

There’s an iframe based trick available that works universally across browsers, but this by itself did not work directly with JSF prior to 2.2. To support this, changes had to be made to the mechanism that triggers a JSF request/response cycle. Interestingly, the reference implementation uses this as the transport mechanism and thus the AJAX upload in reality doesn’t use AJAX at all. The spec doesn’t mention this though and so leaves the door open for future implementations using XHR level 2.

A prerequisite to an AJAX file upload mechanism is having a standard file upload in JSF. For this a separate issue was created: Non-Ajax File Upload. Interesting here is that this implementation is based on Servlet 3.0 multipart support, like e.g. this implementation by my co-worker Bauke. This means among others that the venerable FacesServlet is now annotated with the @MultipartConfig annotation and that JSF now requires Servlet 3.0.

The standard file upload component can be used on a view as follows:

  1. <h:form prependId="false" enctype="multipart/form-data">
  2.  
  3.     <!-- The new regular file upload component -->
  4.     <h:inputFile id="fileUpload" value="#{someBean.file}" />
  5.  
  6.     <h:commandButton value="Upload" />
  7. </h:form>

Implementation of the AJAX file upload component was tracked separately as well.

The AJAX file upload component is in typical JSF fashion not a completely separate component, but just requires that the <f:ajax> tag is being added to the regular component:

  1. <h:form prependId="false" enctype="multipart/form-data">
  2.  
  3.     <!-- Now it's the AJAX file upload component -->
  4.     <h:inputFile id="fileUpload" value="#{someBean.file}" >
  5.         <f:ajax />
  6.     </h:inputFile>
  7.  
  8.     <h:commandButton value="Upload" />
  9. </h:form>

The type that’s produced by the upload component is the Servlet’s 3.0 javax.servlet.http.Part. As with regular input components, a validator can be attached which will then have access to the fully uploaded file.

Commits for the regular file upload have been done between 15/dec/11 and 26/sep/12 and the associated issue had been marked as resolved, while commits for the ajax part have been done on 26/Feb/13 and the associated issue had been marked as resolved as well.

Further reading:

Commits for the main feature have been done between 22/May/12 and 22/Feb/13.

State


Stateless views (spec issue 1055) Big Ticket Feature

When JSF 1.0 was released, people found it left a few things to be desired*. Over time nearly all of these initial issues have been taken care of (most of them in the JSF 2.0 release).

Yet, one fundamental issue that people have complained about since day one remained open; the issue of being stateful or put differently the lack of being stateless.

Now unlike the other issues, being stateful is not specifically a JSF issue. Many frameworks, especially component based frameworks are stateful (e.g. Wicket, ASP.NET, etc). The question is even if being stateful is actually an issue or simply something that follows from the fact that many applications do in fact have state and JSF is just managing that state for you.

In JSF 1.x the state mechanism was not entirely optimal though. It stored many things that were put as literals on the page defining a view. For instance, give a component an attribute foo=”bar” inside some table with 10 rows, and the string “bar” would end up 10 times in the view state. JSF 2.0 already fixed that with a mechanism called Partial State Saving, which made sure only changes to the state were saved. As a result of this, very little was still saved.

So why do people still want absolutely no state? There appear to be a number of different reasons, some justified, some debatable. Among those are the following:

  • Coolness, Hype and Hipness
  • Performance advantages
  • Memory advantages
  • Ability to route request to any node in cluster
  • Preventing view expired exceptions

The first item, “Coolness, Hype and Hipness”, is about the fact that being “stateless” is somewhat of a hype for some. According to them; in order to be cool, one has to be stateless, since stateless is what makes things cool (a kind of circle reasoning). The problem here is that many applications simply have state. Using a so-called stateless architecture doesn’t make that state magically disappear, and more often than not these applications have to dedicate some amount of code dedicated to sucking in state from a central DB at the start of each request and spitting it out to the same DB at the end of it. There are good reasons to go stateless (see below), but going stateless just because you’ve heard it’s the new trend and without taking your application requirements into account is not the best idea.

Performance advantages can be debatable as well. As it appears, JSF spends very little time in applying and saving state. This is especially true when state is saved on the server and no serialization is used. Being stateless can in fact have a negative effect if this state is actually really there and now has to be restored from some (remote) location.

Memory advantages can be equally debatable. The memory required by components to save their state is actually very small, while the state the user explicitly keeps (e.g. by using view scoped beans) is already under his or her control. If no state is wanted, the user can always opt to use request scoped beans exclusively.

The ability to route requests to any node in a cluster can be a serious one though. If state is required, no matter how small this state is, a postback HAS to go to the same node as where it originated from. This complicates load-balancing and makes it more difficult to remove a single node from the cluster for e.g. maintenance. Sticky sessions with buddy replication can somewhat solve this issue though, but it’s still not ideal.

Preventing view expired exceptions can also be serious. If e.g. a form is displayed on screen and state is saved on server, then upon the first postback JSF insists the state is there. But on the very first postback it’s nearly impossible to have any real state; namely the page was initially rendered in response to a repeatable GET request. So, whatever state there is saved can theoretically only be cached data that should be fully restorable. A workaround is to save state on the client in this case, but in JSF this is a global setting so then the entire application has to resort to this.

Although the issue asking for a stateless mode attracted the most votes ever, it was created relatively late and therefor wasn’t slot into the JSF 2.2 time frame. But then seemingly out of the blue Manfred Riem suddenly added a proprietary (RI-specific) feature to Mojarra that allowed for stateless views.

The implementation of this was surprisingly minimalistic, with the core of the change consisting of just two simple changes:

  • The TagHandler for <f:view> now processes the boolean attribute transient and passes it to UIViewRoot#setTransient
  • ViewDeclarationLanguage#restoreState simply does not restore state when UIViewRoot is stateless, but only builds the view

It simply makes use of the existing “transient” feature that had been available in JSF for some time on components (e.g. for use on a Form), but never got much attention. When this is set to true JSF would already skip such component when saving state. In fact, code could already set this attribute to true itself on UIViewRoot, but then ViewDeclarationLanguage#restoreState would complain. So, a slightly different explanation of the implementation of this feature is that JSF simply doesn’t complain anymore when there’s no state. And voila… just by removing some nagging JSF was suddenly stateless ;)

This Mojarra specific feature was subsequently proposed for standardization and retroactively taken as the implementation for spec issue 1055. As such a few additional changes were made that are discussed below.

The first additional change is that a public API method was added:

javax.faces.render.ResponseStateManager.isStateless(FacesContext context, String viewId)

This method only works for post backs though, and it thus shouldn’t be used to determine if the current view is stateless (UIViewRoot.isTransient can be used for that). Instead, it’s used to determine if the (non-)state that was last posted back is the special “stateless state”. To encode this “stateless state”, the RI uses the string “stateless” as the value for the view state parameter “javax.faces.ViewState”.

The second change is that if the product stage is “development”, a warning is now logged and a FacesMessage is added to the view when a stateless (transient) view root is used in combination with a view scoped bean.

Example of this feature:

<f:view xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    transient="true"
>
   <html>
        <h:head/>
        <h:body>
             <h:form>
                 <!-- Input components here -->
             </h:form>
        </h:body>
    </html>
</f:view>

The minimalistic approach of this feature does leave some room for improvement. With the current version stateless behavior has to be set per view and it’s orthogonal with the existing state saving options “client” and “server”. Setting an entire application to be stateless via the state saving method context parameter might be a next step. Datatables and similar components also still require that the model before and after a postback is exactly the same. With stateless views this is not necessarily the case, so an extended support for stateless components should use some kind of key here so the implementation can e.g. determine from which row an action originated.

As mentioned, a mere stateless view might not bring the huge performance benefits that are sometimes attributed to the concept “stateless”. However, closely associated (and perhaps expected?) with the concept is that of re-using views (pooling, singletons, …). This aspect is not addressed in JSF 2.2, but Leonardo Uribe is investigating this for MyFaces.

One practical thing to take specifically into account is that the “simply don’t save state” approach might not be compatible with existing components which may not expect that certain values are just not there. It’s left at the user’s discretion to verify that a given component indeed works in stateless mode.

For all its simplicity, a major result of this being put into the specification is that JSF 2.2 compatible components will have to take this into account; either fully support it in some way, or throw an exception of some kind. This awareness can be a great start for more advanced support.

*
For starters it lacked a native templating engine. JSP was (mis)used instead, but it was a bit of an abomination (e.g. life-cycle conflicts and things like the content-interweaving issue). GET support was also nothing to write home about. There was some rudimentary support, but not everybody was able to find this and the prevailing opinion was that JSF didn’t support it at all. For a component based framework, actually creating components was a rather tedious effort that involved the creation of many “moving parts”, which to make matters worse all had to be kept in sync whenever something changed (a situation that’s somewhat reminiscent to the early EJB2 beans).

Commits for this feature have been done between 07/Feb/13 and 28/Feb/13 and all associated issues have been marked as resolved

Resources


ResourceResolver unified with ResourceHandler (spec issue 809)

In JSF 2.0 and 2.1 there is the ResourceResolver and the ResourceHandler.

The ResourceResolver came in with JSF 2.0 from the once standalone Facelets 1.x. By default JSF loads Facelets views from the root of the WAR (the web application root), but via a custom ResourceResolver a user can provide other locations to load these views from. This can be any location for which a URL can be created, like another location and/or name in the WAR, a location inside some .jar file or even a database for e.g. views that are dynamically created at runtime.

The ResourceHandler is used to load artifacts that are served to the client. These artifacts can be anything but are typically things like CSS and JavaScript files. The ResourceHandler has a default location to load resources from as well (the not always entirely optimal world readable /resources in the web application root and META-INF/resources/ on the classpath) and like the ResourceResolver a user can provide a custom implementation that is able to load resources from other locations.

Owing to the different lineage the way to provide custom implementations for both these two artifacts is completely different.

For a custom ResourceResolver a context parameter in web.xml is needed. This is because it came in from a once external library and these can’t add their own tags to faces-config.xml but have to use the generic web.xml parameters:

<context-param>
    <param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
    <param-value>com.example.MyResourceResolver</param-value>
</context-param>

A custom ResourceHandler has to be registered in faces-config.xml as follows:

<application>
    <resource-handler>com.example.MyResourceHandler</resource-handler>
</application>

These different methods for registering isn’t really consistent and the names are not very clear either. Who would guess that a resource resolver is for custom Facelets, while a resource handler is for other resources?

An important issue with the separate ResourceResolver is that it’s defined specifically for Facelets. While Facelets is currently the default and only serious VDL (View Description Language) available, JSF is officially VDL neutral. This means there is no real way in JSF 2.1 to universally load VDL views for whatever VDL is being used. And even when programming specifically for Facelets, a ResourceResolver could not be consulted directly, but had to be obtained from the FaceletFactory, which itself could not be obtained in a standard way.

For JSF 2.2 the functionality of the ResourceResolver has been merged into the ResourceHandler, and the ResourceResolver itself has been deprecated. The main result of this merge is the following new method in ResourceResolver:

public ViewResource createViewResource(FacesContext context, String resourceName)

Compared to the venerable URL resolveUrl(String path) method that createViewResource replaces, the latter is specified to be applicable to general view resources and by default is functional equivalent to the existing createResource. Besides being much more consistent, this means it’s now also possible to load Facelets from a jar file without needing to provide a custom resolver.

Although not specified, it’s expected that JSF implementations will keep supporting ResourceResolver for a while, simply by letting the default resolver call the new createViewResource method. E.g.

public URL resolveUrl(String resourceName) {
    ViewResource viewResource = resourceHandler.createViewResource(context, resourceName);
 
    if (viewResource != null) {
        return viewResource.getURL();
    }
 
    return null;
}

In the reference implementation backwards compatibility is however only partially enabled.

When building a view a ResourceResolver is still consulted as in the following call chain:

ViewHandler#buildView ->  … -> ResourceResolver#resolveUrl -> ResourceHandler#createViewResource

But when checking if a view exists, a ResourceResolver is not consulted as in the following call chain:

ViewHandler#viewExists -> ResourceHandler#createViewResource

For the unification, the existing type javax.faces.application.Resource has been given a base class: javax.faces.application.ViewResource, consisting of only the URL getURL() method.

It’s interesting to note that this unification is attributed to both issue 719 and 809, however both issues originally asked for something else (more or less).

719 seems to ask for a way to load resources from a custom location, but was created before the ResourceResolver was brought into JSF and thus totally ignored this while it’s existence basically solved that issue.

809 is about a situation that existed in the short-lived 2.0, where in addition to a custom ResourceResolver it was also needed to provide a custom ExternalContext, which was very unclear. But this issue was already solved when JSF 2.1 introduced the ViewDeclarationLanguage#viewExists method.

Commits for this feature have been done between 07/Mar/12 and 05/Apr/12 and all associated issues have been marked as resolved


Resource Library Contracts (spec issue 763) Big Ticket Feature

Early on in the development cycle of JSF 2.2 there was excitement about a particular feature that was in the race for inclusion in JSF: multi-templating.

Multi-templating is the culmination of many different request (e.g. about “skinning”, or “re-useable app modules”) that all boil down to having the concept of “themes” in JSF. Theming is something that is supported by a lot of different systems. In operating systems one can change the appearance of e.g. Ubuntu using any of the build in themes, or using externally obtained ones. On the web, things likes WordPress or Blogger have elaborate support for it as well.

The overarching idea is that with the press of a button a user can change the appearance of an application in potentially many ways (colors, fonts, images, even layout) all at once while all functionality stays the same. From a programmer’s point of view the impact on the code should be absolutely minimal or even non-existent.

The multi-templating feature for JSF might have included a kind of admin management console, where users could download their own themes, switch between them on the fly, offer a marketplace, gallery or app store for theme bundles with meta-data where users of an application (not the programmers) could download themes and apply them to their account (assuming a kind of multi-tenancy setup), etc etc. There might have been some sort of inheritance in those app bundles, and who knows what.

Unfortunately this all proved to be too much and near the end of the JSF dev cycle (nov/2012) the feature was deferred to a later release.

Shortly after that a reduced scope was proposed and accepted for inclusion in JSF 2.2. Because the work on this started very late, the emphasis above all had to be on the reduced scope aspect, while keeping the door open for future more elaborate support.

The result is a relatively small but important addition to the existing resource handling mechanism; the introduction of a mere “prefix” for resource libraries that is more or less invisible to template clients. The “prefix” simply translates into a directory name that stores resources (which because of the “ResourceResolver unified with ResourceHandler” feature can also consist of Facelets views now, and thus Facelets templates). If the directory that stores those resources is in a .jar file, a “theme” can be changed by exchanging the .jar file at build time. There are two default locations for this: /contracts in the web application root, and META-INF/contracts on the class path.

Granted, it’s a far cry from what the initial multi-templating feature promised. There is no meta-data associated with a collection of resources, there’s no real interface and no real bundle. There has also been little focus on the run-time switching aspect (but there is some support, see below). Essentially it’s an extra directory used to group resources (a kind of namespace if you will), with a few mechanisms (some static, some dynamic) to determine which of those get imported into the “global namespace”.

Even though there’s no explicit interface present or any module-like declaration of what’s being exported, the spec refers to this directory as a contract and informally explains for the sake of discussion that the declaration of this contract can be thought to consists out of three elements:

  1. The templates present in the directory
  2. The insertion points in such templates
  3. Resources such as Images, CSS and JavaScript files present in the directory (optionally)

Following this, one could informally (e.g. in a readme.txt) declare a contract as follows:

The contract provides the template “foo.xhtml” which has insertion points “bar” and “kaz”.

Because of the informal declaration it’s thus not possible for tools to check if two different contract implementations (two different directories) indeed adhere to the same contract declaration (but remember the prevailing “reduced scope” argument for this feature and the possibility for this to be added in a later version of the spec).

There are basically three variations via which resource library contracts can be used:

  1. The Highlander rule: There can be only one
  2. Dynamic selection per view
  3. Static selection for view patterns

The Highlander rule; There can be only one, is akin to how injection is resolved in CDI. There simply has to be one implementation of a contract present in either contracts or META-INF/contracts. When this situation holds, no explicit configuration or qualification has to be done. The following demonstrates this:

Assume the following file structure:

/contracts
    /contract1
        template.xhtml
contract-client.xhtml

With the following file contents:

/contracts/contract1/template.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <h:body>
 
        Template from contract implementation 1 <br/>
 
        <ui:insert name="content"/>
 
    </h:body>
</html>

contract-client.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <ui:composition template="/template.xhtml">
 
        <ui:define name="content">
            Content from template client.	
        </ui:define>
 
    </ui:composition>
</html>

When packing these 2 files in a ROOT.war (yes only these 2 files, noting else is needed) and deploying it, requesting localhost:8080/contract-client.jsf will yield the following result:

Template from contract implementation 1 
Content from template client.

Notice that the Facelet “contract-client.xhtml” refers to just /template.xhtml as its template instead of /contracts/contract1/template.xhtml. Since /contracts/contract1/ is the only “contract directory” that contains a Facelet called template.xhtml the resolution is straightforward.

As mentioned above, we can change the template by deleting the /contracts/contract1/ directory and copying a new directory (possibly with a different name) there that contains a Facelet called template.xhtml. Of course that would not be a terribly exciting way to swap templates and certainly in JSF 2.1 we could also just delete a Facelet and copy a new one into whatever directory we used to store our templates. When we take into account that templates and resources can come from a single jar file as well, the “Highlander approach” can still be interesting as it allows us to change the look of the application at build time by exchanging a jar.

Things get more interesting when we consider the case where we have multiple implementations of the same contract present.

Assume the following file structure:

/contracts
    /contract1
        template.xhtml
    /contract2
        template.xhtml
contract-client.xhtml

With the same definitions as in the first example and the following new one:

/contracts/contract2/template.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <h:body>
 
        Template from contract implementation 2 <br/>
 
        <ui:insert name="content"/>
 
    </h:body>
</html>

There are now 2 conflicting definitions of template.xhtml. In CDI you will get an error if such ambiguity exists, but in JSF 2.2 it’s undefined behavior. The RI picks and chooses one at random. (perhaps an opportunity for a utility library or tooling to flag such error).

An individual view can dynamically (or when required statically) resolve this ambiguity by using the new contracts attribute on <f:view>. When we want contract-client.xhtml to statically use the version of its template in the /contract2 directory we could change it as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <f:view contracts="contract2">
        <ui:composition template="/template.xhtml">
 
            <ui:define name="content">
                Content from template client.	
        </ui:define>
 
        </ui:composition>
    </f:view>
</html>

The value of the contracts attribute can also come from an EL expression. With the help of an extra bean we can create a rudimentary theme switcher in JSF 2.2:

@Named
@SessionScoped
public class ThemeSwitcher implements Serializable {
 
    private static final long serialVersionUID = -1L;
 
    private String theme = "contract1";
 
    public void switchTheme() {
        if ("contract1".equals(theme)) {
            theme = "contract2";
        } else {
            theme = "contract1";
        }
    }
 
    public String getTheme() {
        return theme;
    }
}

contract-client.xhtml needs to be changed as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <f:view contracts="#{themeSwitcher.theme}">
        <ui:composition template="/template.xhtml">
 
            <ui:define name="content">
                Content from template client.
 
                <h:form>
                    <h:commandButton action="#{themeSwitcher.switchTheme}" value="Switch theme" />
                </h:form>	
            </ui:define>
 
        </ui:composition>
  </f:view>
</html>

Note that the contracts attribute is now bound to the EL expression #{themeSwitcher.theme}.

Unfortunately, the contracts attribute in only allowed to be used on a top-level <f:view>. This means we can’t e.g. use a ‘normal’ template to abstract it away. If we want to switch the theme of an entire application this way we need to put this expression on each and every view, which is not entirely DRY.

Finally there is the “Static selection for view patterns” options. With this we can configure an entire application or a collection of views (via a pattern) to use a specific contract. This is however a static configuration and thus can’t be used for any run-time switching of themes.

Static selection for view patterns can be done via the new <resource-library-contracts> element in faces-config.xml. If we remove the <f:view> from contract-client.xhtml again and then leave the rest as is, we can select that the template to be used is from the contract1 directory with the following JSF 2.2 faces-config.xml file in WEB-INF:

<?xml version="1.0" encoding="UTF-8"?>
 
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">
 
	<application>
		<resource-library-contracts>
			<contract-mapping>
				<url-pattern>*</url-pattern>
				<contracts>contract1</contracts>
			</contract-mapping>
		</resource-library-contracts>
	</application>
 
</faces-config>

(note that for JSF 2.2 the well known java.sun.com name-space changed to xmlns.jcp.org)

It would have been great if the <contracts> element could have accepted an EL expression, but this is not possible and only literals are allowed. It’s fairly easy to change the value of <contracts> to contract2, but it requires a restart and it will take effect for all users of a web app.

While this feature may leave some things to be desired, it’s nevertheless an excellent foundation to build more elaborate functionality. Hopefully JSF 2.3 will indeed focus on this.

Further reading:

Commits for this feature have been done between 15/Nov/12 and 16/Mar/13 and all associated issues have been marked as resolved.

Injection / Annotations


Injection in most JSF artifacts (spec issue 763) (mentioned in JSR)

In JSF 2.1, relatively few JSF artifacts are injection targets for EJB (@EJB, @Resource), CDI (@Inject) or JSF’s native injection mechanism. Basically only managed beans (backing beans) are injection targets.

This poses a problem for e.g. converters and validators, which not rarely need an EJB service to do their work. For instance, an incoming user ID from a GET request might needs to be converted to a User instance via the Stateless EJB UserService. There are some workarounds for this as outlined in this excellent guide from my co-worker Bauke, but they ain’t pretty.

In JSF 2.2 injection will be possible in many more artifacts, like for instance in a StataManager, a ResourceHandler, and even in a PartialViewContectFactory. Specifically injection into an ActionListener, SystemEventListener and PhaseListener can be really useful and is now possible.

Unfortunately the ones that perhaps matter most of all, converters & validators, are still not injection targets. It’s likely that those will be taken into consideration for JSF 2.3 though.

Commits for this feature have been done between 27/aug/11 and 31/oct/11 and the associated issue had been marked as resolved, but on 11/jan/12 an additional commit was done that changed how the InjectionProvider is internally obtained by the FactoryFinder.


CDI compatible @ViewScoped (spec issue 1087)

One of the many important features that JSF 2.0 brought was the view scope. This is the scope that is active for a single view (page) and post-backs to that view from a single window or tab. Managed beans utilize this scope mainly via the @ViewScoped annotation (there’s an XML variant for the masochists among us).

Despite all the goodness that @ViewScoped brought us, it’s unfortunately* also known as the one thing that prevented CDI to be a drop-in replacement for ye olde JSF Managed Beans. Namely, @ViewScoped works exclusively with those JSF Managed Beans. This poses a dilemma. For many problems the view scope is the better scope, but CDI beans are the better bean (always). Choosing @ViewScoped means giving up CDI, and choosing CDI means giving up @ViewScoped.

(* This unfortunate situation is a result from the fact that CDI finished relatively late in the Java EE 6 development cycle, while JSF 2 finished rather early. The annotation based managed beans facility in JSF 2 may look like a duplication of the CDI efforts, but it’s actually the exact same facility that was in JSF 1.0, only with annotations as alternative for XML.)

Several third parties like Seam 3 and CODI have provided solutions for this problem, but supposedly many of them have various issues, and at any length such important core functionality should maybe not depend on a third party.

So, JSF 2.2 will support the view scope directly for CDI, by providing a CDI extension for this.

Besides this plain fact, there are a couple of interesting observations to be made.

The first is that JSF gives a very clear signal it’s moving towards CDI. It now has a second dependency on CDI, although an optional one. If CDI is not available the annotation will simply not have any effect.

The second is that JSF 2.2 has introduced a new annotation, javax.faces.view.ViewScoped instead of reusing the existing javax.faces.bean.ViewScoped as most if not all existing third party solutions do. The reason for this is that this way the entire javax.faces.bean package can be deprecated later on. Indeed, javax.faces.bean.ViewScoped has gotten a “pre-deprecate” warning in its Javadoc:

The annotations in this package may be deprecated in a future version of this specification because they duplicate functionality provided by other specifications included in Java EE. When possible, the corresponding annotations from the appropriate Java EE specification should be used in preference to these annotations. In this case, the corresponding annotation is javax.faces.view.ViewScoped. The functionality of this corresponding annotation is identical to this one, but it is implemented as a CDI custom scope.

Early versions of the new annotation hinted that GET requests back to the same view would also be considered to be within the same view scope. With the current annotation this is not the case, as a GET request will always create a new view instance. However in later iterations this mysterious comment disappeared again.

The exact Javadoc that said this was:

When this annotation, along with javax.inject.Named is found on a class, the runtime must place the bean in a CDI scope that remains active as long as the user remains on the same view, including reloads or navigations from the current view immediately, with no intervening views, back to the same view, even via an HTTP GET request.

(emphasis mine)

But as said, this comment was removed, so most likely the new CDI view scope will NOT magically work for GET requests as well.

Example in code:

import javax.inject.Named;
import javax.faces.view.ViewScoped;
 
@Named
@ViewScoped
public class Foo {
    // ...
}

Commits for this feature have been done on 31/aug/12 and the associated issue has been marked as resolved, but the actual implementation had been deferred to JAVASERVERFACES-2506 for which a commit was done on 28/sep/12 and has been marked as resolved. Several renames and strengthening of the implementation was done via a diverse range of other issues, e.g. JAVASERVERFACES-2641, for which commits have been done between 9/jan/13 and 10/jan/13 and which has been marked as resolved as well.


Facelets Component Tag can be declared via annotation (spec issue 594)(mentioned in JSR)

Before JSF 2.0, creating (java based) custom components was a lot of work. The amount of required work was largely reduced in JSF 2.0, mainly because Facelets does not require an explicit tag handler and because a component can be registered via its annotation.

However, one tedious requirement remained. In order to make a component useable in Facelets, a tag name for it had to be declared in a *-taglib.xml file.

In JSF 2.2 this requirement has been lifted and the tag declaration can be done via the component’s annotation. For this the @FacesComponent annotation introduces 3 new attributes:

  • createTag – If set to true the component will be directly useable via a tag on a Facelet.
  • tagName – Optional explicit name for the tag. If omitted, the class’ simple name with the first character in lowercase will be used.
  • namespace – Optional explicit namespace for the tag. If omitted the namespace ‘http://xmlns.jcp.org/jsf/component’ will be used.

For instance:

  1. @FacesComponent(value="components.CustomComponent", createTag=true)
  2. public class CustomComponent extends UIComponentBase {
  3.  
  4.     @Override
  5.     public String getFamily() {        
  6.         return "my.custom.component";
  7.     }
  8.  
  9.     @Override
  10.     public void encodeBegin(FacesContext context) throws IOException {
  11.  
  12.         String value = (String) getAttributes().get("value");
  13.  
  14.         if (value != null) {        
  15.             ResponseWriter writer = context.getResponseWriter();
  16.             writer.write(value.toUpperCase());
  17.         }
  18.     }
  19. }

Without the need to configure or declare anything else, this component can now be used on a JSF 2.2 Facelet as follows:

page.xhtml

  1. <html xmlns="http://www.w3.org/1999/xhtml"
  2.     xmlns:h="http://java.sun.com/jsf/html"
  3.     xmlns:test="http://xmlns.jcp.org/jsf/component"
  4. >
  5.     <h:body>   		
  6.         <test:customComponent value="test"/>        
  7.     </h:body>
  8. </html>

Commits for this feature have been done between 13/feb/12 and 15/feb/12 and the associated issue has been marked as resolved.


Facelets ResourceResolver can be declared via annotation (spec issue 1038)

In Facelets it has always been possible to let users provide a hook to influence the way that Facelets loads template files. This is done via a ResourceResolver that users can register in web.xml via the environment parameter javax.faces.FACELETS_RESOURCE_RESOLVER.

With such a resolver, users can let Facelets load templates from the classpath or from any location that is expressible via a URL.

The web.xml mechanism however pre-dates the time that Facelets was officially part of JSF itself and it of course requires the presence of such a web.xml file. Since Facelets is now officially part of JSF and there is a strong trend going to make XML optional in favor of annotations, the Facelets resource resolver has now gotten an official annotation in the JSF spec:

@FaceletsResourceResolver.

The presence of that annotation on a class automatically registers it as a Facelets resource resolver. If a resolver is specified in both XML and via an annotation, the XML overrides the annotation as per the usual Java EE conventions. If multiple annotated classes are found, the first one encountered is used and a warning is logged.

Commits for this feature have been done between 06/oct/11 and 12/oct/11 and the associated issue has been marked as resolved.


Component and validator annotations default to simple class name (spec issue 703)

With Java EE 5 a trend was started to introduce convention over configuration into the platform, a trend which continued strongly in Java EE 6.

For annotations that cause a class to be registered under some name this typically means the simple class name (class name without the package) with the first letter de-capitalized is taken as the default for this name. For instance, in JSF 2 with the following class definition the managed bean will be available to EL using the name foo

@ManagedBean
public class Foo {
    // ...
}

If needed the name can be specified explicitly:

@ManagedBean(name="myfoo")
public class Foo {
    // ...
}

For components and validators this convention wasn’t used, and the name always had to be specified fully, e.g. for a component:

@FacesComponent("bar")
public class Bar extends UIComponentBase {
    // ...
}

Notice the inconsistency between “name=” for the managed bean and not having to use an attribute name for the component.

In JSF 2.2 the name can now be omitted for components, converters and validators as well, so the code shown above can become:

@FacesComponent
public class Bar extends UIComponentBase {
    // ...
}

This makes the overall platform a bit more consistent and is especially useful for simple implementations in application space. Most likely component libraries will still provide a (long) explicit name to prevent name clashes.

Commits for this feature have been done on 07/mar/12 and the associated issue has been marked as resolved.

Security / Type-safety


Cross Site Request Forgery protection (spec issue 869) (mentioned in JSR)

Cross Site Request Forgery is an attack that lets users unknowingly do a request to a site where they are supposed to be logged-in, that has some side-effect that is most likely in some way beneficial to the attacker. GET based requests are most obvious here, but POST requests are just as vulnerable.

JSF seems to have some implicit protection against this when state is saved on the server, since a post-back must contain a valid javax.faces.ViewState hidden parameter. Contrary to earlier versions, this value seems sufficiently random in modern JSF implementations.

Nevertheless, JSF 2.2 will contain additional/even stricter protection against this. Among others client state encryption is now on by default and there’s a token parameter for protection of non-postback views.

Commits for this feature have been done between 13/sep/11 and 21/sep/11.


More thorough type checking for composite component attributes (spec issue 745)

In JSF 2.1, it’s not always easy to defer the exact type of a value expression bound to an attribute of a composite component, if said expression resolves to null. Finding the right type just by asking ElResolver is complicated by the fact that ELResolver#getType is supposed to return the most general type that is accepted by the corresponding ELResolver#setValue. It’s also not always equal to getValue().getClass() as explained by the javadoc.

In JSF 2.1, CompositeComponentAttributesELResolver#getType returned null when asked for the type, since it’s a read only resolver.

For JSF 2.2 this is replaced with an algorithm that first checks if the base is an ExpressionEvalMap and if so simply gets the value expression from that and asks it for its type. Then the metadata for the composite component is consulted to see if there’s a type being set for the given attribute (this corresponds to the type attribute on the cc:attribute tag). Finally, if a type is found via the metadata it’s only used if the type obtained from the value expression is either null, or if the metadata type is more specific (narrower).

Commits for this feature have been done between 20/jul/11 and 10/aug/11.

Java API


Programmatic configuration (spec issue 533)

In Java EE, configuration can generally be done via either annotations or XML. Increasingly, there’s also a third variant available: programmatic configuration. A well known example of this is Servlet 3.0, where a Servlet can be added via the @WebServlet annotation, the <servlet> element in web.xml, or by calling ServletContext#addServlet.

This is supported in JSF as well, e.g. via the Application and FactoryFinder classes. The OmniFaces utility library for example uses this to programmatically set a new ViewHandler.

Those existing classes however are not always optimal. They are more or less at a kind of intermediate level: they accept objects (as opposed to Strings), but in a rather raw form. In order to satisfy the API, the user still has to do some work manually and in addition to that often has to make the calls at exactly the right time. Too early and the call fails because nothing related to JSF has been initialized yet, too late and the call won’t have any effect since the artifact in question has already been set and doesn’t allow the programmer to programmatically reset it. Furthermore, just like in Servlet 3.0, they cover only a fraction of the functionality that annotations and XML cover.

JSF 2.2 will introduce an exciting new variant of programmatic configuration: a user specified callback method in which a DOM root representing the system’s meta-data (faces-config.xml) can be populated right before JSF processes it. In a way this is at a lower level than the existing programmatic configuration, since it will only allow String based values. On the other hand, it’s at a higher level since the programmer only has to specify the FQN of e.g. a ViewHandler class and does not need to worry about calling its constructor with the previous ViewHandler (if any) and making sure all injections have been done and life-cycle methods have been called for it.

A difference with other programmatic methods is that this particular API only allows for new configuration to be contributed, i.e. it can not be used to modify or append directly to existing configuration. It should be treated just like having an additional faces-config.xml file present in the application.

Being a callback, it does automatically solves the problem of when it’s the right time to call the configuration API.

Said callback method is provided by a class that extends and implements the abstract class javax.faces.application.ApplicationConfigurationPopulator. A file containing the name of the implementing class has to be put into the META-INF/services directory with as name the fully qualified class name of this abstract class. JSF can then use the java.util.ServiceLoader mechanism to pick this class up. Incidentally this is the same mechanism that ServletContainerInitializer uses.

User code can get a hold of all such service instances (one per jar that’s on the classpath) as well using code such as the following:

ServiceLoader services = 
    ServiceLoader.load(ApplicationConfigurationResourceDocumentPopulator.class);

The method to be implemented is called populateApplicationConfigurationResource, returns void and accepts a single argument of type org.w3c.dom.Document.

E.g.

META-INF/services/javax.faces.application.ApplicationConfigurationPopulator

com.example.MyInitializer

 

com/example/MyInitializer.java

public class MyInitializer extends ApplicationConfigurationPopulator {
 
    public void populateApplicationConfiguration(Document document) {
        String ns = document.getDocumentElement().getNamespaceURI();
 
        Element applicationEl = document.createElementNS(ns, "application");
        Element viewHandlerEl = document.createElementNS(ns, "view-handler");
 
        viewHandlerEl.appendChild(
            document.createTextNode(MyViewHandler.class.name())
        );
 
        applicationEl.appendChild(viewHandlerEl);
        document.appendChild(applicationEl);
    }
}

(The DOM API is rather verbose, but with a small utility method this can easily be reduced to something like addNode(document, “application/view-handler”, MyViewHandler.class);)

Commits for this feature have been done between 30/may/12 and 12/sep/12 and the associated issue has been marked as resolved.


FaceletFactory in the standard API (spec issue 611)

JSF has a facility for obtaining factories for various things via the FactoryFinder. Even though Facelets is a standard part of JSF since 2.0, the FaceletFactory could not be obtained this way as it was an implementation detail.

In JSF 2.2, the status of Facelets as a default technology within JSF has been given another boost by making this factory obtainable from the FactoryFinder and moving it to the API part of JSF. The factory is obtainable via the constant FactoryFinder.FACELET_FACTORY (javax.faces.view.facelets.FaceletFactory).

A practically consequence of this is that it’s now possible to create a Facelet programmatically (in a portable way) and call the apply() method in order to build a component tree.

Commits for this feature have been done on 15/sep/11 and the associated issue has been marked as resolved.


FlashFactory and FlashWrapper (spec issue 1071)

Next to the FaceletFactory, another new factory obtainable via the FactoryFinder in JSF 2.2 is the new FlashFactory. This factory can be used to create Flash instances.

Obtaining those instances was already possible before JSF 2.2 via ExternalContext#getFlash and this will remain the default way for ‘normal’ user code. The fact that there’s now a standard factory underneath means that there’s a hook available for overriding and/or wrapping the default implementation. This mechanism is explained here.

The factory is obtainable via the constant FactoryFinder.FLASH_FACTORY (javax.faces.context.FlashFactory).

Overriding it in faces-config.xml can be done as follows:

  1. <factory>
  2.     <flash-factory>com.example.MyFlashFactory</flash-factory>
  3. </factory>

In addition to a factory, a new convenience wrapper class for the Flash, FlashWrapper has been added. Similar to existing wrapper classes like ViewHandlerWrapper, ExceptionHandlerWrapper, etc this allows one to wrap an existing Flash instance and selectively override methods.

Commits for this feature have been done on 16/feb/12 and the associated issue has been marked as resolved.


Instantiating composite component in Java (spec issue 599)

JSF 2.0 introduced the concept of the composite component: a component that is created via an .xhtml template instead of Java code. Even though the composite component is defined in .xhtml, it’s a first class component and ends up in the component tree as a Java component.

Up till now however there wasn’t any official API to instantiate a composite component as a Java instance via user code. So when building a component tree programmatically (see e.g. Authoring JSF pages in pure Java), incorporating those composite components was challenging to say the least.

JSF 2.2 will provide an explicit API for this.

Commits for this feature have been done between 02/oct/11 and 01/feb/13 and the associated issue has been marked as resolved.


Support for the Collection interface in UIData (spec issue 479) (mentioned in JSR)

From the beginning of JSF, the UIData component (known from e.g. <h:dataTable>) only realistically supports the List, native array and JSF specific DataModel as input for its value binding*. This means other collection types always have to be expressed as any of these types. While this is not particular difficult, it’s a tedious thing to do and makes the code more verbose.

This issue has a rather long history, but it’s now finally addressed.

JSF 2.2 will introduce a javax.faces.model.CollectionDataModel in which UIData wraps an incoming value if it’s of type Collection. Collection is one of the last types being checked, so if the incoming value is a List the ListDataModel takes precedence.

The following are now the supported types:

  • null (becomes empty list)
  • javax.faces.model.DataModel
  • java.util.List
  • java.lang.Object[]
  • java.sql.ResultSet
  • javax.servlet.jsp.jstl.sql.Result
  • java.util.Collection new!
  • java.lang.Object (becomes ScalarDataModel)

Commits for this feature have been done on 31/jan/12 and the associated issue has been marked as resolved.

* java.sql.ResultSet and javax.servlet.jsp.jstl.sql.Result are officially also supported, but it seems usage of those are rather rare in practice. Also, only DataModel is internally supported, other types are automatically adapted into a DataModel.


Many additional wrapper classes

In JSF many parts of the framework can be replaced by user supplied versions. Those versions can either completely replace the existing functionality, or can do this partially. For this the decorator pattern is utilized, where the user supplied implementation gets a reference to the existing implementation and can delegate functionality that it doesn’t want to replace to that.

To make this easy, JSF offers a bunch of wrapper classes; ViewHandlerWrapper for ViewHandler, StateManagerWrapper for StateManager, etc.

Until now there weren’t wrapper classes for:

  • Lifecycle
  • ActionListener
  • Renderer
  • NavigationCase
  • NavigationHandler

In JSF 2.2 there now are, with the predictable names:

  • LifecycleWrapper
  • ActionListenerWrapper
  • RendererWrapper
  • NavigationCaseWrapper
  • NavigationHandlerWrapper

For LifecycleWrapper there wasn’t a separate JIRA issue, but it was committed as part for the work for spec issue 949, while many others had their own issue, e.g. ActionListenerWrapper had spec issue 993.

Commits for this feature have been done between 09/May/11 and 30/Nov/12 and all associated issues have been closed.

Lifecycle


Identify client windows via a Window Id (spec issue 949)

Arguably one of the biggest problems that has been plaguing web application development since its inception is the inability to distinguish requests originating from different windows of a single browser. Not only has an actual solution been long overdue, it has taken a long time to realize this even was a problem.

The root of the problem, as always, is that the HTTP protocol is inherently stateless while applications in general are not. There is the concept of a cookie though, which is overwhelmingly the mechanism used to distinguish requests from different users and to implement things like a session scope where on its turn the bulk of login mechanisms are based on.

While a cookie does work for this, it’s global per browser and domain. If a user opens multiple tabs or windows for the same domain then requests from those will all send the same cookie to the server. Logging in as a different user in a different window for the same website is thus not normally possible, and having workflows (involving post-backs, navigation) in different windows can also be troublesome because of this.

In JSF there are various solutions that are somehow related to this. The view scope effectively implements a session per window as long as the user stays on the same page and does only post-backs. The Flash is used for transferring data between different pages (presumably within the same window) when navigation is done via Redirect/GET. There’s a wide variety of scopes implemented by third parties that do something similar.

All of these have some implicit notion or assumption of the concept of a ‘client window’, but there is no explicit API for this.

JSF 2.2 will introduce support for two different aspects of this:

  1. Identification of an individual window: the Client Window Id
  2. API and life-cyle awareness of the window concept

The first item unfortunately cannot be implemented perfectly, as ultimately only the HTTP protocol can do this. HTTP/2.0 might indeed do this, but it will be some time before that will be available. JSF will do a best-effort though and might allow users to easily plug-in their own implementation if they so desire.

Since no method to identify a window is perfect, the user can configure the preferred method in web.xml via a context parameter:

<context-param>
    <param-name>javax.faces.CLIENT_WINDOW_MODE</param-name>
    <param-value>url</param-value> 
</context-param>

The spec only demands support for url and none. none is the default and means the feature is disabled.

The only other choice url means the feature is enabled, and that the client window is tracked via either a hidden field or a request parameter.

The hidden field should be written during state saving with the name “javax.faces.ClientWindow” that contains the client window ID. Just like the view ID, JSF can use this after a post-back. For GET requests the spec defines the jfwid query parameter, which has to be added to links and contains the same client window Id value (the Servlet spec describes a similar mechanism for the session ID). E.g.

http://example.com/foo?jfwid=953FAAGhGhYF78%3A1

When both the hidden field and query parameter are present, the hidden field takes precedence.

It’s an open question what should happen when such link is opened in a new window or tab (e.g. using a browser’s “Open in New Tab” feature when right clicking on a link).

If needed, a page author can disable the appending of the jfwid parameter to a link when using the core components <h:link> and <h:button> via the newly introduced attribute disableClientWindow. E.g.

<h:link value="New" outcome="aview" disableClientWindow="true" target="_blank" />

Component authors can offer support for this as well using the disableClientWindowRenderMode method on the ClientWindow class. E.g.

FacesContext context = ...
 
ClientWindow clientWindow = context.getExternalContext().getClientWindow();
if (clientWindow != null) {
    try {
        clientWindow.disableClientWindowRenderMode(context);
        // Do stuff
    } finally {
        clientWindow.enableClientWindowRenderMode(context);
    }
}

Modes other than url and none are possible, but are for now implementation specific. Non-recognized modes seem to be allowed to be silently interpreted as url. Remarkable is that the RI never actually checks for the value url anywhere.

In the reference implementation the client window ID consists of the session ID (JSESSIONID) followed by separator and a sequential number, e.g. 953FAAGhGhYF78:1. The exact format of this ID is implementation specific and no assumptions can be made that it contains the session ID.

There are various places where the client window concept will appear in the API, but most visible will be the new class that was already briefly mentioned above: ClientWindow and the method to obtain it: ExternalContext#getClientWindow().

The JavaDoc for ClientWindow mentions the following:

The lifetime of a ClientWindow starts on the first request made by a particular client window (or tab, or pop-up, etc) to the JSF runtime and persists as long as that window remains open or the session expires, whichever comes first. A client window is always associated with exactly one UIViewRoot instance at a time, but may display many different UIViewRoots during its lifetime.

Note that client window ID nor ClientWindow implement a new scope, but are instead a basis on which existing and new scopes can be portably implemented.

See also these resources:

Commits for this feature have been done between 23/feb/12 and 23/oct/12 and the associated issue has been marked as resolved, but extra commits were done between that date and 14/mar/13. A separate issue to implement this feature was created at JAVASERVERFACES-2572. A commit for the implementation issue has been done on 02/Nov/12 and the associated issue has been marked as resolved.


Restoring view scope before view is build (spec issue 787)

In JSF 2.0 a new scope called the view scope was introduced. The life-time of this scope is coupled to that of the view state associated with the component tree for a given view. As such it’s easy to just store the data in this scope along with the view state and restore it whenever view state is restored, which happens right after the view has been build.

However, for some advanced usages it’s more convenient to have the view scope restored before the view is build again. As a very contrived example, the bean Intro from the code shown in Single class pure Java JSF application could not be view scoped, since the view scope doesn’t exists at the time the view needs to be build.

Disentangling the view scope from the general view state data actually has other benefits as well, e.g. users could provide alternative handlers for the view scope, something which is not possible or at least very difficult and not portable at the moment.

Currently a new method (UIViewRoot#restoreViewScopeState(FacesContext context, Object state)) to restore only ViewScope has been committed. A separate effort is planned for JSF 2.2 to also create the corresponding saveViewScopeState, but as of yet nothing has been committed for that.

Commits for this feature have been done between 9/jun/11 and 27/jul/11 and the associated issue has been marked as resolved.


System events for The Flash (spec issue 766)

JSF 2 introduced the concept of system events, which are events that can be fired by arbitrary objects at arbitrary points during the request processing lifecycle.

In the current version JSF 2.1 there are some 16 events defined, e.g. PostAddToViewEvent, PostConstructViewMapEvent, PreRenderViewEvent, PreValidateEvent, etc.

JSF 2.2 will fire 4 additional events specifically for usage with The Flash. These are:

  1. PostKeepFlashValueEvent – Fired when a value is kept in The Flash
  2. PostPutFlashValueEvent – Fired when a value is stored in The Flash
  3. PreClearFlashEvent – Fired before The Flash is cleared
  4. PreRemoveFlashValueEvent – Fired when a value is removed from the Flash

Commits for this feature have been done between 28/oct/11 and 31/oct/11.


Publish PostRestoreStateEvent (spec issue 1061)

Normally system events in JSF are fired/published via the Application#publishEvent API.

However in JSF 2.1 and before, PostRestoreStateEvent has been an exception to this rule. The problem is that this event must be delivered to all UIComponents. Requiring the use of the publish API for this is sub-optimal with respect to memory requirements, since it would also require every component to return a list with itself as a listener when UIComponent.getListenersForEventClass() is called.

Earlier versions of JSF therefor delivered the event directly to the components using a tree traversal, but this meant it was not possible to install any listeners for this event.

In JSF 2.2 this problem was solved by simply doing both the event publishing (without making UIComponents default listeners) AND doing the traditional tree traversal. In Mojarra, the event is published first and then the tree traversal starts.

Commits for this feature have been done on 15/dec/11.


Mandate tree visiting for partial state saving (spec issue 1028)

In order to implement the partial state saving feature of JSF, an implementation must somehow look at all components in the component tree and ask them for their (partial) state.

The exact way in which this is done was implementation specific in JSF 2.1 and earlier. Mojarra used a tree visiting algorithm for this, while MyFaces used a so-called “facets + children” traversal.

The differences between those two are somewhat technical, but one of them is that tree visiting allows the algorithm for the actual traversal to be plugged-in (strategy pattern), while the “facets + children” traversal doesn’t allow this (the code accesses the list of children of a component directly and iterates over it).

Another major difference is that tree visiting is “in context” (parent component can set up a context/scope before its children are visited), while “facets + children” traversals just follow a ‘dumb’ pointer structure.

Finally, tree visits have the ability to visit “virtual components” created by iterating components like UIData. (for a typical JSF data table, there is no component per row in the tree, but the UIData creates this illusion by swapping state in and out for each row).

For state saving, this are somewhat conflicting properties. Setting up a context and doing iterating over virtual children is unwanted, but influencing the traversal can be important. JSF 2.1 introduced the IS_SAVING_STATE and SKIP_ITERATION hints, which can undo the unwanted effects, while keeping the ability to influence the traversal.

In JSF 2.2, tree visiting will now be mandated for partial state saving. StateManager#saveView and StateManager#restoreView have been deprecated in favor of methods with the same name in StateManagementStrategy, for which implementations are now required to use the visit API (UIComponent#visitTree), e.g. as-in the simplified example:

  1. viewRoot.visitTree(visitContext, new VisitCallback() {
  2.     public VisitResult visit(VisitContext context, UIComponent target) {       
  3.         if (!target.isTransient()) {          
  4.             savedState.put(
  5.                 target.getClientId(context.getFacesContext()),
  6.                 target.saveState(context.getFacesContext())
  7.             );
  8.         }        
  9.         return ACCEPT;
  10.     }
  11. });

(This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)

Commits for this feature have been done on 22/dec/11.


All component types in metadata activate full lifecycle (spec issue 762)

JSF 2.0 added the concept of a metadata section in a view. This special section has two properties; its content can be read without constructing the entire view, and on a non-postback (non-faces, e.g. an initial GET request) components residing in this section can do something before the view is being rendered. Before JSF 2.0 this was not possible; on an initial GET request to a view only the lifecycle phase RENDER_RESPONSE was executed.

There was however one thorny issue, and that’s that the spec asked for checking for the presence of UIViewParameters (<f:viewParam>) as a precondition for executing lifecycle phases before RENDER_RESPONSE. In practice this meant a dummy <f:viewParam> had to be added in order for other kind of components to do anything before the view is rendered.

In JSF 2.2 such dummy isn’t needed anymore and there’s simply a check for a metadata section with components inside it.

To support this a new method has been added to javax.faces.view.ViewMetadata:

public static boolean hasMetadata(UIViewRoot root)

This will return true if there’s metadata for the given view, and false otherwise.

Commits for this feature have been done between 08/jun/11 and 31/jan/13 the associated issue has been marked as resolved.


Input fields can be updated with AJAX after validation error (spec issue 1129)

A particular nasty issue in JSF 2.0 (and before) is that it’s not possible to update any input fields with AJAX after a validation error has occurred.

Consider the following use case:

There’s a form on screen with an input field for name. Users can either type in the name directly, or press a button and choose a name from a dialog. After the user makes a selection in the dialog, the input field for name is updated with that value via AJAX.

So far so good.

But, if the user types in a name directly and a validation error happens because of that, the dialog is suddenly unable to put a new (valid) value in the input field.

This is because of a rule in JSF that input components (EditableValueHolders) are not allowed to pull new values in from the model to which they are bound after a validation error has occurred. The only way to put a new value into them is by requiring the user to manually enter something. This is however totally unintuitive and breaks many use cases.

The issue has been known for some time as has been documented as early as 2007. Users provided various cleaning solutions in forums. The issue also frequently came up on stackoverflow.

In response to this, libraries such as OmniFaces implemented a reusable solution for this problem. When a little later PrimeFaces also implemented a solution, it became clear something standardized was needed.

Çağatay Çivici, the lead developer of PrimeFaces (who is also a JSF EG member), therefor contributed the specification of a standard way to reset those input fields.

The primary result of this specification for page authors is the addition of a new attribute to the <f:ajax> tag; resetValue. Setting this to true will reset all components that are to be re-rendered, e.g. the components of which the id is given in the render attribute. Note that the official VDL doc says:

This will cause resetValue() to be called on any EditableValueHolder instances encountered as a result of this ajax transaction.

Intuitively this may not be entirely clear, as another set of instances that are involved with the AJAX transaction are those that are specified in the execute attribute. But in this case “instances encountered as a result…” thus means those specified in the render attribute, or from the server’s point of view the IDs returned by javax.faces.context.PartialViewContext.getRenderIds().

Example:

<h:commandButton value="DoStuff" action="#{someBean.someAction}">
    <f:ajax render="field1 field2" resetValues="true" />
</h:commandButton>

Then there’s also a mechanism for use with non-AJAX request; <f:resetValues>. This is a tag handler that can be nested inside “action components” (javax.faces.component.ActionSource instances), and that installs an ActionListener on its parent component that resets all components that are given in its render attribute. In effect it’s thus a kind of specialized action listener tag.

Example:

<h:commandButton value="DoMoreStuff">
    <f:resetValues render="field1 field2" />
</h:commandButton>

This may look odd at first since the entire purpose of resetting components was to update them via AJAX, and this resets after a non-AJAX request. However, it means that by using this “action listener” components are never in the non-updatable state to begin with, which may be preferable in some situations. Care should be taken that the render attribute DOES NOT accept the typical ‘macros’ like @form and @all.

As for the Java API, JSF 2.0 did already add the resetValue convenience method to EditableValueHolder, but has now also added a public convenience method to reset all components from a given collections of Ids in the entire tree:

javax.faces.component.UIViewRoot.resetValues(FacesContext, Collection<String>)

This method mirrors exactly what <f:ajax resetValues=”true” /> and <f:resetValues> do.

Commits for this feature have been done between 06/Nov/12 and 06/Dec/12 and the associated issue has been marked as resolved.

XML configuration


Case insensitivity for state saving method (spec issue 1010)

In JSF one can set whether state is saved on the server or on the client via the context parameter javax.faces.STATE_SAVING_METHOD in web.xml which can be set to “server” or “client”. The values had to be used exactly as given. Using “Client” or “CLIENT” would actually result in server state saving being used. As of JSF 2.2 the value is made case insensitive, so those preferring to use “Client” can now do so.

Commits for this feature have been done on 26/may/11 and the associated issue has been marked as resolved.


Standardized server state serialization (spec issue 1127)

Every time a view is rendered in JSF that uses state, this state is stored somewhere. In case state is stored on the client all objects and their primitives that make up this state are serialized and as an (encrypted) base64 encoded string sent to the client. In case state is stored on the server only a view state Id is sent to the client.

This view state Id points to a capture of the state stored in server memory. Making this “capture” can be done by just storing pointers (a shallow copy), or by doing the same as is done for the state on the client and serializing everything (making a deep copy).

Both these methods have their advantages and disadvantages. A shallow copy is much cheaper in terms of both CPU and memory utilization and allows you to inject EJB beans in @ViewScoped beans, but if fields of an object are changed in one ‘copy’, they change in all other copies. This last effect could lead to unexpected results. Serialization on its turn requires much more CPU and memory and doesn’t work with EJB injection (of which the proxies aren’t serializable), but it does allow for a true history of state.

The two major (and practically only) JSF implementations Mojarra and Myfaces both offered proprietary context parameters to set the desired behavior: com.sun.faces.serializeServerState for Mojarra and org.apache.myfaces.SERIALIZE_STATE_IN_SESSION for MyFaces. A major problem that portable applications are facing in JSF 2.1 and before is that Mojarra and MyFaces have their defaults reversed. Mojarra defaults to not serializing, while Myfaces defaults to serializing.

In JSF 2.2 this proprietary context parameter will be standardized via the new javax.faces.SERIALIZE_SERVER_STATE. However, JSF 2.2 still does not mandate what the default should be, but does state that serializing for state on server is optional, carefully hinting at not serializing being a good default. Mojarra at least will continue to have not serializing as the default.

Example of setting server state to use serialization:

<context-param>
    <param-name>javax.faces.SERIALIZE_SERVER_STATE</param-name>
    <param-value>true</param-value>
</context-param>

Commits for this feature have been done on 22/aug/12.


Configurable resource directory (spec issue 996)

In JSF 2.0 a special directory was introduced called the “resources directory”. This directory is a directory called resources in the root of a web archive and is to load the definition of composite components by convention. Aligning with the entire easy-of-use and no-configuration theme, there is nothing that needs to be configured for this. A developer can create a sub-directory in this resources directory which will become a namespace, and all elements in this sub-directory will be automatically recognized as composite components.

This entire mechanism is by itself a great example of the ease of use improvements that JSF 2.0 brought. In the older thinking, a developer would have to put an XML file somewhere, then register the XML file itself, then register in this XML file what the namespace was and where the definitions of component could be found. Not difficult, but rather tedious indeed.

So the concept of this auto-registering resources directory was a great step forward. Unfortunately, there is one small problem. The resources directory is an ordinary directory in the web root, meaning its world readable by default. This on its turn means the source code of composite components is world-readable if there’s no .xhtml to .xhtml mapping, or an attempt can be made to execute them directly as-if they were top-level pages. Both effects are undesirable as any source level artifact should be totally inaccessible to random clients.

JSF 2.2 will therefor introduce a context parameter called javax.faces.WEBAPP_RESOURCES_DIRECTORY that will allow a developer to choose a different directory. At best this is a compromise, since the defaults are still unsafe and these defaults are what the majority of developers will (initially) use. For new JSF applications, this will thus be more or less a required configuration parameter, which sadly goes against the no-config theme that brought us the resources directory in the first place.

Example of setting the resources directory to a non-world-readable directory:

<context-param>
    <param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
    <param-value>WEB-INF/resources</param-value>
</context-param>

Further reading:

  • Commits for this feature have been done on 20/mar/12.

    Standards compliance


    Unique ids and fixed name attribute for view state field (spec issue 220)

    For keeping track of state associated with forms, JSF implementations write a hidden input field in each form that’s used on a page.

    In JSF 1.2 this field was standardized and the specification demanded that both the id and name attributes were set to javax.faces.ViewState*.

    The rule however breaks “W3C XHTML 1.0 Transitional” and above standards compliance. Namely, per that standard the id attribute should be globally unique within a document. If the JSF spec mandates that it should always have a fixed value, it clearly can’t be unique if multiple forms are being used on a single page.

    Very early on, Mojarra introduced the parameter com.sun.faces.enableViewStateIdRendering, that when set to false simply omitted rendering the id attribute (thus leaving only the name present). Since this is an implementation specific parameter, not all third party libraries necessarily take its effects into account.

    Therefor from JSF 2.2 on only the name attribute is mandated to have the fixed name. JSF 2.2 compatible libraries wanting to do something with the viewstate now have to work with a name-spaced Id (like other ‘normal’ elements in the markup rendered by JSF), or do lookups based on the name name attribute if they want to continue using the fixed name.

    For now, Mojarra has removed the com.sun.faces.enableViewStateIdRendering parameter completely, so setting this explicitly to true will not bring the id attribute back.

    Commits for this feature have been done on 30/jan/12 and the associated issue had initially been marked as resolved, but was re-opened on 06/feb/12 because of complexities involving the notorious troublesome Portlets environment and a new commit was done on 09/feb/12. See the EG discussion for more details.

    *In addition the spec strongly recommends, though doesn’t enforce, that the value of this input field is difficult to predict in order to prevent cross site scripting attacks, see Cross Site Request Forgery protection for more details.


    Allowing id attribute on all elements for HTML5 content (spec issue 1100)

    Contrary to previous HTML standards, it’s allowed in HTML5 to use an id attribute for every kind of element.

    In JSF 2.1 and earlier, the id attribute on the head was not being rendered. In case HTML5 content is being served, JSF 2.2 will render the id attribute for this element. For previous versions of HTML this is not done. Additionally, the VDL docs were updated and now state that for the body element an id attribute is rendered as well (this already happened, but the docs didn’t mention it).

    Incidentally, a nice tidbit of information that we learned from this issue is that in JSF 2.2, HTML5 will be the default.

    Commits for this feature have been done between 14/may/12 and the associated issue has been marked as resolved.

    Cancelled features

    Components


    Component modification management (spec issue 984)

    In JSF, components can introduce variables in a kind of “component scope” or “component context”. The var attribute of iterating components like UIData or UIRepeat is a well known example of this. E.g.

    1. <ui:repeat value="#{someBean.items}" var="item">
    2.     <!-- item is in scope here -->
    3. </ui:repeat>
    4.  
    5. <!-- item no longer in scope -->

    In JSF 2.1 and before there is no explicit API that components can use to manage this context. This is potentially troublesome for components that need to do a full tree visit within a clean context.

    To assist with managing this context, JSF 2.2 would have introduced a ComponentModificationManager that could have been obtained via a call to FacesContext#getComponentModificationManager

    Although details remained scarce throughout the development (only an API draft had been committed), it’s possible the API might have been used by components as follows:

    1. public boolean visitTree(VisitContext visitContext, VisitCallback callback) {
    2.     ComponentModificationManager manager = visitContext.getFacesContext().getComponentModificationManager();
    3.  
    4.     ComponentModification modifications = manager.suspend(visitContext.getFacesContext());
    5.     try {
    6.         return super.visitTree(visitContext, callback);
    7.     } finally {
    8.         manager.resume(visitContext.getFacesContext(), modifications);
    9.     }
    10. }

    (This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)

    The person who originally requested this feature for one reason or the other wasn’t able to give feedback about it when it was committed. When the feedback could finally be given, there was no time left, and the feature was asked to be removed and will likely be re-attempted for JSF 2.3.

    Commits for this feature have been done on 16/dec/11, but it was reverted on 14/mar/13.


    Component modification management (spec issue 763)

  • Injection in all JSF artifacts
  • The original goal of JSF 2.2 was to have support for injection into all JSF artifacts. This had at one point indeed been implemented, and could be used with most snapshot versions of JSF 2.2 that were published during its dev cycle.

    Unfortunately, at the very last moment it was discovered that there are some intricate subtleties involved with injecting into a UIComponent and its attached artifacts converter, validator and behavior.

    Following that discovery, injection into those artifacts was pulled at the very last moment (the proposed final draft still mentions them).


    That’s it for now! I’ll periodically update this page to cover additional JSF 2.2 items.

    Arjan Tijms

    Fetching arbitrary object graphs in JPA 2

    25 April 2012

    In Java EE, JPA (Java Persistence API) is used to store and retrieve graphs of objects. This works by specifying relations between objects via annotations (or optionally XML). Hand over the root of an object graph to the entity manager and it will persist it. Ask the entity manager for an object with a given Id and you’ll get the graph back.

    This is all fine and well, but how in this model do we control which branches of the graph are retrieved and to which depth branches should be followed?

    The primary mechanism to control this with is the eager/lazy mechanism. Mark a relation as eager and JPA will fetch it upfront, mark it as lazy and it will dynamically fetch it when the relation is traversed. In practice, both approaches have their cons and pros. Mark everything eager and you’ll risk pulling in the entire DB for every little bit of data that you need. Mark everything lazy, and you’ll not only have to keep the persistence context around (which by itself can be troublesome), but you also risk running into the 1 + N query problem (1 base query is fired, and then an unknown amount of N queries when iterating over its relations). If fetching 1000 items in one query took approximately as long as fetching 1 item per query and firing 1000 queries, then this wouldn’t be a problem. Unfortunately, for a relational database this is not the case, not even when using heaps of memory and tons of fast SSDs in RAID.

    There are various ways to overcome this. For instance there are proprietary mechanisms for setting the batch size, so not 1000 queries are fired but 10. We could also assume that all entities relating to those 1000 items are all in the (JPA) cache. Then 1000 fetches of 1 entity are indeed about as costly as 1 fetch of 1000 entities, but this is a dangerous assumption. Assume wrong and you might bring down your DB.

    The fundamental problem however is that eager/lazy are static properties of the entity model. In practice, the part of the graph that you want often depends on the use case. For a master overview of all Users in a system, you’d probably want a rather shallow graph, but for the detail view of a particular User you most likely need a somewhat deeper one.

    Again, there are various solutions for this. One is to write individual JPQL queries for each use case. This certainly works, but the number of queries can grow rapidly out of hand this way (allUsersWithAddress, allUsersWithAddressAndFriends, allUsersWithAddressAndFriendsWithAddress , …). Another solution that addresses exactly this problem are the fetch profiles that were introduced in Hibernate 3.5. As can be seen in the official documentation, this solution is not particularly JPA friendly. You need access to the native Hibernate session, which is possible, but not pretty. One way or the other, fetch profiles are Hibernate specific.

    In this posting I would like to present an alternative solution. It feels a little like fetch profiles, but the graph to be fetched can be specified dynamically and it uses the JPA API only. It works by using the criteria API to programmatically add one or more JOIN FETCH clauses to a query. Unfortunately JPA does not yet have the capabilities to turn a JPQL query into a Criteria query, so either the query must already be a Criteria or it should be a simple find. The following code demonstrates the latter case:

    @Stateless
    public class SomeDAO {
     
        @PersistenceContext
        private EntityManager entityManager;
     
        public T findWithDepth(Class<T> type, Object id, String... fetchRelations) {
            CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(type);
            Root<T> root = criteriaQuery.from(type);
     
            for (String relation : fetchRelations) {
                FetchParent<T, T> fetch = root;
                for (String pathSegment : relation.split(quote("."))) {
                    fetch = fetch.fetch(pathSegment, JoinType.LEFT);
                }
            }
     
            criteriaQuery.where(criteriaBuilder.equal(root.get("id"), id));
     
            return getSingleOrNoneResult(entityManager.createQuery(criteriaQuery));
        }
     
        private <T> T getSingleOrNoneResult(TypedQuery<T> query) {        
            query.setMaxResults(1);
            List<T> result = query.getResultList();
            if (result.isEmpty()) {
                return null;
            }
     
            return result.get(0);
        }
    }

    The findWithDepth method can now be called with one or more path expressions, where each path is just a chain of properties separated by a dot (like in expression language). E.g.:

    User user = someDao.findWithDepth(
        User.class, 15, "addresses", "friends.addresses"
    );

    The above line would fetch the user with “id” 15, and pre-fetches the addresses associated with that user, as well as the friends and their addresses. (Note that the @Id field is hardcoded to be called “id” here. A more fancy implementation could query the object for it)

    This solution, though handy, is however not perfect. While all JPA vendors support fetching multiple relations of one level deep (addresses and friends in the example above), not all of them support fetching chained relations (friends.addresses in the example above). Specifically for Hibernate care should be taken to avoid fetching so-called “multiple bags” (sets and @OrderColumn are a typical solution). Of course it’s always wise to avoid creating a huge Cartesian product, which is unfortunately one low-level effect of the underlying relational DB you have to be aware of, even when purely dealing with object graphs.

    Despite the problems I outlined with this approach above, I hope it’s still useful to someone. Thanks go to my co-workers Jan Beernink and Hongqin Chen for coming up with the original idea respectively refining it.

    Arjan Tijms

    Hibernate’s “Pure native scalar queries are not yet supported”

    22 April 2012

    In JPA one can define JPQL queries as well as native queries. Each of those can return either an Entity or one or more scalar values. Queries can be created on demand at run-time from a String, or at start-up time from an annotation (or corresponding XML variant see Where to put named queries in JPA?).

    Of all those combinations, curiously Hibernate has never supported named native queries returning a scalar result, including insert, update and delete queries which all don’t return a result set, but merely the number of rows affected.

    It’s a curious case, since Hibernate does support scalar returns in non-native named queries (thus a scalar return and named queries is not the problem), and it does support scalar returns in dynamically created native queries (thus scalar returns in native queries are not the problem either).

    An example of this specific combination:

    <named-native-query name="SomeName">
        <query>
            INSERT INTO
                foo
            SELECT
                *
            FROM
                bar
        </query>
    </named-native-query>

    If you do try to startup with such a query, Hibernate will throw an exception with the notorious message:

    Pure native scalar queries are not yet supported

    Extra peculiar is that this has been reported as a bug nearly 6 years(!) ago (see HHH-4412). In that timespan the advances in IT have been huge, but apparently not big enough to be able to fix this particular bug. “Not yet” certainly is a relative term in Hibernate’s world.

    A quick look at Hibernate’s source-code reveals that the problem is within org.hibernate.cfg.annotations.QueryBinder, more specifically the bindNativeQuery method. It has the following outline:

    public static void bindNativeQuery(org.hibernate.annotations.NamedNativeQuery queryAnn, Mappings mappings){
        if (BinderHelper.isEmptyAnnotationValue(queryAnn.name())) {
            throw new AnnotationException("A named query must have a name when used in class or package level");
        }
        NamedSQLQueryDefinition query;
        String resultSetMapping = queryAnn.resultSetMapping();
        if (!BinderHelper.isEmptyAnnotationValue(resultSetMapping)) {
            query = new NamedSQLQueryDefinition (
                // ...
            );
        }
        else if (!void.class.equals(queryAnn.resultClass())) {        
            // FIXME should be done in a second pass due to entity name?
            final NativeSQLQueryRootReturn entityQueryReturn =
                new NativeSQLQueryRootReturn (
                    // ...
                );
        }
        else {
            throw new NotYetImplementedException( "Pure native scalar queries are not yet supported" );
        }
    }

    Apparently, the NamedNativeQuery annotation (or corresponding XML version), should either have a non-empty resultset mapping, or a result class that’s something other than void.

    So, isn’t a workaround for this problem perhaps to just provide a resultset mapping, even though we’re not doing a select query? To test this, I tried the following:

    <named-native-query name="SomeName" result-set-mapping="dummy">
        <query>
            INSERT INTO
                foo
            SELECT
                *
            FROM
                bar
        </query>
    </named-native-query>
     
    <sql-result-set-mapping name="dummy">
        <column-result name="bla" />
    </sql-result-set-mapping>

    And lo and behold, this actually works. Hibernate starts up and adds the query to its named query repository, and when subsequently executing the query there is no exception and the insert happens correctly.

    Looking at the Hibernate code again it looks like this shouldn’t be that impossible to fix. It’s almost as if the original programmer just went out for lunch while working on that code fragment, temporarily put the exception there, and then after lunch completely forgot about it.

    Until this has been fixed in Hibernate itself, the result-set-mapping workaround might be useful.

    Arjan Tijms

    Sample CRUD application with JSF and RichFaces

    30 March 2012

    During my thesis project I will be using JavaServer Faces. Therefore it is important I get familiar with the framework. To get familiar I made a small CRUD (Create Read Update Delete) application. It is a simple application that makes it possible to keep track of users. It consists of a user list, a page to add/edit users and a page to delete a user.

    The code

    The research project will focus on when it is beneficial to use client-side scripting instead of/complementary to server side programming. To get up to speed a small CRUD application has been made without the use of client-side scripting and the same CRUD application was adapted to use client-side scripting by using RichFaces. The client-side scripting was added to the editing form to allow validating the form, without the need of making requests to the server.

    The structure of the source project is as follows:

    • backing
      • Index.java – Backing for index.xhtml
      • UserDelete.java – Backing for UserDelete.xhtml
      • UserEdit.java – Backing for UserEdit.xhtml
    • constraints
      • Email.java –  Validation annotation for fields. Fields with this annotation are validated to be a proper email address.
      • EmailConstraintValidator.java – Performs the validation for email addresses.
    • ejb
      • UserDAO.java – Data Access Object for users.
    • entities
      • User.java – Bean object for a user. The fields of this object are annotated with validators.
      • UserConvertor.java – Converts a userId to a user.
    • util
      • Messages.java – Utility object that helps with sending messages between pages.

    The following JSF pages are in the project:

    • index.xhtml – Page with a list with all users
    • user_delete.xhtml – Page used to confirm whether a user should be validated
    • user_edit.xhtml – Page used for adding and editing users

    While creating this application, I tried as much as possible to adhere to best practices. For examples, to go from the master (list) view to the detail (edit) view a GET request is used with the user id as parameter. The user is modified via POST and there’s a redirect and GET back to the master view (PRG pattern).

    Both applications make use of Enterprise Java Beans, Bean Validation and Java Persistence API. EJB is used to inject persistence in the managed beans. Bean validation is used to ensure the data is consistent with the business rules.

    In the RichFaces version user_edit.xhtml is updated to have client-side validations. Only the email address cannot be validated on the client. For that field is Ajax used.

    The code of the project has been uploaded to Google Code so it can viewed by everyone. The code without the use of client-side scripting is put in the default branch and the code with client-side scripting is put in the RichFaces branch.

    Demo

    The compiled applications have been uploaded to OpenShift. It makes showing your work to the public very easy. This is a free cloud platform which runs a JBoss server. The projects can be directly uploaded from Eclipse to the OpenShift server. The live demo can be viewed here.

    To upload your project yourself to OpenShift it is first required to make an account at OpenShift. Then register your public key at OpenShift. When you have the OpenShift plug-in installed in Eclipse you can add the OpenShift server to the server view in Eclipse. From there you can get the default project from OpenShift. This project is only used to send the war files to server, not to hold the code. By adding the JSF project to the OpenShift server it automatically places the war file in the OpenShift project during a publish. By pushing the OpenShift project to the server using GIT, the application is put in the cloud and is ready to use. The detailed process to upload to OpenShift from Eclipse is available here.

    So wrapping up, I’ve made a small project to get familiar with the code, I have uploaded the code to Google Code and I’ve put the application OpenShift.

    Mark van der Tol

    Automatically setting the label of a component in JSF 2

    22 March 2012

    In JSF input components have a label attribute that is typically used in (error) messages to let the user know about which component a message is. E.g.

    Name: a value is required here.

    If the label attribute isn’t used, JSF will show a generated Id instead that is nearly always completely incomprehensible to users. So, this label is something you definitely want to use.

    Of course, if the label is going to be used in the error message to identify said component, it should also be rendered on screen somewhere so the user knows which component has that label. For this JSF has the separate <h:outputLabel> component, which is typically but not necessarily placed right before the input component it labels.

    The problem

    The thing is though that this label component should nearly always have the exact same value as the label attribute of the component it labels, e.g.

    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{myBean.username}" label="Username" required="true" />

    There’s a duplication here that feels rather unnecessary (it feels even worse when the label comes from a somewhat longer expression, which is typical for I18N). My co-worker Bauke identified this problem quite some time ago.

    Finding a solution

    It appears though that an implementation that automatically sets the label attribute of the target “for” component to the value of the outputLabel isn’t that difficult, although there are a couple of things to keep in mind.

    For starters, a component in JSF doesn’t directly have something akin to an @PostConstruct method in which you can set up things. There are tag handlers and meta rules in which you can set up attributes, but when they execute not all components have to exist yet.

    Luckily, we always have the plain old constructor and since JSF 2 components can register themselves for system events. This gets us into a method where we can setup things.

    Additionally, we have to be aware of state. System event listeners are luckily not stateful, so perfectly suited for tasks that need to be setup once (Phase listeners are stateful though, and will ‘come back’ after every postback). Attributes of a component are by default stateful, so we only need to set those once, not at every postback. Finally, the API distinguishes between deferred expressions (value expressions) and literals. If we want to support dynamic labels and only want to setup the wiring once, it’s important to take this distinction into account.

    Finally, when searching for the target “for” component we can take advantage of the fact that typically this component will be close by. Compared to the regular search on the view root, the well-known “relative-up/down” search algorithm is probably more efficient here. This algorithm will start the search in the first naming container that is the parent of the component from where we start our search in the component tree. This will work its way up until there are no more parents, and if the component then still isn’t found (practically this is rare if the component indeed exists), then a downward sweep will be done starting from the root.

    So, this all comes down to the following piece of code then (slightly abbreviated):

    @FacesComponent(OutputLabel.COMPONENT_TYPE)
    public class OutputLabel extends HtmlOutputLabel implements SystemEventListener {
     
        public OutputLabel() {
            if (!isPostback()) {
                getViewRoot().subscribeToViewEvent(PreRenderViewEvent.class, this);
            }
        }
     
        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
     
            String forValue = (String) getAttributes().get("for");
            if (!isEmpty(forValue)) {
                UIComponent forComponent = findComponentRelatively(this, forValue);
     
                if (getOptionalLabel(forComponent) == null) {
                    ValueExpression valueExpression = getValueExpression("value");
                    if (valueExpression != null) {
                        forComponent.setValueExpression("label", valueExpression);
                    } else {                    
                        forComponent.getAttributes().put("label", getValue());
                    }
                }
            }
        }
    }

    After creating a tag for this component, the following can now be used on a Facelet:

    <o:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{myBean.username}" required="true" />

    If a form is posted with this in it and no value is entered, JSF will respond with something like:

    Username: Validation Error: Value is required.

    An implementation of this is readily available in the new OmniFaces library, from where you can find the documentation and the full source code. There’s also a live demo available.

    Arjan Tijms

    How to run the Mojarra automated tests

    26 February 2012

    The JSF RI implementation Mojarra comes with a very extensive test suite. There are some instructions available on how to actually run those tests, such as the entry “How do I run the automated tests?” in the official FAQ and the document “TESTING_A_BUILD.txt” at the root of the Mojarra repository.

    Both sets of instructions are not overly detailed and they don’t seem to be entirely up to date either. For instance, the entry in the FAQ states the following:

    This target will cause the JSF API and implementation to be deployed to the GlassFish server
    that is downloaded as part of the build process

    This however doesn’t happen for testing JSF 2.x anymore (there was code that downloaded GlassFish V2 for JSF 1.x, but this can’t be used for 2.x).

    The TESTING_A_BUILD.txt document mentions:

    Be sure to install glassfish with a password on admin
    make sure that password.txt is found in container.home

    But how do we install glassfish with a password? If GlassFish is distributed as a .zip there is no install script, and the version with an installer also doesn’t offer any option to specify a password. I guess that there once was an option in the installer for this but it seems to have been removed since. Additionally, the password.txt in container.home appears to be not entirely correct.

    After some trial & error I got the tests to run (more or less, read below). For my own reference and in the hope it’ll be useful to someone, I’m jotting the instructions down here.

    Download GlassFish 3.1.1 from http://glassfish.java.net/downloads/3.1.1-final.html (I choose the zip archive).

    Unzip GlassFish somewhere; we’ll call the resulting directory [glassfish home] below. This will look something like:

    glassfish3 <--- [glassfish home]
        bin
        glassfish
        javadb
        mq
        pkg
    

    The tests assume a password is being used, so we're now going to set one:

    cd into [glassfish home]/bin and execute the following command:

    ./asadmin start-domain domain1

    On Mac OS X this may take a minute due to a reverse DNS lookup being attempted (there's a fix).

    After GlassFish has started, execute the following command:

    ./asadmin change-admin-password

    Press enter twice and enter adminadmin for the password as below:

    Enter admin user name [default: admin]> (press enter)
    Enter admin password> (press enter)
    Enter new admin password> (enter adminadmin)
    Enter new admin password again> (enter adminadmin)
    Command change-admin-password executed successfully.
    

    Most commands in the test suite that interact with GlassFish use a password file (--passwordfile option), but for some reason not all. For those an additional .asadminpass file is required to be in the home directory of the user as whom the tests are run. This can be created via the following command:

    ./asadmin login

    Press enter once and again enter adminadmin for the password as below:

    Enter admin user name [default: admin]> (press enter)
    Enter admin password> (enter adminadmin)
    Login information relevant to admin user name [admin]
    for host [localhost] and admin port [4848] stored at
    [/home/youruser/.asadminpass] successfully.
    Make sure that this file remains protected.
    Information stored in this file will be used by
    asadmin commands to manage the associated domain.
    Command login executed successfully.
    

    You can shutdown the container now using the following command:

    ./asadmin stop-domain domain1

    Mojarra has recently gone from being distributed as 2 jars to 1 jar. The Glassfish 3.1.1 that you downloaded still uses 2 jars. In the past the test code patched GlassFish, but probably in anticipation of GlassFish shipping with 1 jar this no longer happens. In the mean time, it's necessary to patch GlassFish yourself.

    In [glassfish home]/glassfish/domains/domain1/config/default-web.xml and [glassfish home]/glassfish/lib/templates/default-web.xml remove the entries jsf-api.jar and jsf-impl.jar and replace them by a single javax.faces.jar. I.e.:

    Replace

    jsf-api.jar
    jsp-impl.jar
    jsf-impl.jar

    With

    javax.faces.jar
    jsp-impl.jar

    Make a backup of the resulting [glassfish home] directory now. The test suite occasionally corrupts GlassFish and you often need to restore a fresh version. In fact, to have reliable test results you might opt to use a fresh GlassFish for every test run.

    The Mojarra tests depend a lot on Maven, so if haven't installed Maven then install it now. E.g. on Ubuntu:

    sudo apt-get install maven2

    (This is not needed on OS X, since it already comes with Maven)

    Now we're ready to check out the Mojarra source code. I'll assume SVN knowledge here.

    Check out: https://svn.java.net/svn/mojarra~svn/trunk

    We'll rever to the directory where you checked out those sources as [source home] below. E.g.

     
    Mojarra <--- [source home]
        jsf-api
        jsf-ri
        jsf-tools
        [...]
        password.txt
        build.properties.glassfish
        [...]
    

    Prior to starting the tests, a few files need to be customized. First, put the following in [source home]/password.txt:

    AS_ADMIN_PASSWORD=adminadmin

    Now copy [source home]/build.properties.glassfish to [source home]/build.properties.

    Set the following entries in the newly created [source home]/build.properties:

    jsf.build.home=[source home]
    container.name=glassfishV3.1_no_cluster
    container.home=[glassfish home]/glassfish
    halt.on.failure=no

    For example:

    jsf.build.home=/home/myuser/Mojarra
    container.name=glassfishV3.1_no_cluster
    container.home=/home/myuser/glassfish3/glassfish
    halt.on.failure=no

    If you haven't already set this up, define JAVA_HOME. This is typically not needed on OS X, but is needed on a e.g. a fresh Ubuntu installation. If you don't do this, Maven will let you think it can't find an artifact from a remote repository, while in fact it couldn't compile some source files.

    Additionally set ANT_OPTS to allow more memory to be used. E.g. in Ubuntu (bash):

    export JAVA_HOME=/opt/jdk1.6.0_31/
    export PATH=/opt/jdk1.6.0_31/bin:$PATH
    export ANT_OPTS='-Xms512m -Xmx786m -XX:MaxPermSize=786m'

    Now we're *almost* ready to run the build and the test. Unfortunately the Mojarra trunk seems to have a circular dependency between the clean and main targets at the moment. To break this dependency, comment out two ant tasks in [source home]/jsf-test/build.xml (as of writing on line 119):

    1. <!-- ensure the api jar is deployed to the local maven repo -->
    2. <!-- COMMENT THIS OUT:
    3. <ant dir="${api.dir}" target="main">
    4.     <property name="skip.javadoc.jar"  value="true" />
    5. </ant>
    6. <ant dir="${api.dir}" target="mvn.deploy.snapshot.local">
    7.     <property name="skip.javadoc.jar"  value="true" />
    8. </ant>
    9. -->

    Now cd to [source home] and execute the following command:

    ant clean main

    If you're lucky, the build will succeed without failures. Now undo the commenting in [source home]/jsf-test/build.xml, so the file will look like below again:

    1. <!-- ensure the api jar is deployed to the local maven repo -->
    2. <ant dir="${api.dir}" target="main">
    3.     <property name="skip.javadoc.jar"  value="true" />
    4. </ant>
    5. <ant dir="${api.dir}" target="mvn.deploy.snapshot.local">
    6.     <property name="skip.javadoc.jar"  value="true" />
    7. </ant>

    cd to [source home] and execute the following command again:

    ant clean main

    If everything still went correctly, we can now run the tests. There are quite a lot of tests and running the suite till completion took 31 minutes on my 2.93Ghz i7 iMac and 48 minutes on an Ubuntu 11.10 installation running inside VirtualBox 4.1.8 on the same machine. The tests generate a whopping 1.6MB of logging, so if you want to scan it later you might want to divert it to a file:

    ant test.with.container.refresh > ~/test.txt

    If you want to follow the proceedings of the test run, you can use e.g. tail in a second terminal:

    tail -f ~/test.txt

    In my case, whatever I tried and however clean my system was, some tests were always failing. E.g. testFormOmittedTrinidad, TestLifecycleImpl, ScrumToysTestCase, AdminGuiTestCase.

    Occasionally some tests don't honor the halt.on.failure=no setting that we did in the build.properties files. If this happens comment out the offending test. If you want to test your own changes to Mojarra, make sure to run the test suite a couple of times to get an idea of what tests are already failing for your system. I personally tried a couple of different machines and environments but none of them was able to pass all tests.

    Finally, some extra information for Eclipse users. The tests can be run via Eclipse as well. If you initially check out the Mojarra project in Eclipse, you'll see a lot of errors. There are Eclipse project files, but they are obviously outdated (this is fixable, but I'll leave that for a next article). When working with Eclipse, you'll use Eclipse for editing the source code and for navigation (call references, navigate into and such). Even if the Eclipse project files are corrected, the actual compiler output will be thrown away.

    To start the ant build via Eclipse, do the following:

    Right click on build.xml, click Run As -> Ant Build… Go to the JRE tab and under VM arguments add the following:

    -Xms512m -Xmx786m -XX:MaxPermSize=786m

    On the same dialog go to the Environment tab and set JAVA_HOME to your installed JDK, e.g.
    variable JAVA_HOME, Value /opt/jdk1.6.0_31 (this is not specifically needed on OS X or if you've already set JAVA_HOME globally for your system).

    Go to the Targets tab and deselect everything. Then first select clean and then main. The target execution order in the bottom left corner of the dialog should list them in the right order. Having followed the instructions outlined above for command line ant (commenting out entries in [source home]/jsf-test/build.xml) now click Run. Follow the same instructions for restoring the file and again click Run. Finally, deselect both targets and select the test.with.container.refresh target.

    Arjan Tijms

    Eclipse 3.7 SR2 released!

    24 February 2012

    With once again an amazing release accuracy, today Eclipse Indigo Service Release 2, aka Eclipse 3.7.2 has been released.

    In the core packages, some 89 bugs have been fixed.

    Important projects that are part of the release train were updated as well, for instance WTP was updated from 3.3.1 to 3.3.2 (a fact not mentioned yet on the WTP homepage, but it can be found here). WTP 3.3.2 fixes no less than 112 bugs.

    My personal favorite bug that has been fixed is 100% CPU for long time in ASTUtils.createCompilationUnit. Just having a fairly innocent page in your workspace would completely hang the CPU for minutes or more.

    For the next version of Eclipse we’re supposedly going to get to see the 4.x line by default on the downloads page, so this might well be the last 3.x version that’s prominently featured on said page. Time will tell of course.

    For now, Eclipse 3.7.2 can thus be downloaded from the usual place at http://eclipse.org/downloads and the general release notes can be found at http://www.eclipse.org/eclipse/development/readme_eclipse_3.7.2.html

    Arjan Tijms

    best counter