Conditionally printing HTML tags in JSF Facelets

This took me a bit to figure out so I thought I’d post it.

Say you’re using JSF and want to conditionally print some HTML tags in your Facelet that could, technically speaking, result in non well-formed markup. You can’t really do it. Printing something like is illegal as it’ll complain about the < and > characters being in there. Using the tag doesn’t work either, even if you wrap the content in a CDATA element. Problem is that it’s preventing you from writing non well-formed markup in any which way.

One of the solutions is to force the rendering kit to not analyze the output for “well-formedness” by passing the HTML markup in a variable.

In your facelet.xhtml


<h:outputText escape="false"
              rendered="#{someCondition}"
              value="#{messages['lessThan'].concat('ul').concat(messages['greaterThan'])}"/>

In messages.properties

lessThan=<
greaterThan=>

What the hell is the cause of this NullPointerException?

It’s infinite deep!

nullpointerexception-cause

IntelliJ Hilarity

Note that this is a very lame post. IntelliJ IDEA is the greatest Java IDE in the world, his post does not “diss” it in any way, just pointing out something that was funny to me and only so because I’ve been at it for quite some time now.

I often have IntelliJ generate the equals() and hashCode() methods for me when programming @Entity beans. Here’s what it did for me:

equals

Makes sense, but notice how the last if statement is highlighted? That’s IntelliJ’s way of telling me that it can make things better which is a little weird because IntelliJ’s the guy that generated the code for me. Anyway, I see what the hint has to say:

hint

It’s saying that it can make some of these ifs redundant and sure enough once I take the hint the return clause is joined with last if like so:

first-hint

It’s all good but notice now that it now highlighted the previous if statement and if I accept it, it’ll continue doing the same thing over and over again. I’ll accept all the improvements it wants to make and I’ll finally end up with this method which is logically equivalent to what I showed you in the first picture:

final

The difference isn’t that great in an entity with three properties but you get the point about tertiary statements and IntelliJ”s love for them.

Writing Custom Facelet JSF Components

Writing Facelet JSF Components is NOT the same thing as writing custom JSP-based JSF Components. Once you get past that it turns out they’re not hard to write at all. There’s no mucking around with JSP tag libraries, TLD files and other such archaic nonsense.

You need to edit create/edit three files in total. Here’s an example of a Facelet JSF component that prints out a table row when it is nested around another UI component. For example, the component if used the following way:


<arse:tableRow>
    <h:inputText id="myId" label="My Label"/>
</arse:tableRow>

would print


<tr>
  <td>My Label</td>
  <td><input type="text" ..../></td>
</tr>

Simple, right? Here’s the three files you have to create/edit:

faces-config.xml

Make sure the following is present in your faces-config.xml:


    <component>
        <component-type>tableRow</component-type>
        <component-class>com.arsenalist.UITableRow</component-class>
    </component>

META-INF/mytag-taglib.xml

Create a file withe following contents under your META-INF folder:


<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">

<facelet-taglib>
    <namespace>http://www.arsenalist.com/jsf/util</namespace>
    <tag>
        <tag-name>tableRow</tag-name>
        <component>
            <component-type>tableRow</component-type>
            <renderer-type>tableRow.renderer</renderer-type>
        </component>
    </tag>
</facelet-taglib>

Note the namespace, that’s what you’ll need to refer in the Facelet before using the tag, e.g:


<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:arse="http://www.arsenalist.com/jsf/util"
      . . . 

UITableRow.java

Finally, create the actual component. Here’s an example of a component that wraps the child elements around a tr and a couple tds. We must override getRendersChildren() to return true because it is the component’s duty to render its children (since we’re wrapping it around stuff).


package com.arsenalist;

import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;

/**
 * This class renders a table row.  It must contain two controls, the label and control to render.
 * @author Zarar Siddiqi
 */
public class UITableRow extends UIOutput {

    public UITableRow() {
        setRendererType(null);
    }

    public boolean getRendersChildren() {
        return true;
    }

    public void encodeBegin(FacesContext facesContext) throws IOException {
        // We're rendering a table row
        facesContext.getResponseWriter().startElement("tr", null);
    }

    @Override
    public void encodeChildren(FacesContext facesContext) throws IOException {
        ResponseWriter writer = facesContext.getResponseWriter();

        UIComponent control = getChildren().get(0);

        writer.startElement("td", label);
        // Label goes inside td
        writer.startElement("label", label);
        writer.writeAttribute("for", control.getClientId(facesContext), null);

        writer.write((String) control.getAttributes().get("label"));
        writer.endElement("label");
        writer.endElement("td");

        // Div element goes in the second along with the control
        writer.startElement("td", control);
        control.encodeEnd(facesContext);
        writer.endElement("td");
    }

