JSF 2: ProjectStage only half-baked

In JSF2 there are tons of new and interesting features. Some are big changes and some are really neat small additional things, like the ProjectStage Enum.

Especially for tool-vendors (and component libraries) this is useful to specify the “runtime”. (Development vs. Production vs. SystemTest vs. UnitTest). One example could be the Trinidad Skinning facility. Currently by default we do compression of the generated CSS selectors, but that is a PITA for debugging (even with firebug). However, there is a way around it. Specify the following in your web.xml:

<context-param>
<param-name>
org.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION
  </param-name>
<param-value>true</param-value>

</context-param>

Fine.

Now… with the upcoming JSF2 ProjectStage Enum, we could easily change the Skinning facility to leverage the different possible values. Production, for instance, means compression is on, Development means there is no compression, etc.

However… this means the developer always has to change the WEB.XML (or do some JNDI setup); same is true for Trinidad’s skinning today ;-) The big problem with the ProjectStage is that the JSF spec only talks about web.xml and JNDI for doing the setup configuration. It would be very cool if the specification would be changed to actually allow system props, since that makes our life easier!

One could easily launch a Trinidad application and on the commandline you specify the actual “project stage”:

mvn jetty:run -Djavax.faces.PROJECT_STAGE=Development

That would be great!

UPDATE:

I filed a bug against the spec for this topic.

Client-side validation done wrong (with Spring-Faces)

In JSF there is no concept of client-side conversion and validation. All is done on the server, which means you notice some extra round trips in case there is something “wrong”. Eventually JSF 2.0 will change that…

In the meantime there are some frameworks that provide help. One of them is Apache MyFaces Trinidad.

The basic idea of Apache Trinidad client conversion and validation is that it works on the client in a very similar way to how it works on the server, except the language on the client is javascript instead of java. There are javascript converter objects that support the methods getAsString() and getAsObject(). A TrConverter can throw a TrConverterException. There are javascript validator objects that support the validate() method. A TrValidator can throw a TrValidatorException. Read here for more details on how to decorate your standard converter/validator to enable the client-side representation.

Another possibility is using Spring-Faces, which I think is quite popular since a lot of folks use the WebFlow stuff. But I don’t really like their way of *enabling* client-side conversion / validation.

Their user guide gives some interesting examples on how to use the bits, like:

<sf:clientTextValidator required="true">
  <h:inputText id="creditCardName"
  value="#{booking.creditCardName}" required="true"/>
</sf:clientTextValidator>

What this does is basically enabling client-side “required” validation.

Cool, but noticed it? You add things to your declarative view, that you eventually don’t really want…

  • you handle client-validation as a special case (some extra tag for that used here)
  • you wrap the “validator” around the actual component (JSF usually nests real validators, but this is “just” a dojo wrapper component (to include some fancy dojo-based JS)
  • you are redundant (required true on the client AND on the server (see the <h:inputText />
  • you can (by accident) disable server-side validation, by just saying required:true on the “validator” tag. Think about a man-in-the-middle tool (not tested this)

Another example I saw here:

<sf:clientTextValidator required="true" regExp="[0-9]{16}"
invalidMessage="A 16-digit credit card number is required.">
  <h:inputText id="creditCard" value="#{booking.creditCard}" required="true"/>
</sf:clientTextValidator>

This does validate the entered value to match a regular expression. In Trinidad, this would be coded like this:

<tr:inputText id="creditCard" value="#{booking.creditCard}" required="true"/>
<tr:validateRegExp pattern="[0-9]{16}" messageDetailNoMatch="A 16-digit credit card number is required."/>
</tr:inputText>

This is the way JSF users know how to compose the views. Also, a very minor thing… In Trinidad all attributes to change the messages start with message. In Spring-Faces not. They are called like “promptMessage” or “rangeMessage”. Of course pretty minor, but useful for users that type the XHTML/JSPX in a tool and don’t know the exact naming… you just need to remember messageXzy… ;-)

Of course, there is no standard way of doing things like conversion/validation on the client, which explains why there are different solutions. In Trinidad we actually render the components and we are also in control of the extra validators. So, we can do some stuff inside of our library for things like:

<inputText required="true" ... />

I really hope to see some client-side conversion / validation in JSF 2.0; Looking at Spring-Faces (compared to Trinidad) show that a common solution is really needed. And this solution – I am pretty sure – will follow the natural JSF way, like Trinidad does today.

REST and JSF ?

JavaServer Faces is a great framework to build rich web applications, as shown in the following screenshot:

As you see, the web application in this screenshot is more an APPLICATION, than web… A pretty rich user interfaces, which was composed straightforward by using JSF strength, its declarative (markup-free) view:

<af:document title="..." ...>
  ...
  <af:tree />
  ...
</af:document>

REST – the web architecture…

The term REST was defined by Roy Fielding and it describes an architecture for web apps which use standard HTTP methods like GET, POST, PUT and DELETE to request and manipulate data. REST is (for me) a key component in WOA (web oriented architecture). A simple table to explain the mapping of the HTTP methods to the data manipulation:

HTTP GET -> /api/messages == get a list of messages
HTTP POST -> /api/messages == create a new message
HTTP PUT -> /api/messages/1 == modify message #1

As you can see the URLs in a RESTful (web) application are easy to bookmark…

JSF and REST

JSF is a UI-centric web framework and REST is more available on the (web)service layer. Sure, on a HTTP GET /something you also get some result (HTML, JSON etc)… The RESTful URIs somewhat map directly to the data in the backend (e.g. the message #1). JSF is more about UI, meaning to present different datasources, via its components. In JSF you mostly use the POST HTTP method, when clicking on a link/button to create, update, delete or query some data. The HTTP POST (for a link/button command) can also mean that you may navigate to a different web page… So, this basically means the POST in JSF has definitely a different meaning than in REST…

One of the facts that some complain about in JSF is that the URLs aren’t bookmarkable. Usually JSF-based web apps are more application than web, as said before (ever tried to do a bookmark in a Word document on page 7?). However there are some ways, to workaround the bookmark issue in JSF (like using Servlet-Filters for pretty URLs)…

Bookmarks != REST

The bookmark factor I am not discussing here. If one would like to use REST-style for providing APIs for the applications, he is not only interested in bookmarkable URLs. Adding REST means that your front-controller supports PUT, DELETE and POST (to create things) on the service layer. Every HTTP client (like a browser or the curl tool) could use this API to deal with your application…

How to combine REST with JSF?

Good question. I am not really sure. The JSF 2.0 website says the EG eventually plans to support REST via the JSR 311 effort, but the latest draft of the specification doesn’t contain any hint regarding REST. So, how to integrate the REST-style with JSF? One possibility could be to integrate an adapter to support REST. This adapter would understand POST, GET, PUT and DELETE in a REST-way (and therefore different from the POST/GET in JSF). This adapter could be done with a different Servlet/Filter, that doesn’t map to the FacesServlet at all. The JSF lifecycle is also not needed to do REST, since this is more a service layer, than an actually GUI layer… The adapter could have access to other bits of the JSF framework, like the managed bean facility or the Unified Expression Language, and the adapter could (or should) be based on JSR-311.

I took a quick look at Ruby on Rails and they map the REST/HTTP methods to special methods in their controller (like show, destroy or create). Something like this could be done with a JSF ViewController (like available in Orchestra or Shale). Also Struts2 uses a similar approach to integrate REST. The JBoss Seam Framework already supports 311-based REST today. What they do is basically allowing the JBoss JSR-311 implementation to communicate with Seams DI mechanism:

@Name("customerResource")
@Path("/customer")
public class MyCustomerResource
{
  @In
  CustomerDAO customerDAO;
  @GET
  @Path("/{customerId}")
  @ProduceMime("text/plain")
  public String getCustomer(@PathParam("customerId") int id)
  {
    return customerDAO.find(id).getName();
  }
}

In the above sample the @Name and @In are Seam Annotations; the other ones are defined by JSR-311.

At the end this means there is no really close integration for supporting “real” REST. An extra adapter, like used in Struts2, Seam or Rails makes sense. That would also mean that there is no need to re-write the declarative JSF-view to treat the REST scenario as a special case (in those views). The REST integration actually happens on a different layer, but with an adapter as briefly discussed here, there would be still an integration to some core concepts of JSF, like its managed bean facility.

EJB lite ? I think I need help…

A co-worker pointed me to this article of a EJB 3.1 series. There is something in called “EJB lite”.

Reading the section on EJB lite, I think I need some help… First of all, they strip out some of the (heavy) things in EJB, like remote session beans and MDBs (message driven beans). What remains is “injection, persistence management, stateless session beans and declarative transactions”, sorta…

This sounds to me, that they try to include a *lightweight* EJB version (of course, the term lightweight is actually overused these days). But… isn’t that the goal of WebBeans as well ? To introduce a “lightweight” component model (by unifying EJB/JSF) ?

So, the article says we may see lightweight implementations of this (like in Spring). I now think also about Guice ?!? Or wait, Guice was pretty much driving WebBeans (the DI part)… So, would/should Spring and Guice have to implement WebBeans and/or EJB lite ?

Looks like some questions to solve for the next Java EE umbrella specification… I think I am a bit confused by this :-)

ADF Faces 11g release, demos and autoPPR (ajax)

You eventually noticed that the JDev 11g (including ADF Faces) is now out for production. Also, we updated the ADF Faces demo website:

http://jdevadf.oracle.com/adf-richclient-demo/

One of the cool, new features is something we call “auto PPR”. Here is the demo. In it you see an outputText component, which is bound to an implementation of the ActiveDataModel interface. In this example the model implementation changes every second its data.

Now the model fires data change events and the component will be added to the PPR target. Next time when a new (ajax) request comes in, the updated data will be sent to client automatically. This feature dose not require application developer to configure PPR trigger and target! So you get these updates for free!

Nice Charts with Trinidad

Apache MyFaces Trinidad provides a lot of cool JSF components; a really nice one it the chart component. It offers several possibilities to visualize your structured data. Like this pie chart:

To actual provide such a nice looking chart graphic, you just need to implement an abstract class, provided by Trinidad’s API. This may sound a bit complicated… but actually it is straightforward:

public class CustomerDevelopment extends ChartModel
{
  public List<String> getGroupLabels()
  {
    List<String> years = new ArrayList<String>();
    years.add("2006");
    years.add("2007");
    years.add("2008");
    years.add("2008");
    return years;
  }
  public List<String> getSeriesLabels()
  {
    List<String> products = new ArrayList<String>();
    products.add("Product A");
    products.add("Product B");
    return products;
  }
  public List<List<Double>> getYValues()
  {
    List<List<Double>> chartValues = new ArrayList<List<Double>>();
    // iterate over the groups (years...)
    for(int i = 0; i < getGroupLabels().size(); i++)
    {
      List<Double> numbers = new ArrayList<Double>();

      // now, just read the series, per group (product/year)
      for(int j = 0; j < getSeriesLabels().size(); j++)
      {
        // yes... some random stuff here, in the demo ...
        numbers.add(10000 * Math.random());
      }
      chartValues.add(numbers);
    }
    return chartValues;
  }

}

Actually, the only “tricky” part is the getYValues() method. Here you do two loops to get the correct data. When you are already in the business of providing chart data… this is somewhat familiar.

The JSPX (or Facelet) is also very simple:

<tr:chart value="#{bean.chartModel}" type="pie" />

There are actually more than 10 different types of rendering the chart, take a look at the tagdoc.

Have fun!

identity checks with JavaScript

Every now and than, somebody asks why I am sometimes using three equal signs (===) instead of two (==), when comparing values.

Simple answer is, that I am interested in the identity (type and value) instead of only the value.

Some code:


alert(2 == "2");
alert(2 === "2");

The first one returns TRUE, because the value is equal. But not their types (number vs. string), therefore the second return FALSE.

(sorta) real-time updates, with Trinidad

The technology to ensure (sorta) real-time updates on your web app is called, COMET. This is a giant hack, basically. There are three common ways to actually implement it. Polling, Long Polling and Continuous connection, by using the forever frame pattern/trick. All of them of certain issues:

  • Polling: efficient for rarely changing items, but potentially long latency
  • Long Polling: Latency is the amount of time needed to make a new connection (see Jean-Francois Arcand’s blog).  But this is inefficient for extremely fast (multiple times a minute) event rates and  it means a heavy thread load on servers where each request is a thread, non NIO servers (see Jean-Francois Arcand’s blog)
  • Continuous connection (aka HTTP Streaming): Technical issues (including proxy problems). But this approach has the lowest latency. It also has some issues on none NIO servers, as long polling.

That said… So there are (some cases) where polling is OK…

The good news is, that Trinidad actually supports polling out of the box, by its poll component. Specify a certain ping interval, to ask the server for an update… but keep in mind, the more you ping the server, the worse the client and server performance.

At Oracle we support the continuous connection as well, as part of ADF Faces 11g (Rich Client Framework).

Berlin

I am traveling to Berlin in October to give a talk at the Java User Group of Berlin. The topic will be “Advanced JSF” and I will cover a solid stack, useful to build your JSF-based applications.

Some topics:

  • Apache Trinidad
  • Facelets
  • Ajax Integration
  • JPA
  • Spring
  • Apache Orchestra

The talk in on a Friday – 17th – so come by if you are in Berlin (and interested ;-) ).

I am looking forward to that event. It is always worth to come to Berlin. For me the best city, at least in Germany.