Monthly Archives: July 2009

GWT Plugin for Grails 0.4-SNAPSHOT

I have just released a new interim version of the GWT plugin for Grails. The main changes are:

  • it works with GWT 1.6 properly
  • GWT client requests now go through a controller
  • new command: clean-gwt-modules

Two of those are pretty self-explanatory, but the second one deserves a closer look.

In the beginning…

The traditional approach to GWT RPC involves creating a servlet that extends GWT’s RemoteServiceServlet class for each remote service in your application. Prior to version 0.4, the plugin used a technique based on that approach but geared towards Grails. Rather than requiring the user to create his own servlets and configure them in the web descriptor, the plugin set up a single servlet (extending RemoteServiceServlet) for each GWT module. The servlets simply forwarded requests to the appropriate Grails service.

This approach worked well, particularly as the user gained all the benefits of using proper Grails services, but it meant that neither URL mappings nor Grails filters took effect. Each module had to send requests to a hard-coded URL: /gwt/<moduleName>/rpc. With the introduction of version 0.4 of the plugin, this has all changed.

Enter GwtController

The custom GWT servlet has gone, disappeared, vanished. In its place you’ll find a new controller: GwtController. It works in a similar way to the old servlet, but because requests now go through the standard Grails dispatch logic, URL mappings and Grails filters can now be used on GWT requests.

You don’t have to do anything special to get the new version of the plugin working with your application because it comes with a URL mapping that matches the old hard-coded URL:

class GwtUrlMappings {
    static mappings = {
        "/gwt/$module/rpc"(controller: "gwt", action: "index")

Note that the above mapping includes a module parameter, but the controller currently doesn’t use it any way. It’s only there so that the mapping behaves the same as the old servlet URLs.

If you want to send GWT requests to a different URL, simply add a new entry to your application’s URL mappings. You will need to map the URL to the same controller and action as shown in the code above.

That’s all there is to it! Please try it out and let me know of any problems.

Introducing SmartGWT to Grails

SmartGWT is a custom library for GWT that wraps the SmartClient AJAX toolkit. It looks impressively comprehensive and the show case is pretty slick. As with ExtJS though, SmartClient (and by extension SmartGWT) is quite large, and so it will take some time to learn how to use it. That’s my disclaimer, or more accurately an excuse for using such a pitiful example in this post. My aim here is just to show you how to get started with Grails and SmartGWT.


You need Grails installed, unless you’re using Ant or Maven (in which case you need those installed 😉 ). I’ll assume in this article that you’re using the Grails command line, and therefore have a Grails installation.

Working smart

In order to use SmartGWT you need a Grails project, so create one now. I called mine “smart-working” – feel free to ditch that and use another name. Once Grails has worked its magic and created the project, you need to install the marvellous, wonderful, and downright cool GWT plugin (can you tell I wrote it?):

grails install-plugin gwt
At the time of writing, this command will install version 0.3.2 and present you with a list of GWT-related commands added by the plugin:

Plugin gwt-0.3.2 installed
Plug-in provides the following new scripts:
grails compile-i18n
grails create-gwt-page
grails run-gwt-client
grails create-gwt-module
grails compile-gwt-modules
grails generate-gwt-rpc

It’s looking good so far, but there’s no reference to SmartGWT in any of those commands. The sad truth is, you have to install it yourself at the moment. Fortunately, that’s pretty easy:

  1. grab the SmartGWT distribution from Google Code
  2. extract the zip file
  3. create the directory <project>/lib/gwt, for example smart-working/lib/gwt
  4. copy the smartgwt.jar file (in the root of the unpacked zip) to the directory you just created.

Any GWT libraries that you want to use should go into <project>/lib/gwt.

Your first SmartGWT page

SmartGWT is now ready for action. All we have to do is harness its power in our application’s UI. As with normal GWT, the starting point is a module. Let’s create one now:

grails create-gwt-module org.example.SmartButton
This will create two files under the src/gwt directory:

  • org/example/SmartButton.gwt.xml
  • org/example/client/

At the moment, these files are only configured for bog-standard GWT, but adding SmartGWT is pretty straightforward. First off, we need to add a line to the XML module file:

    <!-- Inherit the core Web Toolkit stuff.                  -->
    <inherits name=""/>

    <!-- Add SmartGWT -->
    <inherits name="com.smartgwt.SmartGwt"/>

    <!-- Specify the module entry point class.                   -->
    <entry-point class="org.example.client.SmartButton"/>

The second step is to use the SmartGWT elements in

package org.example.client;


import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.layout.VLayout;

 * Entry point classes define <code>onModuleLoad()</code>.
public class SmartButton implements EntryPoint {
     * This is the entry point method.
    public void onModuleLoad() {
        VLayout main = new VLayout();

        Button button = new Button("Jump!");
        button.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent evt) {
                SC.say("You first");


The above code will create a simple button with the text “Jump!” on it that, when clicked, will display a modal dialog saying “You first”. We still don’t have a page on which to display this button, though, so we’ll have to create one:

grails create-gwt-page smart.gsp org.example.SmartButton
This will create a new GSP view that uses our SmartButton module. The Grails GWT plugin currently puts the GSP page, smart.gsp, in the project’s web-app directory, but that’s no longer the appropriate location (since Grails 1.1 I believe). So, you should move the smart.gsp file to the grails-app/views directory.

As an aside, you can also create GWT views backed by controllers. If you pass a string of the form <controllerName>/<page>.gsp as the first argument, the command will add the <page> view to the named controller, although you will have to manually add the corresponding action. The command will even offer to create the controller if it doesn’t already exist.

Right, the view has been created and it’s even displaying the button, but it’s a bit like a wireframe view of the button. That doesn’t look good. The problem is that the page can’t find the SmartClient skin files because the CSS link is wrong. You’ll probably also notice that the (wireframe) button is overlaying the Grails logo. Argh!

Let’s address the first problem. SmartGWT assumes that your project follows the standard GWT 1.5 layout. This assumption falls flat on its face with a Grails project, though, hence the incorrect CSS link. To fix the issue, we need to tell SmartGWT where the CSS files can be found. How do we do that? Add the following line to your smart.gsp file:

  <!-- Integrate with Sitemesh layouts           -->
  <meta name="layout" content="main" />

  <!--                                           -->
  <!-- Any title is fine                         -->
  <!--                                           -->
  <title>Example title (change this!)</title>

  <script>var isomorphicDir = "gwt/org.example.SmartButton/sc/"</script>

  <!--                                           -->
  <!-- This script loads your compiled module.   -->
  <!-- If you add any GWT meta tags, they must   -->
  <!-- be added before this line.                -->
  <!--                                           -->
  <script type="text/javascript" src="${createLinkTo(dir: 'gwt/org.example.SmartButton', file: 'org.example.SmartButton.nocache.js')}"></script>

Interestingly (or simply annoyingly depending on your take), you need to remove the leading gwt/ from the isomorphicDir value if you’re using GWT 1.6. I don’t know why, but that’s what you have to do.

Update I have discovered that the standard main.css file used by the default Grails layout doesn’t play nicely with SmartGWT. The best option is probably to modify grails-app/views/layouts/main.gsp by removing the link to main.css. Your SmartGWT application will then look as it should!

The second problem relates the the SmartGWT layout that we use in the example. If you create a VLayout, set it’s height to 100% (via the setHeight100() method, and then call the draw() method, the layout takes up the whole page, even if a Grails layout is applied to the view. The solution involves three steps. First, remove the call to setHeight100() in Second, replace the line


Don’t forget to import the RootPanel class! The final step is to add a div to the body of the host page, smart.gsp:

  <!-- OPTIONAL: include this if you want history support -->
  <iframe id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>
  <div id="main"></div> 
  <!-- Add the rest of the page here, or leave it -->
  <!-- blank for a completely dynamic interface.  -->

If you’re using hosted mode, just refresh the page to see the final product in action! The modal dialog looks a bit off for some reason, but that can probably be fixed by a SmartGWT aficionado.

Update The modal dialog looks off because of the main.css problem mentioned in the previous update. It also seems that you don’t need to remove the call to setHeight100() – that was probably down to main.css as well.

An idiosyncrasy in the GWT plugin

If you use a normal browser to view the SmartGWT page in all its glory, rather than hosted mode, then you may soon notice that the GWT modules are not recompiled by grails run-app when they are modified. This behaviour is intentional: hosted mode reads the module files directly, so there is no reason to incur the extra time penalty involved with compiling the modules on startup. However, for some reason (that I genuinely can’t remember) the compiled JS files have to at least exist, even if they aren’t the latest ones. That’s why the modules are compiled the first time you run the application.

You might think this leaves you in a bit of a pickle if you use a normal browser instead of hosted mode, but you can easily recompile the modules with the grails compile-gwt-modules command.

Variations on the theme

When you inherit the SmartGwt module, your host page is automatically populated with all the required JS and CSS links for the default skin. You can gain a bit more control by inheriting SmartGwtNoTheme, which allows you to specify a different theme in the host page, or SmartGwtNoScript, which allows you full control over the JS files that are included as well as the theme. The showcase example for SmartGWT demonstrates the use of SmartGwtNoScript – note how much more you have to add to the host page!

That’s it for now. I may do more work with SmartGWT in the future. If so, I’ll post anything I find useful.

Developing Grails: setting yourself up

Grails is in need of developers – just take a look at the number of issues in JIRA. The trouble is, developers don’t want to spend a long time familiarising themselves with how Grails works just to fix a bug. So, I hope to lower the barrier to entry by showing you how to develop and debug Grails itself in a series of articles. I’ll start with setting up the development environment.


  • A JDK (1.5 or above). Make sure that you set the JAVA_HOME environment variable to the location of the JDK, *not* a JRE.
  • Ant (I think 1.7+).

That’s it! You don’t even need to install Groovy.

Getting the Grails source

Once upon a time, Grails used to be hosted in a Subversion repository on Codehaus. Those days are gone: you now need git to get the source code from GitHub. I won’t explain how to install git here (should be dead easy on unix-type operating systems), but for ye poor Windows users, try this blog post.

Once git is installed, you have a couple of options:

  1. sign up to GitHub, fork the Grails repository, and then clone your fork locally; or
  2. clone the Grails public URL.

I recommend the first option, because then it’s easy to submit your changes to the Grails development team via a push. The details of forking and pushing are described in one of the GitHub guides. Simply use the “fork” button on the main Grails page on GitHub.

Update I have updated the URL below to take into account the rearrangement of the Grails projects in GitHub.

The other option doesn’t require you to have a GitHub account. Instead, use your git client to get the source code directly:

git clone git:// grails-core
This will copy the Grails repository into a directory called “grails-core”. This will get you the core Grails code, but not the documentation, functional tests, Maven plugin nor a few other things. The core is what most people are interested in though.

Just remember that if you use the second option, you can’t push changes to the Grails team. You’ll have to create patch files and attach them to JIRA issues.

I’m not going to explain how to use git here, but if you need some help, take a look at these introductions:

System configuration

The next trick is to use the development version of Grails for your projects. This is surprisingly straightforward: just set the GRAILS_HOME environment variable to your Grails directory and update the path. So for example, if you have cloned the Grails repository in ~/dev/grails-core, then you set the environment variables like so:

export GRAILS_HOME = ~/dev/grails-core
export PATH = $GRAILS_HOME/bin:$PATH
Of course, the exact syntax you should use depends on your platform. Once these variables are set, you will be using your development version of Grails every time you run the grails command.

Build Grails

Update As of Grails 1.3, we use Gradle to build the project. I have updated the code below, but left the pre-1.3 commands in parentheses.

The source code is all very well, but the Grails command line won’t work until you have built the project. The easiest way to do this is to run

./gradlew libs
(pre-1.3: ant jar)
from the Grails source directory (.../grails-core). You can also run the unit tests with

./gradlew test
(pre-1.3: ant test)
And to execute a single test case:

./gradlew testSingleNameOfTestClassMinusTestExtension
(pre-1.3: ant -Dtest=NameOfTestClassMinusTestExtension test)
So if you want to run the GrailsClassUtilsTests, it’s

./gradlew testSingleGrailsClassUtils
(pre-1.3: ant -Dtest=GrailsClassUtils test)

Editing the source code

So far so good, but it’s not much good having a development version of Grails if you aren’t going to edit it. This is where things get tricky. Grails consists mostly of Java and Groovy code, so if you want to use an IDE, you need one that supports Groovy. IntelliJ IDEA is the prime candidate, but it’s commercial. That said, since you’ll be working on an open source project (Grails), you could use a (free) open source licence. One option is to register as a developer on Codehaus, but you may not be accepted until you have submitted a several (or more) patches that pass code reviews.

If you do have a licence for IntelliJ, you’ll find project files in the root of the Grails directory. Load those up and you’re away! Eclipse is probably a non-starter until SpringSource do their thing with the Groovy/Grails plugin. I’d like to recommend Netbeans, but every time I have tried it for the Grails source code, it has failed (usually becoming unusably slow or simply hanging). Hopefully things will improve in the not too distant future.

Update SpringSource Tool Suite (STS) with Groovy & Grails support is now working very well – and it’s free! IntelliJ Community edition is also free and comes with Groovy (but not Grails support). Since you only need the Groovy bit for working on the Grails code, the Community edition is also a viable option.

Next steps

You should now be set up for Grails development and raring to go. So, in the next installment, I shall look at how the Grails command line is implemented and shine a light on some of the mysteries of scripts and classpaths.

How to write a book

Having completed the book Grails in Action with my co-author Glen Smith not so long ago, I thought it might be a good idea to post some of the things I’ve learned. Despite the title of the post, I definitely don’t profess to be an expert in this field – I’ve only co-written one book after all! The post also targets technical books, rather than books in general. Budding authors may nonetheless find some useful information here.

So, you’ve decided to write a book. What should your first steps be? Good preparation can make the writing process a lot easier in the long run, so we’ll start with that.

1. Write a sample chapter/half-chapter

Ouch. Is he serious? Yep. I suspect the last thing anyone wants to do before writing a book is to write an extra throw-away chapter, or even half a one. There is reason in this madness though.

It’s important to know how long it’s likely to take to write the book. That will enable you to schedule achievable milestones. Unachievable milestones are a great way to become depressed very quickly. It’s also a good idea to find out whether you enjoy writing enough to create a whole book. Better to find out now, rather than half-way through. That said, if I’d tried this, I may never have agreed to do Grails in Action!

If you’re sure you want go through with this, you’ll need to make some important decisions early on. Those decisions depend on knowing who your target audience is.

2. What background will your readers have?

Are they beginner, intermediate, or experienced developers? Will they have some knowledge of your chosen topic? Maybe they know a lot about a related topic, but not the one you are covering. The answer will have a profound impact on the style and content of your book, so think carefully on this one. Once you make the decision and have started writing, stick to it. Beginners will require more background information and more explanation for any given topic.

For example, with Grails in Action we decided to target intermediate to experienced Java developers who may know nothing about Groovy or Grails. We also wanted to fit as much advanced stuff and practical advice in as possible so that experienced Grails developers could benefit.

3. How big will your book be?

This may seem an odd question, but it’s closely related to another: how much stuff do you want to cover? The problem is, if you just think about what information you want to include, you may end up with a mammoth book that’s only suitable for weight lifting! Size is important. Some people like to carry books around with them. Others are intimidated by thick books that look impenetrable. On the other hand, some will view a thin book as light on content.

The overall page count can be estimated by the amount of information you want to convey divided by the pace at which you cover that information. The pace partly comes from writing style, but it is mainly determined by your target audience. A beginner’s book will inevitably have a slower pace than one targetted at experts. So, the faster the pace, the more information you can fit into a given number of pages.

4. Decide what you want to put in the book

By this stage, you should have an idea of how much you can fit into your book, so it’s time to look at what information you want to include. There will be trade-offs, have no doubt. The question is whether you go for more in-depth coverage of fewer topics, or lighter coverage of more. Or in-depth coverage of more topics and let the size of the book increase. Just be careful: you’ll probably find that topics require more pages than you expect. I certainly did.

This seems like a pretty big decision to make and hold yourself to before the book has even started. There is some leeway for sure, but sticking closely to your initial targets will help you keep the book focused. The publisher will be happy too, since they don’t have to make any last minute changes with the printers.

5. Organise your chapters up-front

This is almost a no-brainer. The chapter structure is the equivalent of the 60,000ft view of your book. You have to have some idea of what you want to say and in what order. You don’t have to stick to your initial chapter structure come hell or high water, but changing it will likely have a significant impact on chapters you have already written, particularly with regard to chapter references. You might also need to change examples and the like.

6. Pick an approach for sample code

There are basically two approaches to sample code: use a single example throughout the book that you build up; or use different examples in each chapter. You can even mix and match if you want. A single application running through the book seems the more popular approach at the moment, and it’s the one we chose for Grails in Action.

A single example provides a strong thread for the reader to follow and allows for continuity. It is also more likely to result in real-world code – something that readers appreciate. The main downside is that your chosen example may not suit all topics, and you may end up adding contrived functionality to demonstrate stuff. Using different examples gives you flexibility and the opportunity to use more appropriate scenarios, but each new example typically requires a bunch of support code too.

Now you’re ready to do some writing.

7. Start at the beginning

Writing your chapters sequentially will help you maintain a narrative. If you write them out of order, you won’t know what’s gone before and it becomes difficult to keep a sense of progression going. Remember that readers will typically read non-reference books from the start to the end, so that progression is important. For reference books, it probably doesn’t matter too much in what order you write the chapters.

One variation on this is to pick a chapter that you expect to be easy for your first one. That will help you get warmed up and into the swing of things before you have to tackle trickier topics. But I recommend returning to the sequential approach after that first one.

8. Use free writing

When you want to start a writing session, begin with half an hour or so of free writing. This involves just writing down anything that comes into your head, generally without any regard to punctuation or structure. Just write. This will warm you up and get you into writing mode. You can then use any bits of the free writing in your chapter if you want, but you don’t have to. Note that it’s not essential that you write about the topic that’s planned for the session, but it helps.

9. Use mind maps for each chapter

Mind maps are great tools for organising your thoughts and working out what should go in a chapter. You only have to do this once per chapter, but it’s probably best done after a free writing session on the chapter topic(s). Once you have a mind map, it’s worth turning that into a structure of sections and sub-sections, i.e. giving it a semblance of order. Sorting out the chapter progression in advance like this can make the actual writing much easier. You basically know where you want to go with the chapter, so the writing should flow naturally.

10. Keep communication channels open between co-authors

This may sound like a case of stating the bleeding obvious, but when you’re under time pressure and you just want to finish the chapters you own, it’s easy to skip reading your co-authors’ chapters and letting them know about changes to your own. You don’t want your book to end up with inconsistencies due to a lack of communication. As a concrete suggestion, make sure all co-authors read all the chapters before the book goes to production. It may take time, but it will save heartache later!

That’s it for now. If I think of any more advice, I’ll add it in later. Hopefully the above will help at least one poor soul who’s writing a book, or at least planning to.