    @Override
    public void encodeEnd(FacesContext facesContext) throws IOException {
        ResponseWriter writer = facesContext.getResponseWriter();
        writer.endElement("tr");
    }

    @Override
    public String getFamily() {
        return COMPONENT_TYPE;
    }
}

And that’s that.

GMail Bug – Where are my two messages?

It says I have two messages, but where the hell are they?

gmail-bug-where-are-my-messages

Even the Firefox Google Notifier agrees with me:

If you’ve seen these messages, let me know:

firefox-agrees

JSF Seam Validation + Custom Messages + Annotations + Internationalization

Validation is one of the first things you test out when evaluating a web framework and its often one of the most time consuming to wrap your head around. In this post I’ll talk about three types of validation mechanisms present in JBoss’ Seam which will get you on your way towards validating web forms without too much pain:

I’m going to cover three cases:

  1. Validating required fields without using annotations
  2. Validating manually and displaying custom messages
  3. Validating fields using Hibernate annotations in Seam beans

We’ll also display messages using a simple resource bundle (java.util.ResourceBundle) which will allow us to internationalize our forms and messages. Let’s dive into the examples:

Validating required fields without using annotations

This is the most general case, you want to force the user to input something in your text fields and if they don’t, you want to display a message telling them just that.

Here’s a JSF form which asks for a username and password:


<h:messages/>
<h:form id="LoginForm">
    <table>
	<tr>
	    <td><h:outputText value="#{messages['login.username']}"/></td>
	    <td>
		<h:inputText required="true" value="#{user.username}" label="#{messages['login.username']}"/>
	    </td>
	</tr>
	<tr>
	    <td><h:outputText value="#{messages['login.password']}"/></td>
	    <td>
		<h:inputSecret required="true" value="#{user.password}" label="#{messages['login.password']}"/>
	    </td>
	</tr>
	<tr>
	    <td></td>
	    <td>
		<h:commandButton action="#{loginAction.login}"
				 value="#{messages['button.login']}"/>
	    </td>
	</tr>
    </table>
</h:form>

Specifying required=”true” is all you need to validate required fields. The matter of displaying messages is left to the <h:messages/> tag which iterates through the list of messages generated by the validation phase and displays them sequentially.

By default validation messages are displayed in a format that is not very intuitive, in order to change the format you must override a property in your messages.properties file located at the root of your classpath:

javax.faces.component.UIInput.REQUIRED={0} is a required field.

The placeholder is {0} is automatically filled by the label attribute of the <h:inputText> tag. So in the above case if login.username is defined to be “Username” in the resource bundle, the messages that will be printed will be: Username is a required field.

