Monthly Archives: February 2010

A Tomcat gotcha

Servlet filters. Straightforward, right? A request comes in, goes through each filter in the chain, hits the servlet and then the response goes the other way. Sort of. What could possibly go wrong?

Not much…unless you throw error handling into the mix. The trouble is, the servlet specification doesn’t lay down many rules on how error pages are invoked. My expectation was for the servlet container to transparently offload the request to the error page and then execute the filters in reverse. In other words, the filters shouldn’t be or need to be aware that the request has gone via the error page. The request should behave like any other request.

Tomcat seriously disabused me. It takes a different approach in which the main request almost completes (all the filters execute in reverse) before the request goes to the error page. The following diagram should make it clear what I mean:

Tomcat & Jetty error handling

Tomcat & Jetty error handling

Having read the servlet specification, it does make a bit of sense. One of the few requirements is that the servlet container should pass the original, unwrapped request and response to the error page, unless a filter is configured to execute for the ERROR dispatcher. Unfortunately, if you add something to the request in your filter, or attach a variable to the thread, it won’t be available to the error page if your filter also removes that data.

That may all be a bit too abstract, so how about a concrete example? Some of the filters in Apache Shiro bind an object called the security manager to the request’s thread. Any security code can then easily grab it on demand. When the request has finished, the filter removes (unbinds) the security manager from the thread. That’s just good practice. But what happens if the error page wants to access the security manager?

Hopefully it’s obvious from the discussion so far that you need to add Shiro’s filter to the ERROR dispatcher as well as the REQUEST one. This should work. When the servlet container triggers the error page, it first executes the filter. But that’s not what happened when I tried it. Instead, the error page threw an exception saying that no security manager was bound to the current thread.

What had gone wrong? After some debugging, I discovered that a super class of the filter, OncePerRequestFilter, was skipping execution of the filter if it detected that it had already been processed. How did it do that? By checking whether a particular request attribute was set. In this case, the attribute was still there from the main request, but the security manager had been unbound from the request thread.

This problem didn’t exhibit in Jetty at all, which is kind of annoying because you would hope that code that runs on one container would also run on another. Fortunately, there is a simple moral to this story: filters should always clean up after themselves when they finish and never leave stuff in the request, session, or thread.

Grails 2.0 #1: Gradle for the win?

Ever since I attended a Gradle course, I’ve been rather obsessive about it. In particular, I’ve been looking at integrating Grails into Gradle builds. The early result was a straightforward Gradle plugin that allows you to build Grails projects. I’ve explained how to use it in a previous post, so I won’t talk about that here. It works, but it bothers me that the plugin delegates to the Grails build system. That interaction is always going to be anaemic and will almost certainly frustrate any Gradle power users. But is there any other approach that can work?

The problem

Grails has a custom build system based on Gant that has evolved over the years. The nature of the build and its interaction with Grails plugins means that it’s very difficult to integrate well with other build systems. It does its own dependency management (although it does delegate the grunt work to Ivy) and it has its own event system.

The trouble is, the build is definitely getting more bloated and complex as features are added. In fact, many of those features, such as dependency management, distinct compile/test/runtime classpaths, and artifact publishing, are built into a tool like Gradle. So we’re basically reinventing the wheel to some extent. And I have to admit that Gradle’s API is far more robust and flexible than the Grails build system.

This got me thinking: would a native Gradle build for Grails projects work? After all, build is not one of Grails’ core competencies. Why not leave it to a dedicated tool if that tool can handle Grails’ special requirements? Graeme and I had thought about doing this some time ago, but decided against the move. Gradle was still young and didn’t seem to offer enough benefits. Times have changed though.

My next thought was this: what is a Grails project if not a Groovy WAR project with a rather unique directory structure? If Gradle can handle that directory structure, why not use its standard compile tasks? Doing so would mean that other Gradle plugins would also work with Grails projects.

The solution

On that Gradle course, I discovered a Gradle feature that really sold me on its potential as a build tool for Grails projects: source sets. These are arbitrary groupings of source files that can pretty much manage any directory structure you can throw at them. Even a Grails project. All I had to do was create a test Grails project with a Gradle build, apply the ‘groovy’ plugin, and configure the source sets. Next thing I knew, I could compile a Grails project. Whoohoo!

