Monthly Archives: August 2009

The Command Pattern with the Grails GWT Plugin

A talk by Ray Ryan of Google at the 2009 Google IO conference has caused a bit of a buzz in the GWT community. In that talk, Ray recommends several design patterns that will help make your projects more manageable as they grow in size. The particular suggestion I’ll be focusing on in this post concerns using the Command Pattern for server requests.

The idea is to encapsulate the stuff you want the server to do for your client in command or action objects instead of using standard service methods. For example, rather than calling a search() method on a remote service, you have a search object that gets sent to the server and the server returns the corresponding result or response object. By using this pattern, you can effectively implement caching, batching, undo/redo, etc. See Ray’s presentation for a bit more info on this.

One ready-made implementation of the pattern for GWT is the gwt-dispatch library. I considered integrating this into the Grails plugin, but its server-side components weren’t really suitable for a Grails project. Anyway, I wanted to write something myself so I could better understand what the implementation should do. The result is the plugin’s new action framework, which you can test out with an intermediate release of the plugin.

Getting started

Using the framework is simplicity itself. Let’s say you want to implement a search action. You first create the appropriate classes for it by running a new Grails command:

grails create-gwt-action org.example.myapp.Search
This will create the following files:

  • src/java/org/example/myapp/client/SearchAction.java
  • src/java/org/example/myapp/client/SearchResponse.java
  • grails-app/actionHandlers/org/example/myapp/SearchActionHandler.groovy

The action and response classes represent the request and response data respectively. Both of them implement Serializable, so they have to have a default constructor (which can be private) and can only contain other serializable data. Note that they are added to the client sub-package of the package you specify, because they are used on the client was well as the server.

The action handler is an instance of a Grails artifact type added by the plugin. Its role is to process actions and return the appropriate responses. It would typically offload the majority of the work to a standard Grails service that could then be used by other code, such as a REST or web services interface.

The code

Update I have updated the plugin packages in the following examples, so “org.grails.” is now just “grails.” The change was made for the final release of version 0.5.

The action object should contain only the information necessary to complete the request. Remember, it’s a data object and typically won’t have any behaviour. In the case of our search action, we might need a query string and the maximum number of results the search should return:

package org.example.myapp.client;

import grails.plugins.gwt.client.Action;

public final class SearchAction implements Action<SearchResponse> {
    private static final long serialVersionUID = 1L;

    private String query;
    
    private SearchAction() {}
    
    public SearchAction(String query) {
        this.query = query;
    }

    public String getQuery() {
        return query;
    }
}

Likewise, the response should only contain the data required by the client:

package org.example.myapp.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import grails.plugins.gwt.client.Response;
    
public class SearchResponse implements Response {
    private static final long serialVersionUID = 1L;
    
    private ArrayList<Long> ids = new ArrayList<Long>();
    
    private SearchResponse() {} 
        
    public SearchResponse(List<Long> ids) {
        this.ids.addAll(ids);
    }
        
    public List<Integer> getIds() {
        return Collections.unmodifiableList(this.ids);
    }
}

All very straightforward so far. The final step is to implement the action handler. As I said, this typically offloads the work to a service and in our example we will make use of a search service:

package org.example.myapp

import org.example.myapp.client.SearchAction
import org.example.myapp.client.SearchResults

class SearchActionHandler {
    SearchService searchService

    SearchResponse execute(SearchAction action) {
        def results = searchService.executeSearch(action.query)
        return new SearchResponse(results)
    }
}   

As you can see, all the action needs to do is unwrap the action and create the response. Everything else is handled by the search service. We haven’t even needed to expose a service via GWT! That’s all you need to do on the server side, which just leaves the question of how you execute an action from the client.

On the client

The plugin comes with a dedicated GWT RPC service that you can use to dispatch all your actions: GwtActionService. All you have to do in your GWT code is create the service, instantiate your action, and then call the execute() method:

...
import grails.plugins.gwt.client.GwtActionService;
import grails.plugins.gwt.client.GwtActionServiceAsync;
...
protected void doSearch(String query) {
    GwtActionServiceAsync service = GWT.create(GwtActionService.class);
    ((ServiceDefTarget) service).setServiceEntryPoint(GWT.getModuleBaseURL() + "rpc");

    service.execute(new SearchAction(query), new AsyncCallback<SearchResponse>() {
        public void onFailure (Throwable caught) {
            ...
        }

        public void onSuccess (GetRecentResponse result) {
            ...
        }
    });
}

You could even wrap the action service with another implementation that does caching and/or batching of commands.