If validation passes, then the login() method on the bean referenced by loginAction will be called (as specified by the <h:commandButton> tag.

Validating manually and displaying custom messages

This is probably the most powerful way of validating user input – programmatically. Let’s face it, the built-in validators can only do so much, at some point you end up writing java code to validate input by checking it against a database or queue etc. Going back to the login example, say we need to check the values supplied by the user against a database and if they match, let them into the system and if they don’t, kick them back to the login page with a message. The login page does not change, let’s get to the LoginAction class:


@Name( "loginAction" )
public class LoginAction {

    @In
    private User user;

    @In(create=true)
    private FacesMessages facesMessages;

    public String login() {
        if (user.getUsername().equals( "Arsenalist" ) && user.getPassword().equals( "Raptors" )) {
            return "success";
        } else {
            facesMessages.addFromResourceBundle("login.failed");
            return "failure";
        }
    }
}

It’s very obvious what’s happening here. The injected instance of FacesMessages allows you to use its addFromResourceBundle() method to specify a message that will be displayed in the view resulting from returning “failure”. Just for completeness sakes, here’s the faces-config.xml navigation rule:


    <navigation-rule>
        <from-view-id>/pages/login.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/pages/home.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/pages/login.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

Validating fields using Hibernate annotations in Seam beans

The next step is to apply more complex validation without resorting to writing Java code and for that Seam relies on Hibernate’s validation framework. As an aside, this dependency is probably the most annoying thing about Seam at this point but it works well enough to look past.

Let’s say we need to force the value of username to be atleast 5 characters. In order to do this we need to annotate two things:

  1. The injected user variable in LoginAction so Seam knows to validate it
  2. The User objects properties to specify what to validate.
    1. Here’s the relevant piece in LoginAction.java:

      
      @Name( "loginAction" )
      public class LoginAction {
          @In @Valid
          private User user;
          public String login() {
              . . . .
          }
      

      Here’s the relevant piece in User.java:

      
      @Name( "user" )
      public class User {
      
          private String username;
          private String password;
      
          @Length(min=5, message= "#{messages['login.username.length']}" )
          public String getUsername() {
              return username;
          }
          . . . .
      

      Notice how we’re using a resource key inside an annotation to print the message. This will look for a resource bundle called messages and inside it for the login.username.length property to retrieve the message. You could alternately just write the message in plain old English inside the annotation but why would you want to when you can internationalize.

      The last thing we need to do is tell the JSF page that it will need validation (I think this is a somewhat redundant step since the bean is already annotated but nonetheless it is required). You must wrap the fields of the login form around the <s:validateAll> tag like so:

      
      <h:messages/>
      <h:form id="LoginForm">
          <s:validateAll>
                  . . . .
      	    <h:outputText value="#{messages['login.username']}"/></td>
                  . . . .
          </s:validateAll>
      </h:form>
      

      Note: Be sure to specify required=”true” for the fields you want to apply annotation validations to. Otherwise, you’ll see some very weird results such as only non-blank fields getting the annotation validations applied to while the blank fields get considered valid.

      Here’s a list of annotations that you can use to validate java beans:

      • @Length(min=, max=) Checks whether the string length matches the range
      • @Max(value=) Checks that the value is less than or equal to the max
      • @Min(value=) Checks that the value is greater than or equal to the min
      • @NotNull Checks that the value is not null
      • @Past For a date object, checks that the date is in the past
      • @Future For a date object, checks that the date is in the future
      • @Pattern(regex=”regexp”, flag=) For a string, checks that the string matches this pattern
      • @Range(min=, max=) Checks whether the value is between the min and the max
      • @Size(min=, max=) For collections, checks that the size is between the two
      • @AssertFalse Asserts that the evaluation of the method is false
      • @AssertTrue Asserts that the evaluation of the method is true
      • @Valid For a collection or a map, checks that all the objects they contain are valid
      • @Email Checks whether the string conforms to the email address specification

      That’s all there is to it.

Free Euro 2008 Pool Script

OK, I don’t contribute much to the software community but I’m feeling generous today.

Since I run this pool at my office and for some unknown and weird reasons the link is #1 on Google for Euro 2008 Office Pool, I figured I’d share the piece of code that runs that “system” with the public.

Its basically a PHP/MySQL app with a few tables that are self-explanatory (I hope). You just enter who picked what teams and players and then just update the results as they happen – watch the entrants rise and fall as each team wins, loses or ties. Its quite fun really, much better than doing cocaine. The PDF form that entrants fill out is part of the zip along with everything else you need, but here it is anyway if you want to take a look.

Download the ZIP file here. All you really need to do is dump the schema in a MySQL 5 database (maybe even 4 might work), change the database info in ez_sql.php file (just replace INSERT_HOST tags etc.) and you’re good to go.

If you do feel like joining the pool, send me your entry form and $16 through PayPal to zarars at gmail

Update: I’ve updated this post with an improved version of this software which includes sample data. Here’s the older version.

Worst Captcha Ever

I’m trying to download a file from the evil Rapidshare (who make you wait about 2 painful minutes before giving you the file) and just after the wait time is over, I get a Captcha looking like this:

WTF man? I mean, does it really need to be this hard? Are you telling me that it has come down to us hiding domestic animals in our captcha characters in order to hold off bots? Plus, there are only 3 “letters” in that image but its asking for four.

This is a sad day for the HCI crowd.

On an unrelated note, here’s my cat.

Performing a LEFT OUTER JOIN using JPQL and JPA

Haven’t made a tutorial-type post in a while so here’s an installment of documenting something that should be already documented. The problem at hand is a very common one: how do you do a LEFT OUTER JOIN on two tables (entities) when you’re using the Java Persistence API.

Let’s go with the sports theme and model basketball shoe sponsorship. An NBA player may or may not have a shoe deal, for example Lebron James has a shoe deal with Nike while Juan Dixon doesn’t. We have two tables and entities to work with: Player and ShoeCompany. Now the task at hand is to retrieve all information about all players. Given that many of them don’t have shoe deals we want to be careful of not ignoring them in our query, that’s where the OUTER JOIN kicks in. In other words, retrieve the set of entities where matching values in the join condition may be absent. Here’s what the entities and tables look like:


@Entity
@Table( name="nba_player" )
public class Player {

    @Id @Column
    private Long id;

    @Column
    private String name;

    @OneToOne
    @JoinColumn( name="shoecompany_id" )
    private ShoeCompany shoeCompany;

    // getters and setters
}

@Entity
@Table( name="shoe_company" )
public class ShoeCompany {

    @Id @Column
    private Long id;

    @Column
    private String name;

    // getters and setters
}

Here’s what the tables look like:

nba_player(id, name, shoecompany_id)
shoe_company(id, name)

Doing this query without an OUTER JOIN is also possible, it’s quite simple actually, we just add an additional WHERE clause where we check for the foreign key being NULL.


SELECT *
FROM nba_player p, shoe_company s
WHERE p.shoecompany_id = s.id or p.shoecompany_id IS NULL

The same SQL query using an OUTER JOIN would look like:


SELECT *
FROM nba_player p LEFT OUTER JOIN  shoe_company s
                                       ON (p.shoecompany_id = s.id)

To generate the OUTER JOIN query using JPQL, you’ll have to write this:


SELECT p FROM Player p LEFT JOIN p.shoeCompany sc

That’s it, now you’re free to use and abuse LEFT OUTER JOINs all you want. I’m using TopLink Essentials as the JPA implementation but that shouldn’t come into play. Grab the techy part of the blog’s feed.

IIS messes with the application lifecycle in a way Tomcat wouldn’t dare

How would you dig it if someone randomly restarted your application every few minutes or so for absolutely no reason? Would you be upset, angry or plain confused on why an application server would bother recycling an application at seemingly random intervals without being prompted. See, just like the Servlet specification defines the ServletContextListener interface, it’s .NET counterpart happens to be Global.asax which defines application lifecycle methods like Application_End, Application_Start and such. A pretty sensible idea when you look at the surface of things but what’s horribly, horribly wrong is that .NET applications shut themselves down every 20 minutes if they detect that no requests have been made to IIS. This is all done in the hopes of preserving IIS resources which makes me wonder just exactly how resource intensive running an IIS app really is.

Now think about this, this means that any context loading or application initialization that you do on startup might be happening a few times an hour just because traffic to your application might be slow. Any static variables that you declare get dumped, any kron processes you’re running get killed, database connection pools get emptied, application scope data is erased, worker threads are stopped, everything is gone! If you’re running a plain old website which doesn’t do much, this might be borderline acceptable, but if you perchance happen to do some medium to heavy initialization, you’re bound to run into big time trouble that will leave you scratching your head and adjusting your crotch. And no, it doesn’t matter what you change in Web.config, nothing can save you.

If this isn’t appalling enough, try checking out some of the work-arounds to this problem. If you’re running a kron job in your application, you’ll realize that you’ll be doing some serious work just to keep it running. One of the arguments you hear is that since it’s a kron job, it really doesn’t belong in a .NET application and that you should really be writing a windows service to do the job for you. Now that’s just plain see-through bullshit, you can’t suggest writing a desktop application and call running a kron job in a web application a bad design The .NET gurus also suggest simulating a call to the web server to keep your application alive, something like the following:


void Application_End(Object sender, EventArgs e) {
   WebRequest request = WebRequest.Create ("http://myapp.com/SomePage.aspx");
   HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
   log.Info("Status: " + response.StatusDescription);
   response.Close ();
}

So pretty much, resuscitate it just before it’s about to croak. Truly a pathetic, pathetic piece of code which only exists because of a deep flaw in .NET”s application lifecycle philosophy. Compare this with the old and sturdy ServletContextListener which wouldn’t have the cahones to call contextDestroyed() even if the app was running for 10 years straight.

Another similar problem in .NET is the tendency for threads to store data in the HttpContext.Current object (kinda like ThreadLocal in Java), except that HttpContext is dependent on the Request object actually existing. If the Request is gone away (which only make sense since it’s an atomic event), any variables tied to it are also gone. I never comprehended why simple static space isn’t used instead.

Now someone might argue that you might be able to tweak settings in Machine.config or go to IIS Manager and drill down to Application Pools (new in IIS 6) and change your DefaultAppPool properties to alter the behavior of worker processes, which might do the trick. But the problem is that the default behavior of ALL IIS hosting companies is to leave this crucial setting at it’s default value and the worst part is that it can’t be altered at an application level but only in IIS. Something which just flat out sucks.