Archive for September, 2011

Try-with-resources in JDK7 without scoped declarations

26 September 2011

A handy new feature in JDK7 is the try-with-resources statement. This statement is meant to eliminate a lot of the boilerplate code required for managing InputStreams and OutputStreams. Say for example, that I would want to copy the contents of an InputStream to an OutputStream. This would require the following code only to manage the in- and output stream:

InputStream in = createInputStream();
try {
   OutputStream out = createOutputStream();
   try {
      /* Copy data here */
   } finally {
      try {
      } catch(IOException e) {
         //Prevent this exception from suppressing actual exception
} finally {
   try {
   } catch(IOException e) {
      //Prevent this exception from suppressing actual exception

Using the new try-with-resources statement, the above code can be rewritten as the following:

try (InputStream in = createInputStream(); OutputStream out = 
      createOutputStream()) {
   /* Copy data here */

The InputStream and OutputStream are automatically closed at the end of the try-with-resources block. If an exception is thrown during the main block and then again during the closing of one (or both) of the streams, the exception on the close operation is added to the original exception as a suppressed exception, so no exceptions are swallowed silently anymore. The try-with-resources blocks are also not limited to be used for in- and output streams, but can be used on any object that implements the AutoCloseable interface.

There is one minor disadvantage to the try-with-resource statement, it is required to define the variable that refers to the object to be closed within the brackets after the try. For example, if you have a method that receives an InputStream as a parameter, the Java compiler would not allow you to do this:

public void readData(InputStream in) {
   try(in) {
      int input;
      while((input = >=0) {
         //Use input here

The above code would produce a compiler error as no variable has been defined between the brackets of the try-with-resources statement. I would propose the following workaround for this situation:

public void readData(InputStream in) {
   try(InputStream autoCloseableInputStream = in) {
      int input;
      while((input = >=0) {
         //Use input here


This code does compile and the stream is automatically closed at the end of the try block. Since the autoCloseableInputStream and in variables refer to the exact same object, it is not necessary to actually use the autoCloseableInputStream variable in the code. Using a name like autoCloseableInputStream makes it clear that this variable is only defined in order to be able to use the try-with-resources statement.

Single class pure Java JSF application

18 September 2011

In my previous blog entry, Authoring JSF pages in pure Java, it was explained how to set up a JSF based web application using nothing but pure Java. No XML based templating (Facelets) was required and the view was build purely programmatically.

I got one remark though that the example code did used expression language (EL) to patch some of the parts together. Although EL is really convenient, as it provides a way to point to a (nested) method on a scoped object, it’s not regular type-safe Java.

Luckily, the Java component API of JSF doesn’t only use EL based ValueExpressions and MethodExpressions, but also allows regular Java types to be set as listeners and values. This is demonstrated in the code below. While at it, I’ve done away with the separate backing bean for this example and let the same class that defines the page handle the action event.

The result is a pure Java, xml-less, EL-less, config-less, single class JSF application [phew]:

  1. @ManagedBean
  2. public class Intro implements Page, ActionListener {
  4.     private HtmlOutputText message;
  6.     @Override
  7.     public void buildView(FacesContext context, UIViewRoot root) throws IOException {
  9.         List<UIComponent> rootChildren = root.getChildren();
  11.         UIOutput output = new UIOutput();
  12.         output.setValue("&lt;html xmlns="">");                
  13.         rootChildren.add(output);
  15.         HtmlBody body = new HtmlBody();
  16.         rootChildren.add(body);
  18.         HtmlForm form = new HtmlForm();
  19.         body.getChildren().add(form);
  21.         message = new HtmlOutputText();
  22.         form.getChildren().add(message);
  24.         HtmlCommandButton actionButton = new HtmlCommandButton();
  25.         actionButton.addActionListener(this);
  26.         actionButton.setValue("Do action");
  27.         form.getChildren().add(actionButton);
  29.         output = new UIOutput();
  30.         output.setValue("&lt;/html>");
  31.         rootChildren.add(output);
  32.     }
  34.     @Override
  35.     public void processAction(ActionEvent event) throws AbortProcessingException {
  36.         message.setValue("hello, world");
  37.     }    
  38. }

To run this on Glassfish, only this class and the small (8,980 bytes) javavdl.jar library are required:

After requesting localhost:8080/demo/intro.jsf, a single button will be shown. The message “hello, world” will be displayed when this button is clicked.

Interesting to note perhaps is that the components themselves only exist for the duration of the request and after every post-back the component tree will be re-created. State set on the components during buildView will be marked as the so-called initial state and will typically not be taken into account by JSF’s state saving mechanism. Since only the HtmlCommandButton in the example code references the Page instance after this buildView it will effectively have request scope.

The java based vdl is still rather simple, so it’s still just a proof of concept. I’ve planned some enhancements that I’ll work on soon if time permits (e.g. perhaps support for scopes other than request scope without using EL). Stay tuned!

Arjan Tijms

Authoring JSF pages in pure Java

12 September 2011

JSF is well known as a server side web framework to build a web application’s UI with the help of components. For the overwhelming majority of users those components are represented by the tags one uses to compose a page, be it via JSP or Facelets.

The following is a typical example of a page authored with Facelets:

  1. <html xmlns="" xmlns:h="">    
  2.     <h:body>   
  3.        #{backingBean.hello}   
  4.         <h:form>      
  5.             <h:inputText value="#{}" />                    
  6.             <h:commandButton value="Say Hello" action="#{backingBean.sayHello}" />
  7.         </h:form>        
  8.     </h:body>
  9. </html>

This may give the impression that JSF components *are* the tags shown above, and thus that JSF is necessarily about tags and XML. That is however not true.

JSF has always had a clear separation between the technology used to author pages (the so-called view description language) and the actual API to create components and compose them together into a component tree. This API is a Java API that even in the very first days of JSF had no knowledge whatsoever about JSP or tags. The strict separation allowed alternative view declaration languages like Facelets to be created and eventually be promoted to the default VDL, without needing to change the underlying JSF core framework.

Other view declaration languages have been created as well. One notable example is a concept based on JavaFX, in which a JSF page would look like this:

  1. var x = 0;
  2. var bindVal = "Hello";
  4. function init(){
  5.    FxPage{
  6.       content : [
  7.          FxForm{
  8.                 content : [
  9.                     FxOutputLabel{
  10.                         value : bind bindVal
  11.                     },
  12.                     FxCommandButton{
  13.                         value : "Button"
  14.                         actionListener : function() : String{
  15.                             bindVal = "Hello {x++}";
  16.                             return null;
  17.                         }
  18.                     }
  19.                 ]
  20.             }
  21.         ]
  22.     }
  23. }

See: JavaFX as JSF VDL (View Description Language)?

As it appears, the API to create components and compose a component tree is pretty accessible by itself. It could theoretically be used directly to author pages instead of solely being used as an API for VDL implementations. The problem however is that it’s not clear how to actually start doing that. One trick is to use dynamic tree manipulation and add components in a PreRenderView event on an otherwise empty page.

Another way is to create a minimal VDL implementation. As a proof of concept, that’s what I did. With such a thing it’s possible to create a JSF application completely in Java. No Facelets or JSP files, and following Minimal 3-tier Java EE app, without any XML config, no web.xml or faces-config.xml is required either. There doesn’t even have to be a WEB-INF or WebContent directory in the project.

The following shows a JSF page being defined in pure Java:

  1. public class Intro implements Page {
  3.     @Override
  4.     public void buildView(FacesContext context, UIViewRoot root) throws IOException {
  6.         ELContext elContext = context.getELContext();
  7.         ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
  9.         List<UIComponent> rootChildren = root.getChildren();
  11.         UIOutput output = new UIOutput();
  12.         output.setValue("&lt;html xmlns="">");                
  13.         rootChildren.add(output);
  15.         HtmlBody body = new HtmlBody();
  16.         rootChildren.add(body);
  18.         HtmlForm form = new HtmlForm();
  19.         body.getChildren().add(form);
  21.         ValueExpression messageProperty = expressionFactory.createValueExpression(elContext, "#{myBean.message}", String.class);
  23.         HtmlOutputText message = new HtmlOutputText();
  24.         message.setValueExpression("value", messageProperty);
  25.         form.getChildren().add(message);
  27.         MethodExpression helloMethod = expressionFactory.createMethodExpression(elContext, "#{myBean.action}", Void.class, new Class[0]);
  29.         HtmlCommandButton hiCommand = new HtmlCommandButton();
  30.         hiCommand.setActionExpression(helloMethod);
  31.         hiCommand.setValue("Say hello");
  32.         form.getChildren().add(hiCommand);
  34.         MethodExpression navigateMethod = expressionFactory.createMethodExpression(elContext, "#{myBean.navigate}", String.class, new Class[0]);
  36.         HtmlCommandButton navigateCommand = new HtmlCommandButton();
  37.         navigateCommand.setActionExpression(navigateMethod);
  38.         navigateCommand.setValue("Do navigation");
  39.         form.getChildren().add(navigateCommand);
  41.         output = new UIOutput();
  42.         output.setValue("&lt;/html>");
  43.         rootChildren.add(output);
  44.     }    
  45. }

This will be rendered as follows:

The code shows how components are created simply by using the new operator and a tree is created by just inserting the child components in the children collections of their parents. Action listeners are registered on action source components by setting a method expression that points to the scoped backing bean “myBean”, which is defined as follows:

  1. @ManagedBean
  2. public class MyBean {
  4.     private String message;
  6.     public void action() {
  7.         message = "Hi!";
  8.     }
  10.     public String navigate() {
  11.         return redirectOutcome(OtherPage.class);
  12.     }
  14.     public String getMessage() {
  15.         return message;
  16.     }    
  17. }

Note that the bean features a navigation method that uses the class type of the target page to determine the navigation outcome.

By putting stuff in base classes or utility methods, page implementations can be simplified. For instance, the following shows the page where the user is navigated to after pushing the button on the first page. It inherits from a base class that already defines the html and outer body part, and only implements the body content:

  1. public class OtherPage extends BodyTemplate {
  3.     @Override
  4.     public void buildBody(FacesContext context, HtmlBody body) {    
  5.         HtmlOutputText output = new HtmlOutputText();
  6.         output.setValue("This is a new page.");
  7.         body.getChildren().add(output);        
  8.     }
  9. }

This page is rather simple and is rendered as:

As shown by the screen shots, if the project is called javavdl the initial page can be requested by requesting http://localhost/javavdl/intro.jsf, which is fully implemented using the class given above. After clicking the navigate button, the user will be redirected to http://localhost/javavdl/test/otherPage.jsf, which is fully implemented by For this simple proof of concept, classes implementing pages have to reside in the package resources.javavdl.pages. Sub-packages in that package become paths relative to the deployment root of the application. E.g. /test/otherPage.jsf is implemented by resources.javavdl.pages.test.OtherPage.

The following is a picture of my workspace, showing that there is absolutely not a single xml file:

If this were used for real, the “src” package would probably be in a jar, and the application would consist of nothing more than this jar and the four classes shown in the demo package.

The current setup is really just a proof of concept. I personally think a declarative approach like Facelets is actually clearer, although some people actually do seem to like a purely programmatic approach to building a UI.

If people want to tinker with this, I’ve shared my Eclipse project where I implemented this here: (it currently depends on the Glassfish WTP server adapter being installed).

Arjan Tijms

Simple Java based JSF custom component

4 September 2011

Even though in JSF components have always been a central thing, actually creating them required a ridiculous amount of tedious work in JSF 1.x. Not only did you had to create the actual component, it also required you to:

  • Register the component in an XML file
  • Create a tag handler class, where you referenced the component by its registered name
  • Register the tag in .tld file.

You were also more or less supposed to create a separate renderer class, and although this actually has always been optionally, people seemed to interpret it as being a required part as well. Although none of this was really difficult, the sheer amount of work prevented everyone but component library builders from creating components.

JSF 2.0 addressed all of these concerns by introducing composite components, where you are able to create first-class components just by putting some existing components and/or markup in a Facelets file. For the majority of use cases where application builders needed their own customized components, this is actually all that’s needed.

For some cases however a Java based component is still a more natural fit. Although not as simple to create as composite components, creating Java based custom components has actually been simplified as well. Of the steps outlined above, only a registration for the tag is still required. The actual component can be rather simple:


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

Unfortunately, a registration in an XML file is still required in JSF 2.1 to use this as a tag (note, that in JSF 2.2 this isn’t required anymore):


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <facelet-taglib 
  3.     xmlns=""
  4.     xmlns:xsi=""
  5.     xsi:schemaLocation=""
  6.     version="2.0">
  8.     <namespace></namespace>
  10.     <tag>
  11.         <tag-name>customComponent</tag-name>
  12. 	<component>
  13.             <component-type>components.CustomComponent</component-type>
  14.         </component>
  15.     </tag>
  17. </facelet-taglib>

The custom component can now be used on a Facelet as follows:


  1. <html xmlns=""
  2.     xmlns:h=""
  3.     xmlns:test=""
  4. >
  5.     <h:body>   		
  6.         <test:customComponent value="test"/>        
  7.     </h:body>
  8. </html>

As shown, creating a Java based JSF component that simply renders something is not that complicated. Although composite components should generally be preferred, Java based ones can come in handy and it’s an important extra tool.

It’s a shame perhaps the XML registration is still needed in JSF 2.1, but luckily there was a feature request in the JSF spec JIRA that made it largely unnecessary for JSF 2.2. Hopefully the actual Java code can also be further simplified if the family and component name would be defaulted in a future JSF version (the last e.g. to the fully qualified class name).

Arjan Tijms

css.php best counter