If you use Google Gin, you can simplify your code by having the action service injected into the classes that need it. Simply add something like this to your Gin module definition:

...
import grails.plugins.gwt.client.GwtActionService;
import grails.plugins.gwt.client.GwtActionServiceAsync;

public class MainModule extends AbstractGinModule {
    protected void configure() {
        ...
    }

    @Provides @Singleton
    GwtActionServiceAsync provideGwtActionService() {
      GwtActionServiceAsync service = GWT.create(GwtActionService.class);
      ((ServiceDefTarget) service).setServiceEntryPoint(GWT.getModuleBaseURL() + "rpc");
      return service;   
    }
}

Since GwtActionService is provided by the plugin, you also need to configure your module to inherit from the plugin’s (new) module:

<module>
    ...
    <inherits name="grails.plugins.gwt.Grails"/>
    ...
</module>

I think this is a really clean approach to GWT RPC that reduces the burden on you as a developer. In particular, you no longer have to implement GWT services because you can create simple action handlers instead. Before I implemented this framework, I found that I was creating specific GWT versions of each service. So for example, I had a SearchService and a GwtSearchService, which was pretty inefficient.

I hope you like the new approach!

Internationalising your Grails + GWT applications

The recent 0.4 release of the Grails GWT plugin includes some enhancements in the area of internationalisation (i18n), so now seems like a good time to have a look at how you can add i18n to a Grails/GWT app. This article focuses on the specifics of getting GWT’s i18n support working with Grails, but the GWT website has a useful tutorial if you want more information.

Localising text

Grails and GWT take different approaches to i18n. Both systems are based on properties files with names that follow the usual Java i18n convention for resource bundles, but that’s as far as the similarities go. Grails expects to find the bundles in the grails-app/i18n directory, but GWT looks for them in the module directory structure. With static internationalisation, GWT also requires each property file to have an associated Java interface.

Ideally, you would be able to use the same properties files for both standard GSP pages and GWT code, but the plugin doesn’t support this yet. I don’t even know if it’s possible. Despite that, the plugin does make it easy to get started. Let’s say you have a GWT module org.example.Main that you want to internationalise. The first step is to create the resource bundles that will contain the localised text:

grails create-gwt-i18n org.example.Main
This simple command will generate two files for you:

  • src/gwt/org/example/client/MainConstants.properties
  • src/gwt/org/example/client/MainMessages.properties

The MainConstants.properties file is for basic localised text, whereas MainMessages.properties contains parameterised messages like “Today is {0,date,medium}” (where {0…} is a message parameter). Other than that, both properties files can be treated as standard Java resource bundles.

So how do you access these messages from your GWT code? By creating Java interfaces based on the entries in the properties files and loading the appropriate implementations for those interfaces using GWT’s deferred binding mechanism. It sounds complicated, but in practice it’s pretty straightforward. The plugin provides a Grails command that will perform the first step of creating the appropriate Java interfaces:

grails compile-i18n
Assuming that you have added some enties to the MainConstants.properties and MainMessages.properties files, this command will create

  • src/gwt/org/example/client/MainConstants.java
  • src/gwt/org/example/client/MainMessages.java

In fact, you don’t even need to run this command explicitly because the plugin will run it automatically before compiling the GWT modules.

Both the *Constants and *Messages interfaces contain methods named after the keys in the corresponding properties files. For example, an entry cancelLabel will result in a method cancelLabel(). In the Java world, developers commonly use ‘.’ as a separator in resource bundle keys. You can do this with GWT too, but you end up with underscores in the method names. For example, cancel.label becomes cancel_label(). In other words, the generated methods don’t follow the Java convention. Whether that’s an issue is really down to you.

Now that you have the i18n interfaces, you can start replacing hard-coded text in your GWT UI with localised text. You first need to load the appropriate i18n classes:

public class Main implements EntryPoint {    
    private MainConstants constants = GWT.create(MainConstants.class);
    private MainMessages messages = GWT.create(MainMessages.class);
    ...

You can now call the methods on the constants and messages objects to get the localised text:

public class Main implements EntryPoint {
        ...
        Button saveButton = new Button(constants.save_label());
        Button saveButton = new Button(constants.cancel_label());
        ...
        // Report an error
        RootPanel.get("errorMessage").add(new HTML(messages.msg_upload_fail(filename)));
}

You can also see in the above example how you pass parameters to a message as simple method arguments.

Adding locales

That’s almost all there is to it. Your application will now work with the default locale. To add extra locales, though, requires a few more steps. First off, you need to create the language-specific resource bundles with the translated text. Say we want to display the application in French. We create the files

