21 Dec 2010

Profiling web requests in your Grails application

Here’s a simple filter I’ve been using to help me detect points of improvement in my application:

To use it, put this class in the grails-app/conf folder of your project. To activate the profile, call any URL of your application with the showTime=on parameter, like this:

http://localhost:8080/my-grails-app/book/list?showTime=on

After calling that URL, all request times will be measured and informed on the application’s log, like this:

2010-12-21 12:02:31,698 [http-8080-5] DEBUG filters.UtilFilters  - Request duration for (book/list): 20ms/50ms

The first time informed (20ms) is the time spent executing the action (list in this case) and the second (50ms) is the time spent rendering the view (list.gsp).

To turn off the profiler, call any URL with showTime=off:

http://localhost:8080/my-grails-app?showTime=on

Enjoy :)

Deluan.

21 Dec 2010

Using Cache-Headers plugin in a non-english server

UPDATE: This problem has been fixed in version 1.1.3 of the plugin. Thanks Marc and Luke Daley!

This week I tried the Marc Palmer’s excelent plugin Cache-Headers, and it really rocks! Using it I can make all my server-side generated images be cached on the client, reducing significantly the bandwidth and cpu-power necessary by my application.

But there’s a little gotcha: The plugin (as of version 1.1.2) uses a SimpleDateFormat to generate and check the Last-Modified header, and the implementation creates this SimpleDateFormat with the system’s default Locale, in my case Portuguese. This causes errors like this:

java.lang.IllegalArgumentException: Ter, 21 dez 2010 15:10:33 GMT
    at com.grailsrocks.cacheheaders.CacheHeadersService.withCacheHeaders(CacheHeadersService.groovy:140)
    at com.grailsrocks.cacheheaders.CacheHeadersService$withCacheHeaders.call(Unknown Source)
    at CacheHeadersGrailsPlugin$_addCacheMethods_closure7_closure11.doCall(CacheHeadersGrailsPlugin.groovy:61)
    at org.weceem.controllers.WcmContentController$_closure3.doCall(WcmContentController.groovy:172)
    at org.weceem.controllers.WcmContentController$_closure3.doCall(WcmContentController.groovy)
    at org.apache.shiro.web.servlet.ShiroFilter.executeChain(ShiroFilter.java:687)
    at org.apache.shiro.web.servlet.ShiroFilter.doFilterInternal(ShiroFilter.java:616)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)

The workaround I found was to override the construction of that SimpleDateFormat. Luckily it’s been created in a small class, that is easy to extend:

All you have to do is put this class in your project (in the src/groovy folder) and add the following configuration override in your Config.groovy:

beans {
    cacheHeadersService {
        dateFormatters = new com.deluan.grails.util.EnglishDateFormatterThreadLocal()
    }
}

I already filled a bug report here: http://jira.codehaus.org/browse/GRAILSPLUGINS-2707, and probably this post will be obsolete in a near future :)

Deluan.

1 Nov 2010

Apache Shiro tags for Facelets - Securing your JSF pages

First, a little introduction. You can skip it and go straight to the source code, if you want.

I started working with Apache Shiro when it was still called JSecurity, and I have to say that it really rocks! I tried to use Spring Security (Acegi) in some projects, but the easiness and lean approach of Shiro is unbeatable. For a quick introduction, here's a quote from the project's site:
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.
I've used it in Java and Grails projects, and recently I've even been experimenting it with Google App Engine. It fits very well in almost any Java platform project that needs security.

Shiro already works great in a JSF/Facelets project. You can use it's filters to grant and deny access to some parts of your application and to force authentication (redirect to login).

The only functionality missing is the power of it's JSP taglib, that are used to conditionally render some parts of your HTML, based on user's authorization, roles and permissions (you can learn how to use them with this simple example project). The problem is that this conditional rendering is not totally compatible with JSF's phases. Better than trying to fit a cube in a spherical hole, I decided to rewrite Shiro's JSP tags into a Facelets taglib, totally compatible with JSF.

All original tags are available as their Facelets equivalents, and I have introduced two new ones:

<shiro:hasAnyPermission> - Displays body content only if the current user has one of the specified permissions from a comma-separated list of permission strings.

<shiro:remembered> - Displays body content only if the current user has a known identity that has been obtained from 'RememberMe' services. Note that this is semantically different from the 'authenticated' tag, which is more restrictive.

I've already submitted a patch to Shiro's development team, but they're very busy at the moment packaging the new 1.1 version for release. So I decided to share the taglib on GitHub, and host the artifacts in my personal maven repository, as I need to use the tags in an on-going project.

If you want to try it in your maven project, add my repository to your pom.xml:

and add the jar dependency:

Now you can declare Shiro's namespace in your xhtml pages and use the tags like this:

That's it! Just keep in mind that as soon as this lib gets incorporated officially in Shiro, I'll stop updating it in GitHub and all future enhancements will only be available in the official version. If you want to see the tags incorporated officially into Shiro sooner than later, you can vote here: https://issues.apache.org/jira/browse/SHIRO-206

And if you have any suggestion, please leave a comment.

Enjoy ;)
11 Oct 2010

Using Spring DI in your Gaelyk projects

Since I started using Gaelyk, one of the features I missed most (coming from a Grails background) is Spring's dependency injection. Until recently I didn't even know if it was possible to use Spring in Google App Engine, so I decided to do a little investigation on the subject, and found out that it's very easy indeed.

Here's a little tutorial on how to configure Spring in your Gaelyk project. I'm assuming you have basic knowledge of Spring, Gaelyk and Maven.

First, let's create a Gaelyk project. The easiest way is using the excelent maven-gaelyk archetype:
mvn archetype:generate -DarchetypeGroupId=org.codeconsole -DarchetypeArtifactId=gaelyk-archetype -DarchetypeVersion=0.5.5 -DarchetypeRepository=http://maven-gaelyk.googlecode.com/svn/repository/ -DartifactId=gaelyk-spring -DgroupId=com.deluan.gaelyk -DgaeApplicationName=gaelyk-spring
Now open the project in your favorite IDE, so we can edit the configuration files. First, add the Spring dependency to your pom.xml:
Next we need to configure Spring's ContextLoaderListener in web.xml:
As you can see from above, we configured Spring to load all context configuration files under the directory WEB-INF/spring.

With these configurations in place, your project is already Spring enabled. Now we need a easy way to access the Spring's Application Context. One good way to do this is using a singleton that implements the ApplicationContextAware interface. To keep this post as small as possible, I borrowed an implementation from this blog post, where you can learn more about the details. Create the directory src/main/groovy and put the following SpringApplicationContext singleton there (in the correct package):
Configure the singleton in your spring context:
As you can see, I also declared some SimpleDateFormat instances as beans to be used in our examples.

Now everything is configured and ready to be used. Let's se how we can obtain a spring bean inside a Groovlet. Create the file WEB-INF/groovy/index.groovy with the following content

Now run your application with the command `mvn gae:run`, point your browser to http://localhost:8080/index.groovy and you should see something like this:
Index1

Well, that's it! Nothing so much different from what you are used to do in a normal Web application, right? But remember: Gaelyk is NOT your normal Web framework so let's spice things a little bit.

The solution for looking up beans depicted above is a bit cumbersome.  Let's use Gaelyk's plugin system to make things a little more "groovy". Using the plugin descriptor bellow, we can provide shortcuts to our SpringApplicationContext's methods, getContext() and getBean(). Save it in the file WEB-INF/plugins/spring.groovy:
Before you can use these shortcuts, you need to tell Gaelyk about your descriptor by "installing" it in your project. Save the code bellow in the file WEB-INF/plugins.groovy:
Now you can use the shortcuts in your Groovlets this way:
Cool, isn't it? A note on the `autowire` binding: It creates bindings "automagically" for each bean you passed as a parameter, as if the beans were declared in your Groovlet.

You can download the sample project used in this post from GitHub: http://github.com/deluan/gaelyk-spring. You can follow each commit to see exactly what was changed in each step of this tutorial.

If you have any suggestion or question, please leave a comment.

