Using grails projects in Hudson

Being an agile software development company we use a continuous integration (CI) server like Hudson.
For our grails projects we wrote a simple ant target -call-grails to call the batch or the shell scripts:

    <condition property="grails" value="${grails.home}/bin/grails.bat">
        <os family="windows"/>
    </condition>
    <property name="grails" value="${grails.home}/bin/grails"/>

    <target name="-call-grails">
		<chmod file="${grails}" perm="u+x"/>
        <exec dir="${basedir}" executable="${grails}" failonerror="true">
            <arg value="${grails.task}"/>
            <arg value="${grails.file.path}"/>
            <env key="GRAILS_HOME" value="${grails.home}"/>
        </exec>
    </target>

Calling it is as easy as calling any ant target:

  <target name="war" description="--> Creates a WAR of a Grails application">
        <antcall target="-call-grails">
            <param name="grails.task" value="war"/>
            <param name="grails.file.path" value="${target.directory}/${artifact.name}"/>
        </antcall>
    </target>

One pitfall exists though, if your target takes no argument(s) after the task you have to use a different call:

	<target name="-call-grails-without-filepath">
		<chmod file="${grails}" perm="u+x"/>
        <exec dir="${basedir}" executable="${grails}" failonerror="true">
            <arg value="${grails.task}"/>
            <env key="GRAILS_HOME" value="${grails.home}"/>
        </exec>
    </target>

Using Flying Saucer PDF offline

Flying saucer is a nice tool for quick PDF generation from a (X)HTML page. Everything worked fine when we tested it at home but when we had a demo at a client’s site, no PDF could be generated. The problem was caused by a little snippet in the header of the HTML:

<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The DTD declaration! So we took a look at the flying saucer issue database and found someone who had the same problem.
But another solution is even simpler:
Xerces has a default setting which tells the parser to load external dtds.
Turning this off solved our offline problems:

  DocumentBuilderFactory builderFactory =
    DocumentBuilderFactory.newInstance();
  builderFactory.setFeature(
    "http://apache.org/xml/features/nonvalidating/load-external-dtd",
    false);

When as Set is not what you want

When you want to filter out duplicates in a list in groovy you normally do something like:

        def list = [2, 1, 2, 3]
        def filtered = list as Set
        assertEquals([1, 2, 3], filtered as List)

This kicks out all duplicates in a one-liner. But what if the list is sorted (e.g. in reverseOrder)?

        def list = [3, 2, 2, 1]
        def filtered = list as Set
        assertEquals([3, 2, 1], filtered as List) // this fails!

One solution would be to use a small closure:

        def list = [3, 2, 2, 1]
        def filteredList = []
        list.each {
            if (!filteredList.contains(it)) {
                filteredList << it
            }
        }
        assertEquals([3, 2, 1], filteredList)

This closures preserves the order and filters out the duplicates.

Multipage Flows with Grails Part One – The traditional way

When you are developing web apps once in a while you need a flow of multiple pages just like a shopping cart at Amazon. Since there are different ways to implement such a multipage flow in Grails I thought of recording our experiences here.

The scenario

We model the process of submission of a proposal for different kinds of technologies. First you have to decide which type of proposal (once, long-term, in house) you want to submit. On the second page you give your personal infos and a general description of your intentions using the chosen technologies. Here you also choose the technologies you want. This has an impact on the following page which holds the information for the different technologies. Last but not least you save the proposal and show it to the user so he can see what data he entered. This flow could look like this:

-> chooseType -> enterGeneralInfo -> enterSpecificInfo -> save -> show

In each of the steps we need different parts of the full proposal. So we decided to use Command Objects in Grails. These objects are filled and are validated automatically by Grails. To use them you just have to delare them as parameter to the closure:

def enterSpecificInfo = {GeneralPartCommand cmd ->
  if (!cmd.hasErrors()) {
    Proposal proposal = new Proposal(cmd.properties)
    proposal.specificInfos = determineSpecificInfos(proposal.technologies)
    render(view: 'enterSpecificInfo', model: ['proposal': proposal])
  }
  else {
    render(view: 'enterGeneralInfo', model: ['proposal': cmd])
  }
}

You can then bind the properties in the command object to the proposal itself. The GeneralPartCommand has the properties and constraints which are needed for the general information of the proposal. This imposes a violation of the DRY (Don’t Repeat Yourself) principle as the properties and the constraints are duplicated in the proposal and the command object but more about this in another post.

How to collect all the data needed

Since you can only and possibly want to save the proposal at the end of the flow when it is complete you have to track the information entered in the previous steps. Here hidden form fields come in handy. These have to store the information of all previous steps taken so far. This can be a burden to do by hand and is a place where bugs arise.

How to go from one state to another

To transition from one state to the next you just validate the command object (or the proposal in the final state) to see if all data required is there. If you have no errors you render the view of the next state. When something is missing you just re-render the current view:

if (!cmd.hasErrors()) {
  Proposal proposal = new Proposal(cmd.properties)
  proposal.specificInfos = determineSpecificInfos(proposal.technologies)
  render(view: 'enterSpecificInfo', model: ['proposal': proposal])
}
else {
  render(view: 'enterGeneralInfo', model: ['proposal': cmd])
}

The errors section in the view takes the errors and prints them out. The forms in the views then use the next state for the action parameter.

Summary

An advantage of this solution is you can use it without any add-ons or plugins. Also the URLs are simple and clean. You can use the back button and jump to almost every page in the flow without doing any harm. Almost – the transition which saves the proposal causes the same proposal to be saved again. This duplicates the proposal because the only key is the internal id which is set in the save action.
Besides the DRY violation sketched above another problem arises from the fact that the logic of the states and the transitions are scattered between several controller actions and the action parameters in the forms. Also you have to remember to track every data in hidden form fields.
In a future post we take a look at how Spring (WebFlow) solves some of these problems and also introduces others.

Hibernate Pitfalls

Nehmen wir an wir hätten eine Klasse Activity, die u.a. ein Attribut Duration hat, das die Dauer in Sekunden als Quantity Second angibt. Wenn man nun die Mapping Datei folgendermassen gestaltet:

<hibernate-mapping default-lazy="false">
<class name="Activity" table="activity">
...
<property name="duration" column="duration" type="double" not-null="true"/>
</class>
</hibernate-mapping>

scheint alles ok zu sein. Hibernate findet sein Attribut und seine Setter und Getter. Also los! Das grosse Stirnrunzeln kommt dann beim Starten des Programms (bzw beim Speichern der Activities in die Datenbank):

java.sql.SQLException: Attempt to insert null into a non-nullable column:
column: DURATION table: ACTIVITY in statement [...]

Hmmm… also erstmal den Debugger anschmeissen und der sagt einem duration ist nicht null, ist doch alles ok, aber warum meckert dann hibernate?

Die Lösung ist ganz einfach: hibernate kann den Rückgabewert der getter Methode nicht als double interpretieren und nimmt daher null an, anstelle zu melden, dass die getter Methode den falschen Rückgabetyp hat. Sinnvolle Fehlermeldungen könnten manchmal die Fehlersuche wirklich verkürzen…