  • src/gwt/org/example/client/MainConstants_fr.properties
  • src/gwt/org/example/client/MainMessages_fr.properties

and add the French versions of all the messages there. Next, we need to inform GWT of the new locale by adding the following line to the module file:

<module>
    ...
    <!-- Supported languages -->
    <extend-property name="locale" values="fr"/>
</module>

That’s it! Your users can now view the application in French.

Setting the locale

The application is now localised, but how do you pick which locale to display? The simplest approach is to add a “locale=…” query parameter to the application’s URL. GWT picks up that parameter and loads the appropriate resource bundles. Unfortunately, this doesn’t work so well with Grails because it uses a different query parameter: “lang=…”.

Another issue is that you have to add the “locale” query parameter to any internal links so that the correct locale is propagated to the different pages. This is a pretty ugly and error-prone approach.

Have no fear! There is a simple solution. Simply add the following meta tag either to your GSP pages or, even better, your layouts:

<%@ page import="org.springframework.web.servlet.support.RequestContextUtils" %>
<html>
<head>
    ...
    <meta name="gwt:property" content="locale=${RequestContextUtils.getLocale(request)}">
</head>
...
</html>

Not only will this ensure that GWT uses the same locale as Grails, but the locale will also be retained between pages and modules. To change the locale to French, all you have to do is load the application with the query parameter “lang=fr”. Next time you reload the page without the query parameter, it will still be in French! The same when you navigate to a different URL with the application. Now that’s what I call a result.

Have fun internationalising your Grails/GWT apps!

Grails JSecurity Plugin version 0.4 released

I have finally released version 0.4 of the Grails JSecurity Plugin – see the release notes for more details.

This will be the last release under this name because JSecurity was renamed to Apache Shiro. All future work will now be done on the Shiro Plugin. You can already install a 1.0-SNAPSHOT version that is basically the JSecurity Plugin 0.4 rebadged.

Wildcard permissions

The most significant change in version 0.4 is native support for JSecurity’s WildcardPermission. “What’s that?” I hear you cry. A permission in JSecurity serves two purposes:

  1. it is a representation of a right or privilege that is required to access something, such as a document or a printer
  2. it represents one or more rights or privileges that a particular user has

So in order for a user to access a secured resource, his assigned rights must match (or “imply”) those required by the resource.

JSecurity implements permissions via an interface, called unsurprisingly Permission. You can create any type of permission you like, as long as it implements that interface. Objects get a bit clunky, though, when you start dealing with declarative access control. Consider this example access control filter:

import org.jsecurity.grails.JsecBasicPermission

class SecurityFilters {
    def filters = {
        main(controller: "*", action: "*") {
            before = {
                accessControl {
                    permission(new JsecBasicPermission(controllerName, actionName))
                }
            }
        }
    }
}

This example ensures that each controller action requires the user to have a permission specific to the controller name and action name. As I said, it’s clunky.

WildcardPermission is an implementation of the Permission interface that uses a single string to describe an arbitrary permission. The string must follow a certain pattern in order for the permission to work properly, but this is best demonstrated by example. Let’s take the previous example and modify it to use a wildcard permission:

class SecurityFilters {
    def filters = {
        main(controller: "*", action: "*") {
            before = {
                accessControl {
                    permission("$controllerName:$actionName")
                }
            }
        }
    }
}

We have managed to do away with the import and the permission requirement is now a simple string. The important thing to notice is that the controller and action names are separated by a colon, ‘:’. Each substring separated by a colon is called a part. As far as JSecurity and the WildcardPermission implementation are concerned, these parts have no inherent meaning. They don’t know that the first part is a controller name or that the second part is the name of an action. It’s up to the application to give the parts meaning and interpret them.

Of course, I’ve only shown you a permission requirement. How do you assign such a permission to a user? Well, assuming that you are using the default database realm that comes with the plugin, the code you need will look something like this:

class BootStrap {
    def init = { servletContext ->
        ...        
        // Wildcard permissions.
        def wildcardPermission = new JsecPermission(type: "org.jsecurity.authz.permission.WildcardPermission", possibleActions: "*").save()
        new JsecUserPermissionRel(user: user1, permission: wildcardPermission, target: "book:list,show", actions: "*").save()
        new JsecUserPermissionRel(user: user2, permission: wildcardPermission, target: "book:*", actions: "*").save()
        ...
    }
}

As you can see, you must first create an instance of the JsecPermission domain class for WildcardPermission. You can then link this permission to users via the JsecUserPermissionRel domain class. The target contains the permission string, while the actions property is ignored.

If you take a look at the first permission assignment, you’ll see that it allows the first user to access the list and show actions on the book controller. Notice how the assignment includes the names of two actions? These are sub-parts and they are separated by commas. It’s very unusual to see sub-parts in a permission requirement, but they are common in permission assignments like this. The second user has access to all the actions courtesy of the wildcard ‘*’.

In fact, you can have as many parts and sub-parts as you need. For example, we could add an extra part to the above permissions that represented a domain instance ID.

If you want to learn more about the rules that determine whether one permission string implies another, then take a look at the Javadoc for WildcardPermission. That’s all for now folks!

Cropping an image in HTML

Take a look at the image of the Grails in Action book cover in the sidebar. That image has a white border to the right and bottom, but that border is not visible. Don’t believe me? Tough. For those of you who do believe me and want to know how to crop an image, read on.

The original image is 150×188, but to eliminate the white border we need to display 141×176, i.e. cut of the right 9 pixels and the bottom 12. We could use the width and height attributes of the img tag, but that doesn’t achieve what we want: the browser will just scale the image to fit in those dimensions, so the white border will still be visible.

The trick is to wrap the image in a div with the appropriate dimensions:

<div style="width: 141px; height: 176px; overflow: hidden">
  <img src="..." width="150" height="176">
</div>

Voila! The image is cropped! If I learn how to crop the left and top as well, I’ll update the post.

Are polyglot systems a good idea?

A recent tweet pointed me to a post on polyglotism by Bill Burke of JBoss. It comes in the midst of a lot of interest in alternative languages on the JVM, such as JRuby, Groovy, Scala, and many others. Its basic point is that companies indulge in multiple languages at their peril and a Java shop should really stick to Java. His view struck me as over the top, but a little reflection made me realise that software teams should take on board his message or risk some serious long term problems.

Now, I’m not a dyed-in-the-wool Java developer who believes Java is the solution to all problems. In fact, I like a profusion of languages on the JVM. Variety is the spice of life as they say. A competitive field ensures that only the strongest survive, and without new languages we would probably still be stuck with C or even assembly language. I want to see new languages that improve my productivity as a developer, enable me to write more reliable code, or simplify the code I write. Even better are languages that give me all three.

So why am I echoing Bill’s warning? Because there is a difference between having a vibrant ecosystem of competing and complementary languages and actually using many of them in a single software project, team, or even company. Here are some of the things you should consider:

Language libraries

Almost every language comes with its own class or function library these days. That’s often the case even when a language runs on a virtual machine such as the JVM or .Net’s CLR. Look at JRuby and Scala: they both run on the JVM but have their own class libraries. So if you use more than one language in a project, you’ll have to know all the various libraries pretty well too.

Context switching

It’s not uncommon to have both Groovy and Java files in a Grails project and developers often have to work in both languages to implement features or fix bugs. That means developers have to switch contexts when they move from one type of file to the other. Even with languages as close in syntax as Groovy and Java, this can cause errors to creep in, for example when you try to iterate over a list in Java using the each() method. Imagine mixing Java and JRuby, where you have different class libraries as well as wildly different syntax.

Certainly a good developer can manage this, and if he or she switches between languages frequently, the cost in time and mistakes will dwindle. But can you guarantee that a developer will always be working in all the required languages at any given time?

Other developers

Just because you can pick up a new language and be proficient with it in a few weeks, that doesn’t mean everyone will be able to do that. If you have a team, you have to take into account the other team members. Realise that some will have trouble learning new concepts, such as functional programming or dynamic languages. Don’t forget as well that using non-mainstream languages shrinks the pool of developers you can recruit from.

It takes time

So, you got the Hello World example up and running followed by the Fibonacci sequence. Great! It only took you a few minutes! Then what? Learning the basics of a language can often be fairly simple, but to become proficient takes time and you have to use it on a regular basis. Can you really afford that time for all the team members on a critical project?

When you leave

As Bill pointed out, development teams don’t always stick together. What happens when you leave? The company is potentially left with a hole they can’t fill because there aren’t any free developers that know all the languages you put into the system.

Builds

Last but not least, not all languages play nicely together in a single build. How much effort do you really want to put into making different languages fit into your build system? If it’s not much trouble, then great, but otherwise you could end up with an ongoing maintenance headache.

I don’t mean to dismiss the idea of polyglot projects or systems – a new language may provide real benefits that outweigh the problems. Just make sure that a decision is based on a decent risk assessment or back of an envelope cost-benefit analysis rather than a “hey, that language looks cool, let’s try it out” impulse. Of course, feel free to play around and try new things when you’re working on personal projects!