UPDATE: I've refactored the `autowire`method into a Category, so now it's not necessary to pass `this` as the first parameter.  The new version is available at GitHub
4 Oct 2010

Calling the correct Grails version automatically from command line

Now that I decided to organize and publish some of my code/hacks here, I thought it would be a good thing to republish here my Grails caller script.

I work and mantain various Grails projects at the same time, and some of them uses versions of Grails as old as 1.0.3! So the question is: How to call the right version of grails command for a given project, the version that the project was created with?

First I tried changing the GRAILS_HOME environment variable every time I was going to work with a project that uses a different version than the default. But it’s just too much work for a thing that should be transparent. So I decided to create a shell script to solve this problem. The script should detect which Grails version to call when it’s executed. Here’s the script I came up with:

How it Works?

The script first checks if you specified a version in the command line, like: grails 1.3.5-SNAPSHOT create-app. If not, it looks for an application.properties file in the current folder. This file keeps some metadata for Grails' projects, including the Grails version the project was created with. If it does not find any application.properties in the current folder, it then just calls the default Grails installed in your system, the one that GRAILS_HOME points to.

Prerequisites

  • All your Grails versions must be installed under the same base directory. Ex:

    /opt/grails-1.0.3
      /opt/grails-1.1.1
      /opt/grails-1.2-M2
      /opt/grails-1.3.3
      /opt/grails-1.3.5-SNAPSHOT
  • GRAILS_HOME environment variable must be set and point to your “default” Grails installation

  • This script was tested on Mac OS X (Snow Leopard), Linux (Ubuntu) and Windows (with cygwin)

Installation

  • Download the script: http://gist.github.com/601039
  • Include the folder where it is installed in your PATH.
  • Exclude $GRAILS_HOME/bin from your PATH

Usage

Using the script is as transparent as possible:

  • If you invoke it from a project folder, it will detect the version used by the project and call the correct grails (if it is installed in your system)
  • If you invoke it from any other folder that does not contain a Grails project, it will call the “default” Grails installation
  • If you want to call a specific Grails version (i.e. when doing an upgrade) you can specify the version you want in the first parameter. Ex:

    $ grails 1.3.3 upgrade

If you have any question or suggestion, please leave a comment here or send it to the Grails user list.

30 Sep 2010

How to use an external log4j.properties in you Grails project

In a recent Grails project, I had to follow some corporate guidelines regarding application deployment, and one of those were that the log4j configuration for the application must be externalized and in the properties format.

I searched for a Grails plugin that could help me on this, with no luck. Then I remembered that a Grails application is just a Spring application in disguise, so I looked for the Spring way to do this.

There are at least two ways to do this using Spring: Log4jConfigListener and Log4jConfigurer. I choose the later because the former assumes an expanded WAR file, which was not my case.

Here’s the recipe I came up with:

  • Configure a Log4jConfigurer Spring bean in your grails-app/conf/resources.groovy: (see here for a resources.xml version)

  • Install the templates in your project with grails install-templates, so you can change some files used for Grails' code generation. The one we are interested is the web.xml template

  • Comment out the Grails' Log4jConfigListener from the src/templates/war/web.xml template:

  • You can (and should) remove the log4j configuration block from your Config.groovy

  • That’s it!

This was tested with Grails 1.3.3, deploying to an Oracle WebLogic 10.3.0 container.

28 Sep 2010

Reading: Practices of an Agile Developer

9780974514086

This book seems to summarize well all the good practices that a developer must adopt when working on a team that is committed to the success of software projects. 

One quote from the book: 

"If you're being pressured to compromise code quality, it might help to point out that you, as a developer, don't have the authority to degrade corporate assets (the overall code base)."
18 Mar 2009

Creating permalinks with Grails

I've been working with Grails for some time now and if I had to choose just one good thing to say about it is how it's community is really great!

I think it's time to start giving back some contribution, and here's the first one: A Permalink Codec to generate permalinks based on strings. It strips out all non word chars and convert the resulting string to lowercase:

To use it in your Grails project, save it in `grails-app/utils/com/deluan/grails/codecs` folder as `PermalinkCodec.groovy`.

Please read the (excelent) Grails' manual for more info on how to use codecs.