If only everything was so simple. Trying to run a Grails application proved to be a far tougher challenge. This required compilation and loading of all installed Grails plugins, including the core plugins. On the bright side, I had an opportunity to create a build-specific plugin manager that didn’t have to worry about runtime stuff. This meant a great simplification of the code.

The result of all this work is another Gradle plugin, although this one hasn’t been published yet. It’s in a very raw state at the moment, and I want to avoid confusion with the existing Gradle plugin I mentioned at the beginning of the post.

About the plugin

So how does this plugin work? The core of it is the grails.build.plugin.GrailsPlugin class, which is the entry point for the plugin. It does several things of note:

  • apply the ‘groovy’ and ‘war’ plugins to the project;
  • configure the source sets;
  • sets up some extra dependency configurations; and
  • creates a whole bunch of specialist Grails tasks and creates the dependencies between them.

The most significant tasks are:

  • buildData – instantiates BuildSettings and loads the build configuration
  • buildPlugins – builds the project’s installed Grails plugins and loads them
  • generateWebXml – generates the web descriptor to ./web-app/WEB-INF/web.xml
  • generateApplicationContextXml – generates the root application context descriptor to ./web-app/WEB-INF/applicationContext.xml
  • packageI18n – copies the i18n resource bundles and converts them to ASCII if required
  • run – launches the configured servlet container

As you can see, the plugin already handles Grails plugins, although there is still much that doesn’t work. The fact that the plugin can fully build plugins of various types and add their dependencies and classes to the appropriate classpaths is a big deal though. This just doesn’t happen with the current Grails build system.

Another really neat feature is that Grails plugins can provide their own build files and Gradle plugins. You can see an example in the Jetty plugin that’s packaged in the root of the grails-build-x project. This is incredibly powerful stuff because it means that the Grails plugin can have full access to the Gradle build and do pretty much anything! For Jetty, this means adding the container starter classes to the servletContainer configuration and adding its dependencies to the project’s runtime classpath. But pretty much anything is possible.

The current run task demands some extra requirements of servlet container plugins, so that standard ones won’t work. However, the custom Jetty plugin I referred to earlier can also be used in a normal Grails project with the Grails build system. That means a plugin author can add features that help it integrate with the Gradle plugin without breaking normal Grails projects!

So what does it all mean?

The Grails build system evolved out of a failure on the part of existing build tools to provide a solution to building Grails projects, particularly once plugins were introduced. At the time, I think Gradle was still an idea in the air. Since then, the build system has grown in features and complexity, and it works pretty well.

Now, though, I think it’s time for it to retire. It doesn’t make sense for Grails developers to spend a lot of their time on build stuff when another tool is now available that will do most of the work itself. The build system also doesn’t play particularly well with other build tools, which can make adoption in the enterprise rather tricky. And a clean room implementation means clearing out a lot of cruft and being able to resolve some outstanding and difficult problems.

The great thing about the new Gradle build is that it can be developed in parallel to the Grails 1.x line. And if it makes it into Grails 2.0 as the build system, then hey, the plugin authors have already prepared and tested their plugins for it. Certainly my hope is that Gradle forms the core of the build system for Grails in the future. Fingers crossed!

Building a Grails project with Gradle

Earlier this week, I attended Hans Dockter’s first ever Gradle course. Everything seemed to click into place and it inspired me to have another crack at writing a Gradle plugin for building Grails projects. A lot of the hard work had already been done to get the Maven plugin working reasonably well, so all I had to do was make use of the helper classes that already existed for bootstrapping the Grails build system.

So how do you use it? Simple. Here’s a basic Gradle build file (build.gradle) that you can put in the root of your Grails project:

buildscript {
    repositories {
        mavenCentral()
        mavenRepo urls: 'http://snapshots.repository.codehaus.org'
        mavenRepo urls: 'http://download.java.net/maven/2/'
    }

    dependencies {
        classpath "org.grails:grails-gradle-plugin:1.0-SNAPSHOT"
    }
}

apply id: "grails"

repositories {
    mavenCentral()
    flatDir dirs: "lib"
}

configurations {
    compile.exclude module: "commons-logging"
}

dependencies {
    compile "org.grails:grails-crud:1.2.0",
            "org.grails:grails-gorm:1.2.0",
            "org.apache.httpcomponents:httpclient:4.0",
            "org.apache.httpcomponents:httpmime:4.0",
            ":apache-solr-solrj:1.4:dev",
            ":pgptools:0.1"

    // Required by the Joda Time plugin.
    compile "org.springframework:spring-web:3.0.0.RELEASE"
    compile "org.springframework:spring-webmvc:3.0.0.RELEASE"

    // Required by the JMS plugin.
    compile "org.springframework:spring-jms:3.0.0.RELEASE"

    runtime "org.slf4j:slf4j-log4j12:1.5.5",
            "hsqldb:hsqldb:1.8.0.5",
            "postgresql:postgresql:8.3-603.jdbc3",
            "org.bouncycastle:bcpg-jdk15:1.44",
            "net.sf.ehcache:ehcache-core:1.7.1"
}

Unbelievably, that’s it! You can now execute any of the Grails commands via Gradle like so:

gradle compile
gradle create-domain-class -Pargs=org.example.Book
gradle run-app
gradle run-app -Pargs=--https -Penv=prod
gradle create-gwt-action -Pargs="--shared-pkg=client org.example cmd ListBooks"

The -Pargs option allows you to pass any arguments you want to the corresponding Grails command, while -Penv allows you to override the default environment. In case you’re wondering, the -P option allows you configure project properties. args and env are simply two that are understood by the Grails plugin.

So what’s happening in this build file? First of all, we use the buildscript {} section to configure the plugin as a dependency of the script. Once the plugin is on the classpath, we can apply it to our build via apply id: 'grails'. Alternatively, you could download the plugin JAR file and put it into $GRADLE_HOME/lib.

The rest of the build file is concerned with setting up the dependencies for our Grails project. Quite a few are declared in this example, but the only requirement is that you declare dependencies on at least one Grails module, a logging implementation, and the JDBC driver(s) for whatever database(s) you’re using. If you’re using the Hibernate second-level cache, you should also include EhCache or OSCache.

The true beauty of this plugin is that *all* the Grails commands are available to you, including those provided by plugins. This is far better than the Maven plugin, which has a set of hard-coded goals for the most common Grails commands and a generic exec goal for executing arbitrary Grails commands. I haven’t tested all of the commands, so feel free to report any problems.

The code for the plugin can be found on GitHub. I think you’ll be surprised at how little code there is. In fact, there are only two files: build.gradle in the root of the project, and GrailsPlugin.groovy under src/groovy. I definitely recommend taking a look at the plugin file to see how Gradle’s dynamic tasks made it so easy to support all the Grails commands.

Give it a go and see what you think!

Update First off, the plugin currently only works with Grails 1.2.0+ and Gradle 0.9 snapshots. Second, I’m aware that the build script doesn’t work at the moment. Unfortunately, there appears to be a Gradle bug preventing the fixed build script from working. Stay tuned.

Update 2 My bad. The version of mavenRepo that takes more than one repository URL expects the first one to contain the POM, while the other ones are for getting hold of the JARs. I have corrected the example build so that it has separate mavenRepo lines for the Codehaus Snapshots repository (for the plugin) and the java.net repository (for GParallelizer),

Update 3 I have uploaded a new version of the plugin that allows you to start from scratch. Create a new directory for your Grails project and add the following build.gradle file to it:

buildscript {
    repositories {
        mavenCentral()
        mavenRepo urls: 'http://snapshots.repository.codehaus.org'
        mavenRepo urls: 'http://download.java.net/maven/2/'
    }

    dependencies {
        classpath "org.grails:grails-gradle-plugin:1.0-SNAPSHOT"
    }
}

apply id: "grails"

version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
    flatDir dirs: "lib"
}

configurations {
    compile.exclude module: "commons-logging"
}

dependencies {
    compile "org.grails:grails-crud:1.2.0",
            "org.grails:grails-gorm:1.2.0"

    runtime "org.slf4j:slf4j-log4j12:1.5.5",
            "hsqldb:hsqldb:1.8.0.5",
            "net.sf.ehcache:ehcache-core:1.7.1"
}

From the new directory, run gradle init and a fresh Grails project will be created for you.