Mostly Grails tips from Code Panda

Editing Resources in Maven with GMaven and Groovy Templates

In this post, I will show how to build a simple yet robust resource modification engine for Maven using GMaven and Groovy Templates.

We sometimes need to generate files in our build cycle that are specific to each server and change per deployment cycle. For some projects, this might be Flash / Flex actionscript files that need to reference the build server. For others, it might be datasource locations that change per build project. While maven provides a built-in resource filtering mechanism, it is tied to parts of the maven lifecycle that might not work well for all projects, and mostly changes resources for War files.

Groovy provides a very robust Templating engine. With the introduction of the GMaven plugin, it becomes possible to filter and re-write resource files using this robust mechanism. Combined with the power of Maven’s built-in profiles mechanism, this solution provides a robust and powerful way to edit Flex / Grails and other resources.

For our project, we needed to generate an actionscript file that tells our Flash files which server to connect to. Of course, this changes in every deployment location, and we needed a way to manage this. A naive way would be to check out the files from SVN and then modify them, but this can lead to unmodified errors and all sorts of issues. Ideally, we wanted it added to our maven buildcycle.

Here is our solution:

1. Add template handling to our Maven pom file.

We created a goal in Gmaven that processes templates within our build-templates directory. This can be overwritten in any build.

Notice how we can define a activeByDefault profile so that if a profile is not specified, we can still generate files with default values.

3. define our template files.

A template file is simply a delimited groovy string ( i.e. // for / ) that lives inside the build-templates folder. Any parameter that needs to be replaced will be in the form $server_url, which is defined within the binding part of the pom file.

For example, we created a file Environment.as used by our Flex files to refer to this server, this file will go into the build-templates directory and look like this: