You are on page 1of 391

Table of contents

See the light - agile, industrial strength, rapid web application development made easy

The Grails Framework - Reference Documentation


Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith Version: 2.1.0

Table of Contents
1 Introduction 1.1 What's new in Grails 2.1? 1.2 What's new in Grails 2.0? 1.2.1 Development Environment Features 1.2.2 Core Features 1.2.3 Web Features 1.2.4 Persistence Features 1.2.5 Testing Features 2 Getting Started 2.1 Installation Requirements 2.2 Downloading and Installing 2.3 Creating an Application 2.4 A Hello World Example 2.5 Using Interactive Mode 2.6 Getting Set Up in an IDE 2.7 Convention over Configuration 2.8 Running an Application 2.9 Testing an Application 2.10 Deploying an Application 2.11 Supported Java EE Containers 2.12 Generating an Application 2.13 Creating Artefacts 3 Upgrading from previous versions of Grails 4 Configuration 4.1 Basic Configuration 4.1.1 Built in options 4.1.2 Logging 4.1.3 GORM 4.2 Environments 4.3 The DataSource 4.3.1 DataSources and Environments 4.3.2 JNDI DataSources 2

4.3.3 Automatic Database Migration 4.3.4 Transaction-aware DataSource Proxy 4.3.5 Database Console 4.3.6 Multiple Datasources 4.4 Externalized Configuration 4.5 Versioning 4.6 Project Documentation 4.7 Dependency Resolution 4.7.1 Configurations and Dependencies 4.7.2 Dependency Repositories 4.7.3 Debugging Resolution 4.7.4 Inherited Dependencies 4.7.5 Providing Default Dependencies 4.7.6 Snapshots and Other Changing Dependencies 4.7.7 Dependency Reports 4.7.8 Plugin JAR Dependencies 4.7.9 Maven Integration 4.7.10 Deploying to a Maven Repository 4.7.11 Plugin Dependencies 4.7.12 Caching of Dependency Resolution Results 5 The Command Line 5.1 Interactive Mode 5.2 Creating Gant Scripts 5.3 Re-using Grails scripts 5.4 Hooking into Events 5.5 Customising the build 5.6 Ant and Maven 5.7 Grails Wrapper 6 Object Relational Mapping (GORM) 6.1 Quick Start Guide 6.1.1 Basic CRUD 6.2 Domain Modelling in GORM 6.2.1 Association in GORM 6.2.1.1 Many-to-one and one-to-one 6.2.1.2 One-to-many 6.2.1.3 Many-to-many 6.2.1.4 Basic Collection Types 3

6.2.2 Composition in GORM 6.2.3 Inheritance in GORM 6.2.4 Sets, Lists and Maps 6.3 Persistence Basics 6.3.1 Saving and Updating 6.3.2 Deleting Objects 6.3.3 Understanding Cascading Updates and Deletes 6.3.4 Eager and Lazy Fetching 6.3.5 Pessimistic and Optimistic Locking 6.3.6 Modification Checking 6.4 Querying with GORM 6.4.1 Dynamic Finders 6.4.2 Where Queries 6.4.3 Criteria 6.4.4 Detached Criteria 6.4.5 Hibernate Query Language (HQL) 6.5 Advanced GORM Features 6.5.1 Events and Auto Timestamping 6.5.2 Custom ORM Mapping 6.5.2.1 Table and Column Names 6.5.2.2 Caching Strategy 6.5.2.3 Inheritance Strategies 6.5.2.4 Custom Database Identity 6.5.2.5 Composite Primary Keys 6.5.2.6 Database Indices 6.5.2.7 Optimistic Locking and Versioning 6.5.2.8 Eager and Lazy Fetching 6.5.2.9 Custom Cascade Behaviour 6.5.2.10 Custom Hibernate Types 6.5.2.11 Derived Properties 6.5.2.12 Custom Naming Strategy 6.5.3 Default Sort Order 6.6 Programmatic Transactions 6.7 GORM and Constraints 7 The Web Layer 7.1 Controllers 7.1.1 Understanding Controllers and Actions 4

7.1.2 Controllers and Scopes 7.1.3 Models and Views 7.1.4 Redirects and Chaining 7.1.5 Controller Interceptors 7.1.6 Data Binding 7.1.7 XML and JSON Responses 7.1.8 More on JSONBuilder 7.1.9 Uploading Files 7.1.10 Command Objects 7.1.11 Handling Duplicate Form Submissions 7.1.12 Simple Type Converters 7.1.13 Asynchronous Request Processing 7.2 Groovy Server Pages 7.2.1 GSP Basics 7.2.1.1 Variables and Scopes 7.2.1.2 Logic and Iteration 7.2.1.3 Page Directives 7.2.1.4 Expressions 7.2.2 GSP Tags 7.2.2.1 Variables and Scopes 7.2.2.2 Logic and Iteration 7.2.2.3 Search and Filtering 7.2.2.4 Links and Resources 7.2.2.5 Forms and Fields 7.2.2.6 Tags as Method Calls 7.2.3 Views and Templates 7.2.4 Layouts with Sitemesh 7.2.5 Static Resources 7.2.5.1 Including resources using the resource tags 7.2.5.2 Other resource tags 7.2.5.3 Declaring resources 7.2.5.4 Overriding plugin resources 7.2.5.5 Optimizing your resources 7.2.5.6 Debugging 7.2.5.7 Preventing processing of resources 7.2.5.8 Other Resources-aware plugins 7.2.6 Sitemesh Content Blocks 5

7.2.7 Making Changes to a Deployed Application 7.2.8 GSP Debugging 7.3 Tag Libraries 7.3.1 Variables and Scopes 7.3.2 Simple Tags 7.3.3 Logical Tags 7.3.4 Iterative Tags 7.3.5 Tag Namespaces 7.3.6 Using JSP Tag Libraries 7.3.7 Tag return value 7.4 URL Mappings 7.4.1 Mapping to Controllers and Actions 7.4.2 Embedded Variables 7.4.3 Mapping to Views 7.4.4 Mapping to Response Codes 7.4.5 Mapping to HTTP methods 7.4.6 Mapping Wildcards 7.4.7 Automatic Link Re-Writing 7.4.8 Applying Constraints 7.4.9 Named URL Mappings 7.4.10 Customizing URL Formats 7.5 Web Flow 7.5.1 Start and End States 7.5.2 Action States and View States 7.5.3 Flow Execution Events 7.5.4 Flow Scopes 7.5.5 Data Binding and Validation 7.5.6 Subflows and Conversations 7.6 Filters 7.6.1 Applying Filters 7.6.2 Filter Types 7.6.3 Variables and Scopes 7.6.4 Filter Dependencies 7.7 Ajax 7.7.1 Ajax Support 7.7.1.1 Remoting Linking 7.7.1.2 Updating Content 6

7.7.1.3 Remote Form Submission 7.7.1.4 Ajax Events 7.7.2 Ajax with Prototype 7.7.3 Ajax with Dojo 7.7.4 Ajax with GWT 7.7.5 Ajax on the Server 7.8 Content Negotiation 8 Validation 8.1 Declaring Constraints 8.2 Validating Constraints 8.3 Sharing Constraints Between Classes 8.4 Validation on the Client 8.5 Validation and Internationalization 8.6 Applying Validation to Other Classes 9 The Service Layer 9.1 Declarative Transactions 9.1.1 Transactions Rollback and the Session 9.2 Scoped Services 9.3 Dependency Injection and Services 9.4 Using Services from Java 10 Testing 10.1 Unit Testing 10.1.1 Unit Testing Controllers 10.1.2 Unit Testing Tag Libraries 10.1.3 Unit Testing Domains 10.1.4 Unit Testing Filters 10.1.5 Unit Testing URL Mappings 10.1.6 Mocking Collaborators 10.1.7 Mocking Codecs 10.2 Integration Testing 10.3 Functional Testing 11 Internationalization 11.1 Understanding Message Bundles 11.2 Changing Locales 11.3 Reading Messages 11.4 Scaffolding and i18n 12 Security 7

12.1 Securing Against Attacks 12.2 Encoding and Decoding Objects 12.3 Authentication 12.4 Security Plugins 12.4.1 Spring Security 12.4.2 Shiro 13 Plugins 13.1 Creating and Installing Plugins 13.2 Plugin Repositories 13.3 Understanding a Plugin's Structure 13.4 Providing Basic Artefacts 13.5 Evaluating Conventions 13.6 Hooking into Build Events 13.7 Hooking into Runtime Configuration 13.8 Adding Dynamic Methods at Runtime 13.9 Participating in Auto Reload Events 13.10 Understanding Plugin Load Order 13.11 The Artefact API 13.11.1 Asking About Available Artefacts 13.11.2 Adding Your Own Artefact Types 13.12 Binary Plugins 14 Web Services 14.1 REST 14.2 SOAP 14.3 RSS and Atom 15 Grails and Spring 15.1 The Underpinnings of Grails 15.2 Configuring Additional Beans 15.3 Runtime Spring with the Beans DSL 15.4 The BeanBuilder DSL Explained 15.5 Property Placeholder Configuration 15.6 Property Override Configuration 16 Grails and Hibernate 16.1 Using Hibernate XML Mapping Files 16.2 Mapping with Hibernate Annotations 16.3 Adding Constraints 17 Scaffolding 8

18 Deployment 19 Contributing to Grails 19.1 Report Issues in JIRA 19.2 Build From Source and Run Tests 19.3 Submit Patches to Grails Core 19.4 Submit Patches to Grails Documentation

1 Introduction

Java web development as it stands today is dramatically more complicated than it needs to be. Most modern w Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles.

Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of applications. Grails builds on these concepts and dramatically reduces the complexity of building web appl platform. What makes it different, however, is that it does so by building on already established Java technolo Hibernate.

Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the its associated plugins. Included out the box are things like: An easy to use Object Relational Mapping (ORM) layer built on Hibernate An expressive view technology called Groovy Server Pages (GSP) A controller layer built on Spring MVC A command line scripting environment built on the Groovy-powered Gant An embedded Tomcat container which is configured for on the fly reloading Dependency injection with the inbuilt Spring container Support for internationalization (i18n) built on Spring's core MessageSource concept A transactional service layer built on Spring's transaction abstraction

All of these are made easy to use through the power of the Groovy language and the extensive use of Domain (DSLs)

This documentation will take you through getting started with Grails and building web applications with the Grails

1.1 What's new in Grails 2.1?


Maven Improvements / Multi Module Build Support

Grails' Maven support has been improved in a number of significant ways. Firstly it is now possible to specify pom.xml file:
<dependency> <groupId>org.grails.plugins</groupId> <artifactId>hibernate</artifactId> <version>2.1.0.RC1</version> <type>zip</type> <scope>compile</scope> </dependency>

The Maven plugin now resolves plugins as well as jar dependencies (previously jar dependencies were resolved b by Ivy). Ivy is completely disabled leaving all dependency resolution up to Maven ensuring that evictions work as

There is also a new Grails create-multi-project-build script which features initial support for Maven future release). This script can be run from a parent directory containing Grails applications and plugins and it w multi-module build.

10

Enabling Maven in a project has been made easier with the inclusion of the create-pom command:
grails create-app myapp cd myapp grails create-pom com.mycompany mvn package

To create a multi-module Maven build follow these steps:


grails create-app myapp grails create-plugin plugin-a grails create-plugin plugin-b grails create-multi-project-build com.mycompany:parent:1.0-SNAPSHOT mvn install

Grails Wrapper

The Grails Wrapper allows a Grails application to build without having to install Grails and configure a GRAILS_ variable. The wrapper includes a small shell script and a couple of small bootstrap jar files that typically would be code control along with the rest of the project. The first time the wrapper is executed it will download an installation. This wrapper makes it more simple to setup a development environment, configure CI and manag versions of Grails. When the application is upgraded to the next version of Grails, the wrapper is updated and che code control system and the next time developers update their workspace and run the wrapper, they will autom correct version of Grails. See the Wrapper Documentation for more details.

Debug Option

The grails command now supports a -debug option which will startup the remote debug agent. This behavio by the grails-debug command. grails-debug is still available but is deprecated and may be removed from
grails -debug run-app

Grails Command Aliases


The alias command may be used to define aliases for grails commands. The following command creates an alias named rit (short for "run integration tests"):
grails alias rit test-app integration:

See the alias docs for more info.

Cache Plugin

11

Grails 2.1 installs the cache plugin by default. This plugin provides powerful and easy to use cache functionalit plugins. The main plugin provides basic map backed caching support. For more robust caching options one o plugins should be installed and configured. See the cache-redis docs and the cache-ehcache docs for details. See the main plugin documentation for details on how to configure and use the plugin.

1.2 What's new in Grails 2.0?

This section covers the new features that are present in 2.0 and is broken down into sections covering the build s web tier, persistence enhancements and improvements in testing. Note there are many more small enhancement these sections just cover some of the highlights.

1.2.1 Development Environment Features


Interactive Mode and Console Enhancements
Grails 2.0 features brand new console output that is more concise and user friendly to consume. An example of running tests can be seen below:

In general Grails makes its best effort to display update information on a single line and only present the inform This means that while in previous versions of Grails the war command produced many lines of output, in Gra output is produced:

12

In addition simply typing 'grails' at the command line activates the new interactive mode which features TAB c history and keeps the JVM running to ensure commands execute much quicker than otherwise

13

For more information on the new features of the console refer to the section of the user guide that covers the co mode.

Reloading Agent

Grails 2.0 reloading mechanism no longer uses class loaders, but instead uses a JVM agent to reload changes to c in greatly improved reliability when reloading changes and also ensures that the class files stored in disk remai class files loaded in memory, which reduces the need to run the clean command.

New Test Report and Documentation Templates

There are new templates for displaying test results that are clearer and more user friendly than the previous reports

In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails a documentation:

See the section on the documentation engine for more usage info.

14

Use a TOC for Project Docs

The old documentation engine relied on you putting section numbers into the gdoc filenames. Although conve made it difficult to restructure your user guide by inserting new chapters and sections. In addition, any such restr of section titles resulted in breaking changes to the URLs.

You can now use logical names for your gdoc files and define the structure and section titles in a YAML tabl described in the section on the documentation engine. The logical names appear in the URLs, so as long as yo your URLs will always remain the same no matter how much restructuring or changing of titles you do. Grails 2.0 even provides a migrate-docs command to aid you in migrating existing gdoc user guides.

Enhanced Error Reporting and Diagnosis

Error reporting and problem diagnosis has been greatly improved with a new errors view that analyses stack t displays problem areas in your code:

In addition stack trace filtering has been further enhanced to display only relevant trace information: 15

Line | Method ->> 9 | getValue in - - - - - - - - - - - - | 7 | getBookValue in | 886 | runTask . . in | 908 | run in ^ 662 | run . . . . in

Book.groovy - - - - - - - - - - - BookService.groovy ThreadPoolExecutor.java '' Thread.java

H2 Database and Console

Grails 2.0 now uses the H2 database instead of HSQLDB, and enables the H2 database console in developme /dbconsole) so that the in-memory database can be easily queried from the browser:

Plugin Usage Tracking


To enhance community awareness of the most popular plugins an opt-in plugin usage tracking system has been can participate in providing feedback to the plugin community on which plugins are most popular.

This will help drive the roadmap and increase support of key plugins while reducing the need to support older or thus helping plugin development teams focus their efforts.

Dependency Resolution Improvements


There are numerous improvements to dependency resolution handling via Ivy including:

16

Grails now makes a best effort to cache the previous resolve and avoid resolving again u BuildConfig.groovy.

Plugins dependencies now appear in the dependency report generated by grails dependency-report Plugins published with the release plugin now publish their transitive plugin dependencies in the generated resolved. It is now possible to customize the ivy cache directory via BuildConfig.groovy

grails.project.dependency.resolution = { cacheDir "target/ivy-cache" }

You can change the ivy cache directory for all projects via settings.groovy

grails.dependency.cache.dir = "${userHome}/.ivy2/cache"

It is now possible to completely disable resolution from inherited repositories (repositories defined by other p

grails.project.dependency.resolution = { repositories { inherits false // Whether to inherit repository definitions from plugins } }

It is now possible to easily disable checksum validation errors:

grails.project.dependency.resolution = { checksums false // whether to verify checksums or not }

1.2.2 Core Features


Binary Plugins

Grails plugins can now be packaged as JAR files and published to standard maven repositories. This even work resources (with resources plugin 1.0.1). See the section on Binary plugins for more information.

Groovy 1.8
Grails 2.0 comes with Groovy 1.8 which includes many new features and enhancements

Spring 3.1 Profile Support


17

Grails' existing environment support has been bridged into the Spring 3.1 profile support. For example when ru Grails environment called "production", a Spring profile of "production" is activated so that you can use Spring APIs to configure beans for a specific profile.

1.2.3 Web Features


Controller Actions as Methods

It is now possible to define controller actions as methods instead of using closures as in previous versions of Grai the preferred way of expressing an action. For example:
// action as a method def index() { } // action as a closure def index = { }

Binding Primitive Method Action Arguments

It is now possible to bind form parameters to action arguments where the name of the form element matches the example given the following form:
<g:form name="myForm" action="save"> <input name="name" /> <input name="age" /> </g:form>

You can define an action that declares arguments for each input and automatically converts the parameters to the a
def save(String name, int age) { // remaining }

Static Resource Abstraction

A new static resource abstraction is included that allows declarative handling of JavaScript, CSS and image automatic ordering, compression, caching and gzip handling.

Servlet 3.0 Async Features


Grails now supports Servlet 3.0 including the Asynchronous programming model defined by the specification:

18

def index() { def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } }

Link Generation API

A general purpose LinkGenerator class is now available that is usable anywhere within a Grails application a context of a controller. For example if you need to generate links in a service or an asynchronous background job request:
LinkGenerator grailsLinkGenerator def generateLink() { grailsLinkGenerator.link(controller:"book", action:"list") }

Page Rendering API

Like the LinkGenerator the new PageRenderer can be used to render GSP pages outside the scope of a w a scheduled job or web service. The PageRenderer class features a very similar API to the render m controllers:
grails.gsp.PageRenderer groovyPageRenderer

void welcomeUser(User user) { def contents = groovyPageRenderer.render(view:"/emails/welcomeLetter", model:[user: sendEmail { to user.email body contents } }

The PageRenderer service also allows you to pre-process GSPs into HTML templates:
new File("/path/to/welcome.html").withWriter { w -> groovyPageRenderer.renderTo(view:"/page/content", w) }

Filter Exclusions

Filters may now express controller, action and uri exclusions to offer more options for expressing to which requ should be applied.

19

filter1(actionExclude: 'log*') { before = { // } } filter2(controllerExclude: 'auth') { before = { // } } filter3(uriExclude: '/secure*') { before = { // } }

Performance Improvements

Performance of GSP page rendering has once again been improved by optimizing the GSP compiler to inline possible.

HTML5 Scaffolding
There is a new HTML5-based scaffolding UI:

jQuery by Default

The jQuery plugin is now the default JavaScript library installed into a Grails application. For backwards com plugin is available. Refer to the documentation on the Prototype plugin for installation instructions.

Easy Date Parsing


A new date method has been added to the params object to allow easy, null-safe parsing of dates: 20

def val = params.date('myDate', 'dd-MM-yyyy') // or a list for formats def val = params.date('myDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd']) // or the format read from messages.properties via the key 'date.myDate.format' def val = params.date('myDate')

Customizable URL Formats

The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessi addNumbers in a controller named MathHelperController would be something like /mathHelper/a allows for the customization of this pattern and provides an implementation which replaces the camel cas hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated of "hyphenated" to the grails.web.url.converter property in grails-app/conf/Config.groovy
// grails-app/conf/Config.groovy grails.web.url.converter = 'hyphenated'

Arbitrary strategies may be plugged in by providing a class which implements the UrlConverter interface and a that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NA bean in the context with that name, it will be used as the default converter and there is no need to ass grails.web.url.converter config property.
// src/groovy/com/myapplication/MyUrlConverterImpl.groovy package com.myapplication class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) { // return some representation of a property or class name that should be used i } }

// grails-app/conf/spring/resources.groovy beans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }

Web Flow input and output

It is now possible to provide input arguments when calling a subflow. Flows can also return output values that ca flow.

1.2.4 Persistence Features


The GORM API
21

The GORM API has been formalized into a set of classes (GormStaticApi, GormInstanceApi and Gorm that get statically wired into every domain class at the byte code level. The result is better code completion for ID with Java and the potential for more GORM implementations for other types of data stores.

Detached Criteria and Where Queries

Grails 2.0 features support for DetachedCriteria which are criteria queries that are not associated with any sessi thus can be more easily reused and composed:
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def results = criteria.list(max:4, sort:"firstName")

To support the addition of DetachedCriteria queries and encourage their use a new where method and DSL ha greatly reduce the complexity of criteria queries:
def query = Person.where { (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9) } def results = query.list(sort:"firstName")

See the documentation on DetachedCriteria and Where Queries for more information.

New findOrCreate and findOrSave Methods

Domain classes have support for the findOrCreateWhere, findOrSaveWhere, findOrCreateBy and findOrSaveBy behave just like findWhere and findBy methods except that they should never return null. If a matching instance c database then a new instance is created, populated with values represented in the query parameters and retu findOrSaveWhere and findOrSaveBy, the instance is saved before being returned.
def book Galaxy") def book def book def book

= Book.findOrCreateWhere(author: 'Douglas Adams', title: "The Hitchiker's Guid = Book.findOrSaveWhere(author: 'Daniel Suarez', title: 'Daemon') = Book.findOrCreateByAuthorAndTitle('Daniel Suarez', 'Daemon') = Book.findOrSaveByAuthorAndTitle('Daniel Suarez', 'Daemon')

Abstract Inheritance

GORM now supports abstract inheritance trees which means you can define queries and associations linking to ab

22

abstract class Media { String title } class Book extends Media { } class Album extends Media { } class Account { static hasMany = [purchasedMedia:Media] } .. def allMedia = Media.list()

Multiple Data Sources Support

It is now possible to define multiple datasources in DataSource.groovy and declare one or more datasource uses by default:
class ZipCode { String code static mapping = { datasource 'ZIP_CODES' } }

If multiple datasources are specified for a domain then you can use the name of a particular datasource as a name regular GORM method:
def zipCode = ZipCode.auditing.get(42)

For more information see the section on Multiple Data Sources in the user guide.

Database Migrations

A new database migration plugin has been designed and built for Grails 2.0 allowing you to apply migrations to yo changes and diff your domain model with the current state of the database.

Database Reverse Engineering


A new database reverse engineering plugin has been designed and built for Grails 2.0 that allows you to generate an existing database schema.

Hibernate 3.6
Grails 2.0 is now built on Hibernate 3.6

23

Bag Collections

You can now use Hibernate Bags for mapped collections to avoid the memory and performance issues of loadin enforce Set uniqueness or List order. For more information see the section on Sets, Lists and Maps in the user guide.

1.2.5 Testing Features


New Unit Testing Console Output
Test output from the test-app command has been improved:

New Unit Testing API

There is a new unit testing API based on mixins that supports JUnit 3, 4 and Spock style tests (with Spock 0.6 and

24

import grails.test.mixin.TestFor @TestFor(SimpleController) class SimpleControllerTests void testIndex() { controller.home() {

assert view == "/simple/homePage" assert model.title == "Hello World" } }

The documentation on testing has also been re-written around this new framework.

Unit Testing GORM

A new in-memory GORM implementation is present that supports many more features of the GORM API m criteria queries, named queries and other previously unsupported methods possible.

Faster Unit Testing with Interactive Mode

The new interactive mode (activated by typing 'grails') greatly improves the execution time of running unit and int

Unit Test Scaffolding


A unit test is now generated for scaffolded controllers

25

2 Getting Started
2.1 Installation Requirements

Before installing Grails you will need as a minimum a Java Development Kit (JDK) installed version 1.6 or a appropriate JDK for your operating system, run the installer, and then set up an environment variable called JAV the location of this installation. If you're unsure how to do this, we recommend the video installation guides from g Windows Linux Mac OS X These will show you how to install Grails too, not just the JDK.

On some platforms (for example OS X) the Java installation is automatically detected. However in many ca manually configure the location of Java. For example:
export JAVA_HOME=/Library/Java/Home export PATH="$PATH:$JAVA_HOME/bin"

if you're using bash or another variant of the Bourne Shell.

2.2 Downloading and Installing


The first step to getting up and running with Grails is to install the distribution. To do so follow these steps: Download a binary distribution of Grails and extract the resulting zip file to a location of your choice Set the GRAILS_HOME environment variable to the location where you extracted the zip On Unix/Linux based systems this is typically a matter of adding something like the GRAILS_HOME=/path/to/grails to your profile On Windows this is typically a matter Computer/Advanced/Environment Variables Then add the bin directory to your PATH variable: of setting an environment

var

On Unix/Linux based systems this can be done by adding export PATH="$PATH:$GRAILS_H profile On Windows this is done by modifying Computer/Advanced/Environment Variables the Path environment

vari

If Grails is working correctly you should now be able to type grails -version in the terminal window and this:

Grails version: 2.0.0

26

2.3 Creating an Application


To create a Grails application you first need to familiarize yourself with the usage of the grails command following manner:
grails [command name]

Run create-app to create an application:

grails create-app helloworld

This will create a new directory inside the current one that contains the project. Navigate to this directory in your c
cd helloworld

2.4 A Hello World Example

Let's now take the new project and turn it into the classic "Hello world!" example. First, change into the "hellowor created and start the Grails interactive console:

$ cd helloworld $ grails

You should see a prompt that looks like this:

What we want is a simple page that just prints the message "Hello World!" to the browser. In Grails, whenever you just create a new controller action for it. Since we don't yet have a controller, let's create one now with command:

grails> create-controller hello

27

Don't forget that in the interactive console, we have auto-completion on command names. So you can type "cre" to get a list of all create-* commands. Type a few more letters of the command name and then <tab> again to f

The above command will create a new controller in the grails-app/controllers/helloworl HelloController.groovy. Why the extra helloworld directory? Because in Java land, it's strongly r classes are placed into packages, so Grails defaults to the application name if you don't provide one. The create-controller provides more detail on this. We now have a controller so let's add an action to generate the "Hello World!" page. The code looks like this:
package helloworld class HelloController { def index() { render "Hello World!" } }

The action is simply a method. In this particular case, it calls a special method provided by Grails to render the pag

Job done. To see your application in action, you just need to start up a server with another command called run-ap

grails> run-app

This will start an embedded server on port 8080 that hosts your application. You should now be able to access y URL http://localhost:8080/helloworld/ - try it!

If you see the error "Server failed to start for port 8080: Address already in use", then it means a server is running on that port. You can easily work around this by running your server on a differe using -Dserver.port=9090 run-app. '9090' is just an example: you can pretty much anything within the range 1024 to 49151. The result will look something like this:

28

This is the Grails intro page which is rendered by the grails-app/view/index.gsp file. It detects t controllers and provides links to them. You can click on the "HelloController" link to see our custom page conta World!". Voila! You have your first working Grails application.

One final thing: a controller can contain many actions, each of which corresponds to a different page (ignoring Each page is accessible via a unique URL that is composed from the controller name and /<appname>/<controller>/<action>. This means you can access the Hello World page via /helloworld/hello/inde controller name (remove the 'Controller' suffix from the class name and lower-case the first letter) and 'index' is you can also access the page via the same URL without the action name: this is because 'index' is the default actio controllers and actions section of the user guide to find out more on default actions.

2.5 Using Interactive Mode


Grails 2.0 features an interactive mode which makes command execution faster since the JVM doesn't have to command. To use interactive mode simple type 'grails' from the root of any projects and use TAB completion to commands. See the screenshot below for an example:

For more information on the capabilities of interactive mode refer to the section on Interactive Mode in the user gu

2.6 Getting Set Up in an IDE


IntelliJ IDEA

IntelliJ IDEA and the JetGroovy plugin offer good support for Groovy and Grails developers. Refer to the se Grails support on the JetBrains website for a feature overview.

IntelliJ IDEA comes in two flavours; the open source "Community Edition" and the commercial "Ultimate E support for Groovy, but only Ultimate Edition offers Grails support. 29

With Ultimate Edition, there is no need to use the grails integrate-with --intellij command, understands Grails projects natively. Just open the project with File -> New Project -> Create existing sources.

You can still use Community Edition for Grails development, but you will miss out on all the Grails specific fe classpath management, GSP editor and quick access to Grails commands. To integrate Grails with Commu following command to generate appropriate project files:
grails integrate-with --intellij

Eclipse

We recommend that users of Eclipse looking to develop Grails application take a look at SpringSource Tool Suite support for Grails including automatic classpath management, a GSP editor and quick access to Grails com Integration page for an overview.

NetBeans

NetBeans provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the applications in the IDE, code completion and integration with the Glassfish server. For an overview of featur Integration guide on the Grails website which was written by the NetBeans team.

TextMate

Since Grails' focus is on simplicity it is often possible to utilize more simple editors and TextMate on the M Groovy/Grails bundle available from the Texmate bundles SVN. To integrate Grails with TextMate run the following command to generate appropriate project files:
grails integrate-with --textmate

Alternatively TextMate can easily open any project with its command line integration by issuing the following co of your project:
mate .

2.7 Convention over Configuration

Grails uses "convention over configuration" to configure itself. This typically means that the name and location o of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails. Here is a breakdown and links to the relevant sections:

30

grails-app - top level directory for Groovy sources conf - Configuration sources. controllers - Web controllers - The C in MVC. domain - The application domain. i18n - Support for internationalization (i18n). services - The service layer. taglib - Tag libraries. utils - Grails specific utilities. views - Groovy Server Pages - The V in MVC. scripts - Gant scripts. src - Supporting sources groovy - Other Groovy sources java - Other Java sources test - Unit and integration tests.

2.8 Running an Application

Grails applications can be run with the built in Tomcat server using the run-app command which will load a se default:
grails run-app

You can specify a different port by using the server.port argument:


grails -Dserver.port=8090 run-app

Note that it is better to start up the application in interactive mode since a container restart is much quicker:
$ grails grails> run-app | Server running. Browse to http://localhost:8080/helloworld | Application loaded in interactive mode. Type 'exit' to shutdown. | Downloading: plugins-list.xml grails> exit | Stopping Grails server grails> run-app | Server running. Browse to http://localhost:8080/helloworld | Application loaded in interactive mode. Type 'exit' to shutdown. | Downloading: plugins-list.xml

31

More information on the run-app command can be found in the reference guide.

2.9 Testing an Application

The create-* commands in Grails automatically create unit or integration tests for you within th test/integration directory. It is of course up to you to populate these tests with valid test logic, informa found in the section on Testing. To execute tests you run the test-app command as follows:
grails test-app

2.10 Deploying an Application

Grails applications are deployed as Web Application Archives (WAR files), and Grails includes the war comman task:
grails war

This will produce a WAR file under the target directory which can then be deployed as per your container's ins Unlike most scripts which default to the development environment unless overridden, the war command runs environment by default. You can override this like any script by specifying the environment name, for example:
grails dev war

NEVER deploy Grails using the run-app command as this command sets Grails up for auto-reloa runtime which has a severe performance and scalability implications

When deploying Grails you should always run your containers JVM with the -server option and with sufficien A good set of VM flags would be:
-server -Xmx512M -XX:MaxPermSize=256m

2.11 Supported Java EE Containers

Grails runs on any container that supports Servlet 2.5 and above and is known to work on the following specific co

32

Tomcat 7 Tomcat 6 SpringSource tc Server Eclipse Virgo GlassFish 3 GlassFish 2 Resin 4 Resin 3 JBoss 6 JBoss 5 Jetty 7 Jetty 6 IBM Websphere 7.0 IBM Websphere 6.1 Oracle Weblogic 10.3 Oracle Weblogic 10 Oracle Weblogic 9

Some containers have bugs however, which in most cases can be worked around. A list of known deployment is the Grails wiki.

2.12 Generating an Application

To get started quickly with Grails it is often useful to use a feature called Scaffolding to generate the skeleton of this use one of the generate-* commands such as generate-all, which will generate a controller (and its unit tes views:
grails generate-all Book

2.13 Creating Artefacts

Grails ships with a few convenience targets such as create-controller, create-domain-class and so on that will c different artefact types for you.

These are just for your convenience and you can just as easily use an IDE or your favourite text editor For example to create the basis of an application you typically need a domain model:
grails create-domain-class book

33

This will result in the creation of a domain class at grails-app/domain/Book.groovy such as:
class Book { }

There are many such create-* commands that can be explored in the command line reference guide.

To decrease the amount of time it takes to run Grails scripts, use the interactive mode.

34

3 Upgrading from previous versions of Grails

Although the Grails development team have tried to keep breakages to a minimum there are a number of ite upgrading a Grails 1.0.x, 1.1.x, 1.2.x, or 1.3.x applications to Grails 2.0. The major changes are described in m here's a brief summary of what you might encounter when upgrading from Grails 1.3.x:

35

environment bean added by Spring 3.1, which will be auto-wired into properties of the same name.

Logging by convention packages have changed, so you may not see the logging output you expect. U configuration as described below.

HSQLDB has been replaced with H2 as default in-memory database. If you use the former, either change yo or add HSQLDB as a runtime dependency.

The release-plugin command has been removed. You must now install the Release plugin and use its command instead. The redirect() method no longer commits the response, so isCommitted() will return false. If then call request.isRedirected() instead.

The redirect() method now uses the grails.serverURL config setting to generate the redirect URL. You the setting, particularly from the development and test environments.

withFormat() no longer takes account of the request content type. If you want to do something based o type, use request.withFormat(). Adaptive AJAX tags using Prototype will break. In this situation you must install the new Prototype plugin.

If you install Resources (or it is installed automatically), tags like <g:javascript> won't write anything add the <r:layoutResources/> tags to your layout. Resources adds a '/static' URL, so you may have to update your access control rules accordingly.

Some plugins may fail to install because one or more of their dependencies can not be found. If this happens has a custom repository URL that you need to add to your project's BuildConfig.groovy.

The behaviour of abstract domain classes has changed, so if you use them you will either have to move t 'src/groovy' or migrate your database schema and data.

Criteria queries default to INNER_JOIN for associations rather than OUTER_JOIN. This may affect some of Constraints declared for non-existent properties will now throw an exception.

beforeValidate() may be called two or more times during a request, for example once on save() and view is rendered.

Public methods in controllers will now be treated as actions. If you don't want this, make them protected or pr

The new unit testing framework won't work with the old GrailsUnitTestCase class hierarchy. Your o to work, but if you wish to use the new annotations, do not extend any of the *UnitTestCase classes.

Output from Ant tasks is now hidden by default. If your scripts are using ant.echo(), ant.input(), e use alternative mechanisms for output. Domain properties of type java.net.URL may no longer work with your existing data. The serialisation appears to have changed. Consider migrating your data and domain models to String.

The Ivy cache location has changed. If you want to use the old location, configure the appropriate global se be aware that you may run into problems running Grails 1.3.x and 2.x projects side by side.

With new versions of various dependencies, some APIs (such as the Servlet API) may have changed. I implements any of those APIs, you will need to update it. Problems will typically manifest as compilation err The following deprecated classes grails.web.OpenRicoBuilder. have been removed:

grails.web.JsonB

36

Upgrading from Grails 1.3.x


Changes to web.xml template

If you have customized the web.xml provided by grails install-templates then you will need to up template with the latest version provided by Grails. Failing to do so will lead to a ClassNotFound org.codehaus.groovy.grails.web.util.Log4jConfigListener class.

Groovy 1.8 Changes

Groovy 1.8 is a little stricter in terms of compilation so you may be required to fix compilation errors in your a occur under Grails 1.3.x.

Groovy 1.8 also requires that you update many of the libraries that you may be using in your application. Librarie upgrade include: Spock Geb GMock (upgrade unavailable as of this writing)

New 'environment' bean

Spring 3.1 adds a new bean with the name 'environment'. It's of type Environmen org.springframework.core.env) and it will automatically be autowired into properties with the same cause particular problems with domain classes that have an environment property. In this case, adding the meth
void setEnvironment(org.springframework.core.env.Environment env) {}

works around the problem.

HSQLDB Has Been Replaced With H2

HSQLDB is still bundled with Grails but is not configured as a default runtime dependency. Upgrade optio HSQLDB references in DataSource.groovy with H2 references or adding HSQLDB as a runtime dependency for t

If you want to run an application with different versions of Grails, it's simplest to add HSQLDB as a runtime de can do in BuildConfig.groovy:

37

grails.project.dependency.resolution = { inherits("global") { } repositories { grailsPlugins() grailsHome() grailsCentral() } dependencies { // Add HSQLDB as a runtime dependency runtime 'hsqldb:hsqldb:1.8.0.10' } }

A default DataSource.groovy which is compatible with H2 looks like this:


dataSource { driverClassName = "org.h2.Driver" username = "sa" password = "" } // environment specific settings environments { development { dataSource { dbCreate = "create-drop" // one of 'create', 'create-drop','update' url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }

Another significant difference between H2 and HSQLDB is in the handling of byte[] domain class propertie BLOB size is large and so you typically don't need to specify a maximum size. But H2 defaults to a maximum siz store images in the database, the saves are likely to fail because of this. The easy fix is to add a maxSize cons property:
class MyDomain { byte[] data static constraints = { data maxSize: 1024 * 1024 * 2 // 2MB } }

This constraint influences schema generation, so in the above example H2 will have the data column set to BIN Hibernate.

38

Abstract Inheritance Changes

In previous versions of Grails abstract classes in grails-app/domain were not treated as persistent. This is n has a significant impact on upgrading your application. For example consider the following domain model in a Gra
abstract class Sellable { } class Book extends Sellable { }

In Grails 1.3.x you would get a BOOK table and the properties from the Sellable class would be stored w However, in Grails 2.x you will get a SELLABLE table and the default table-per-hierarchy inheritance rules apply the Book stored in the SELLABLE table. You have two options when upgrading in this scenario:

1. Move the abstract Sellable class into the src/groovy package. If the Sellable class is in the src/gro no longer be regarded as persistent. 2. Use the database migration plugin to apply the appropriate changes to the database (typically renaming abstract class of the inheritance tree).

Criteria Queries Default to INNER JOIN


The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.

Invalid Constraints Now Thrown an Exception


Previously if you defined a constraint on a property that doesn't exist no error would be thrown:
class Person { String name static constraints = { bad nullable:false // invalid property, no error thrown } }

Now the above code will result in an exception

Logging By Convention Changes


The packages that you should use for Grails artifacts have mostly changed. In particular:

39

service -> services controller -> controllers tagLib -> taglib (case change) bootstrap -> conf dataSource -> conf

You can find out more about logging by convention in the main part of the user guide, under "Configuring logge side-effect of injecting the log property into artefacts at compile time.

jQuery Replaces Prototype

The Protoype Javascript library has been removed from Grails core and now new Grails applications have the jQu by default. This will only impact you if you are using Prototype with the adaptive AJAX tags in your application, etc, because those tags will break as soon as you upgrade.

To resolve this issue, simply install the Prototype plugin in your application. You can also remove the protot web-app/js/prototype directory if you want.

The Resources Plugin

The Resources plugin is a great new feature of Grails that allows you to manage static web resources better tha need to be aware that it adds an extra URL at /static. If you have access control in your application, this ma resources require an authenticated user to load them! Make sure your access rules take account of the /static U

Controller Public Methods

As of Grails 2.0, public methods of controllers are now treated as actions in addition to actions defined as traditi were relying on the use of methods for privacy controls or as helper methods then this could result in unexpected this issue you should mark all methods of your application that are not to be exposed as actions as private meth

Command Object Constraints

As of Grails 2.0, constrained properties in command object classes are no longer nullable by default. Nulla properties must be explicitly configured as such in the same way that nullable persistent properties in domain class

The redirect Method

The redirect method no longer commits the response. The result of this is code that relies of this behavior w example:
redirect action: "next" if (response.committed) { // do something }

In this case in Grails 1.3.x and below the response.committed property would return true and the if b Grails 2.0 this is no longer the case and you should instead use the new isRedirected() method of the reque 40

redirect action: "next" if (request.redirected) { // do something }

Another side-effect of the changes to the redirect method is that it now always uses the grails.serverURL c it's set. Previous versions of Grails included default values for all the environments, but when upgrading to Gr more often than not break redirection. So, we recommend you remove the development and test settings for grai replace them with something appropriate for your application.

Content Negotiation

As of Grails 2.0 the withFormat method of controllers no longer takes into account the request content ty CONTENT_TYPE header), but instead deals exclusively with the response content type (dictated by the AC extension). This means that if your application has code that relies on reading XML from the request using with longer work:
def processBook() { withFormat { xml { // read request XML } html { // read request parameters } } }

Instead you use the withFormat method provided on the request object:
def processBook() { request.withFormat { xml { // read request XML } html { // read request parameters } } }

Unit Test Framework

Grails 2 introduces a new unit testing framework that is simpler and behaves more consistently than the old one based on the GrailsUnitTestCase class hierarchy is still available for backwards compatibility, but it does n annotations.

Migrating unit tests to the new approach is non-trivial, but recommended. Here are a set of mappings from the old

41

1. Remove extends *UnitTestCase and add a @TestFor annotation to the class if you're testing a co tag lib, domain class, etc.) or @TestMixin(GrailsUnitTestMixin) for non-core artifacts and non-ar

2. Add @Mock annotation for domain classes that must be mocked and use new MyDomain().sa mockDomain().

3. Replace references to mockRequest, mockResponse and mockParams with request, response an

4. Remove references to renderArgs and use the view and model properties for view rendering, or resp others. 5. Replace references to redirectArgs with response.redirectedUrl. The latter takes into account is a string URL rather than a map of redirect() arguments. 6. The mockCommandObject() method is no longer needed as Grails automatically detects whether command object or not.

There are other differences, but these are the main ones. We recommend that you read the chapter on testing thor everything that has changed.

Note that the Grails annotations don't need to be imported in your test cases to run them from the command lin need them. So, here are the relevant classes with packages: grails.test.mixin.TestFor grails.test.mixin.TestMixin grails.test.mixin.Mock grails.test.mixin.support.GrailsUnitTestMixin grails.test.mixin.domain.DomainClassUnitTestMixin grails.test.mixin.services.ServiceUnitTestMixin grails.test.mixin.web.ControllerUnitTestMixin grails.test.mixin.web.FiltersUnitTestMixin grails.test.mixin.web.GroovyPageUnitTestMixin grails.test.mixin.web.UrlMappingsUnitTestMixin grails.test.mixin.webflow/WebFlowUnitTestMixin Note that you're only ever likely to use the first two explicitly. The rest are there for reference.

Command Line Output

Ant output is now hidden by default to keep the noise in the terminal to a minimum. That means if you use ant. to communicate messages to the user, we recommend switching to an alternative mechanism. For status related messages, you can use the event system:
event "StatusUpdate", ["Some message"] event "StatusFinal", ["Some message"] event "StatusError", ["Some message"]

42

For more control you can use the grailsConsole script variable, which gives you access to an instance particular, you can log information messages with log() or info(), errors and warnings with error() an request user input with userInput().

Custom Plugin Repositories

Many plugins have dependencies, both other plugins and straight JAR libraries. These are often located in Mave core repository or the Grails Central Plugin Repository in which case applications are largely unaffected if they But sometimes such dependencies are located elsewhere and Grails must be told where they can be found.

Due to changes in the way Grails handles the resolution of dependencies, Grails 2.0 requires you to add any su locations to your project if an affected plugin is to install properly.

Ivy Cache Location Has Changed

The default Ivy cache location for Grails has changed. If the thought of yet another cache of JARs on your disk h can change this in your settings.groovy:
grails.dependency.cache.dir = "${userHome}/.ivy2/cache"

If you do this, be aware that you may run into problems running Grails 2 and earlier versions of Grails side-bycan be avoided by excluding "xml-apis" and "commons-digester" from the inherited global dependencies in G projects.

URL Domain Properties

If your domain model has any properties of type java.net.URL, they may cease to work once you upgrade to G the default mapping of URL to database column has changed with the new version of Hibernate. This is a tricky in the long run it's best if you migrate your URL properties to strings. One technique is to use the database migr new text column and then execute some code in BootStrap (using Grails 1.3.x or earlier) to fetch each row of instance, convert the URL properties to string URLs, and then write those values to the new column.

Updated Underlying APIs

Grails 2.0 contains updated dependencies including Servlet 3.0, Tomcat 7, Spring 3.1, Hibernate 3.6 and Groovy certain plugins and applications that depend on earlier versions of these APIs may no longer work. For exam HttpServletRequest interface includes new methods, so if a plugin implements this interface for Servlet 2 3.0 then said plugin will break. The same can be said of any Spring interface.

Removal of release-plugin Command

The built in release-plugin command for releases plugins to the central Grails plugin repository has been release plugin should be used instead which provides an equivalent publish-plugin command.

Removal of Deprecated Classes

The following deprecated classes have been removed: grails.web.JsonBuilder, grails.web.OpenRi

43

Upgrading from Grails 1.2.x


Plugin Repositories

As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. T mechanism in Grails 1.2 and below has been replaced by one built on Ivy, the upside of which is that you ca plugins against Maven repositories as well as regular Grails repositories.

Ivy supports a much richer set of repository resolvers for resolving plugins, including support for Webdav, HTT the section on resolvers in the Ivy docs for all the available options and the section of plugin repositories in explains how to configure additional resolvers.

If you still need support for resolving plugins against secured SVN repositories then the IvySvn project provides SVN repositories.

Upgrading from Grails 1.1.x


Plugin paths

In Grails 1.1.x typically a pluginContextPath variable was used to establish paths to plugin resources. For e
<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />

In Grails 1.2 views have been made plugin aware and this is no longer necessary:
<g:resource dir="images" file="foo.jpg" />

Additionally the above example will no longer link to an application image from a plugin view. To do so change th
<g:resource contextPath="" dir="images" file="foo.jpg" />

The same rules apply to the javascript and render tags.

Tag and Body return values

Tags no longer return java.lang.String instances but instead return a Grails StreamCharBuff StreamCharBuffer class implements all the same methods as String but doesn't extend String, so code l
def foo = body() if (foo instanceof String) { // do something }

44

In these cases you should check for the java.lang.CharSequence interface, which both String and St implement:
def foo = body() if (foo instanceof CharSequence) { // do something }

New JSONBuilder

There is a new version of JSONBuilder which is semantically different from the one used in earlier versions o your application depends on the older semantics you can still use the deprecated implementation by setting the f true in Config.groovy:
grails.json.legacy.builder=true

Validation on Flush

Grails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid If one of your constraints (such as a custom validator) executes a query then this can cause an additional f StackOverflowError. For example:
static constraints = { author validator: { a -> assert a != Book.findByTitle("My Book").author } }

The above code can lead to a StackOverflowError in Grails 1.2. The solution is to run the query in a new (which is recommended in general as doing Hibernate work during flushing can cause other issues):
static constraints = { author validator: { a -> Book.withNewSession { assert a != Book.findByTitle( "My Book").author } } }

Upgrading from Grails 1.0.x


Groovy 1.6

Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you ha compiled with Groovy 1.5 you must recompile it against Groovy 1.6 or higher before using it with Grails 1.1.

45

Java 5.0

Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you sti stream until you are able to upgrade your JDK.

Configuration Changes

1) The setting grails.testing.reports.destDir has been renamed to grails.project.test. consistency. 2) The following settings have been grails-app/conf/BuildConfig.groovy: grails.config.base.webXml grails.project.war.file (renamed from grails.war.destFile) grails.war.dependencies grails.war.copyToWebApp grails.war.resources moved from

grails-app/conf/Config

3) The grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baselin 4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid usage by adding the following to grails-app/conf/Config.groovy:
grails.views.enable.jsessionid=true

5) The syntax used to configure Log4j has changed. See the user guide section on Logging for more information.

Plugin Changes

As of version 1.1, Grails no longer stores plugins inside your PROJECT_HOME/plugins directory by defau compilation errors in your application unless you either re-install all your plugins or set the follo grails-app/conf/BuildConfig.groovy:
grails.project.plugins.dir="./plugins"

Script Changes

1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for im GRAILS_HOME:
Ant.property(environment:"env") grailsHome = Ant.antProject.properties."env.GRAILS_HOME" includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")

46

Instead you should use the new grailsScript method to import a named script:
includeTargets << grailsScript("_GrailsBootstrap")

2) Due to an upgrade of Gant all references to the variable Ant should be changed to ant.

3) The root directory of the project is no longer on the classpath, so loading a resource like this will no longer wor
def stream = getClass().classLoader.getResourceAsStream( "grails-app/conf/my-config.xml")

Instead you should use the Java File APIs with the basedir property:
new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream -> // read the file }

Command Line Changes

The run-app-https and run-war-https commands no longer exist and have been replaced by an argumen
grails run-app -https

Data Mapping Changes

1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old b your mapping as follows:
static mapping = { someEnum enumType:"ordinal" }

2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreig shouldn't need to change anything; however you should drop column on the inverse side as it contains duplicate da

REST Support
Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you parseRequest argument inside a URL mapping:
"/book"(controller:"book",parseRequest:true)

47

Alternatively, you can use the new resource argument, which enables parsing by default:
"/book"(resource:"book")

48

4 Configuration

It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now settings you can actually develop an application without doing any configuration whatsoever, as the quick start important to learn where and how to override the conventions when you need to. Later sections of the user guid configuration settings you can use, but not how to set them. The assumption is that you have at least read th chapter!

4.1 Basic Configuration


For general configuration Grails provides two files: grails-app/conf/BuildConfig.groovy grails-app/conf/Config.groovy

Both of them use Groovy's ConfigSlurper syntax. The first, BuildConfig.groovy, is for settings that are Grails commands, such as compile, doc, etc. The second file, Config.groovy, is for settings that are used w is running. This means that Config.groovy is packaged with your application, but BuildConfig.groovy you're not clear on the distinction: the guide will tell you which file to put a particular setting in. The most basic syntax is similar to that of Java properties files with dot notation on the left-hand side:
foo.bar.hello = "world"

Note that the value is a Groovy string literal! Those quotes around 'world' are important. In fact, this highlights o of the ConfigSlurper syntax over properties files: the property values can be any valid Groovy type, such as arbitrary objects!

Things become more interesting when you have multiple settings with the same base. For example, you could hav
foo.bar.hello = "world" foo.bar.good = "bye"

both of which have the same base: foo.bar. The above syntax works but it's quite repetitive and verbose. You that verbosity by nesting properties at the dots:
foo { bar { hello = "world" good = "bye" } }

or by only partially nesting them:

49

foo { bar.hello = "world" bar.good = "bye" }

However, you can't nest after using the dot notation. In other words, this won't work:
// Won't work! foo.bar { hello = "world" good = "bye" }

Within both BuildConfig.groovy and Config.groovy you can access several implicit variables from con Variable userHome Description Location of the home directory for the account that is running the Grails application.

grailsHome Location of the home directory for the account that is running the Grails application. appName The application name as it appears in application.properties.

appVersion The application version as it appears in application.properties. For example:


my.tmp.dir = "${userHome}/.grails/tmp"

In addition, BuildConfig.groovy has Variable Description

grailsVersion The version of Grails used to build the project.

grailsSettings An object containing various build related settings, such as baseDir. It's of type BuildSettin and Config.groovy has Variable Description

grailsApplication The GrailsApplication instance.

Those are the basics of adding settings to the configuration file, but how do you access those settings from your o depends on which config you want to read. The settings in BuildConfig.groovy are only available from command scripts and can be grailsSettings.config property like so:

50

target(default: "Example command") { def maxIterations = grailsSettings.config.myapp.iterations.max }

If you want to read runtime configuration settings, i.e. those defined in Config.groovy, use the grailsAp which is available as a variable in controllers and tag libraries:
class MyController { def hello() { def recipient = grailsApplication.config.foo.bar.hello render "Hello ${recipient}" } }

and can be easily injected into services and other Grails artifacts:
class MyService { def grailsApplication String greeting() { def recipient = grailsApplication.config.foo.bar.hello return "Hello ${recipient}" } }

As you can see, when accessing configuration settings you use the same dot notation as when you define them.

4.1.1 Built in options

Grails has a set of core settings that are worth knowing about. Their defaults are suitable for most projects, understand what they do because you may need one or more of them later.

Build settings

Let's start with some important build settings. Although Grails requires JDK 6 when developing your applicat deploy those applications to JDK 5 containers. Simply set the following in BuildConfig.groovy:
grails.project.source.level = "1.5" grails.project.target.level = "1.5"

Note that source and target levels are different to the standard public version of JDKs, so JDK 5 -> 1.5, JDK 6 1.7.

In addition, Grails supports Servlet versions 2.5 and above but defaults to 2.5. If you wish to use newer featur (such as 3.0 async support) you should configure the grails.servlet.version setting appropriately:
grails.servlet.version = "3.0"

51

Runtime settings
On the runtime front, i.e. Config.groovy, there are quite a few more core settings:

grails.config.locations - The location of properties files or addition Grails Config files that sh main configuration. See the section on externalised config.

grails.enable.native2ascii - Set this to false if you do not require native2ascii conversion of G files (default: true).

grails.views.default.codec - Sets the default encoding regime for GSPs - can be one of 'non (default: 'none'). To reduce risk of XSS attacks, set this to 'html'. grails.views.gsp.encoding - The file encoding used for GSP source files (default: 'utf-8'). grails.mime.file.extensions - Whether to use the file extension to dictate the mime type in (default: true). grails.mime.types - A map of supported mime types used for Content Negotiation.

grails.serverURL - A string specifying the server URL portion of absolute links, includin grails.serverURL="http://my.yourportal.com". See createLink. Also used by redirects.

grails.views.gsp.sitemesh.preprocess - Determines whether SiteMesh preprocessing hap slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then d option. Don't worry if you don't understand this advanced property: leave it set to true.

War generation

grails.project.war.file - Sets the name and location of the WAR file generated by the war comma

grails.war.dependencies - A closure containing Ant builder syntax or a list of JAR filenames. Let libaries are included in the WAR file.

grails.war.copyToWebApp - A closure containing Ant builder syntax that is legal inside an An "fileset()". Lets you control what gets included in the WAR file from the "web-app" directory.

grails.war.resources - A closure containing Ant builder syntax. Allows the application to do any oth building the final WAR file For more information on using these options, see the section on deployment

4.1.2 Logging
The Basics

Grails uses its common configuration mechanism to provide the settings for the underlying Log4j log system, so add a log4j setting to the file grails-app/conf/Config.groovy. So what does this log4j setting look like? Here's a basic example:

52

log4j = { error warn }

'org.codehaus.groovy.grails.web.servlet', 'org.codehaus.groovy.grails.web.pages' //

// controllers GSP

'org.apache.catalina'

This says that for loggers whose name starts with 'org.codehaus.groovy.grails.web.servlet' or 'org.codehaus.groo only messages logged at 'error' level and above will be shown. Loggers with names starting with 'org.apache.catal messages at the 'warn' level and above. What does that mean? First of all, you have to understand how levels work

Logging levels
The are several standard logging levels, which are listed here in order of descending priority: 1. off 2. fatal 3. error 4. warn 5. info 6. debug 7. trace 8. all

When you log a message, you implicitly give that message a level. For example, the method log.error(msg) the 'error' level. Likewise, log.debug(msg) will log it at 'debug'. Each of the above levels apart from corresponding log method of the same name.

The logging system uses that message level combined with the configuration for the logger (see next section) to d message gets written out. For example, if you have an 'org.example.domain' logger configured like so:
warn 'org.example.domain'

then messages with a level of 'warn', 'error', or 'fatal' will be written out. Messages at other levels will be ignored.

Before we go on to loggers, a quick note about those 'off' and 'all' levels. These are special in that they can configuration; you can't log messages at these levels. So if you configure a logger with a level of 'off', then no me out. A level of 'all' means that you will see all messages. Simple.

Loggers

Loggers are fundamental to the logging system, but they are a source of some confusion. For a start, what are th How do you configure them?

A logger is the object you log messages to, so in the call log.debug(msg), log is a logger instance (of type are cached and uniquely identified by name, so if two separate classes use loggers with the same name, those lo same instance. 53

There are two main ways to get hold of a logger: 1. use the log instance injected into artifacts such as domain classes, controllers and services; 2. use the Commons Logging API directly.

If you use the dynamic log property, then the name of the logger is 'grails.app.<type>.<className>', where ty artifact, for example 'controllers' or 'services', and className is the fully qualified name of the artifact. For exam service:
package org.example class MyService { }

then the name of the logger will be 'grails.app.services.org.example.MyService'. For other classes, the typical approach is to store a logger based on the class name in a constant static field:
package org.other import org.apache.commons.logging.LogFactory class MyClass { private static final log = LogFactory.getLog(this) }

This will create a logger with the name 'org.other.MyClass' - note the lack of a 'grails.app.' prefix since the class can also pass a name to the getLog() method, such as "myLogger", but this is less common because the logging with dots ('.') in a special way.

Configuring loggers
You have already seen how to configure loggers in Grails:
log4j = { error }

'org.codehaus.groovy.grails.web.servlet'

This example configures loggers with names starting with 'org.codehaus.groovy.grails.web.servlet' to ignore any m at a level of 'warn' or lower. But is there a logger with this name in the application? No. So why have a configur the above rule applies to any logger whose name begins with 'org.codehaus.groovy.grails.servlet.' as well. For exa to both the org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest one.

In other words, loggers are hierarchical. This makes configuring them by package much simpler than it would othe

The most common things that you will want to capture log output from are your controllers, services, and ot convention mentioned earlier to do that: grails.app.<artifactType>.<className> . In particular the class name m i.e. with the package if there is one: 54

log4j = { // Set level for all application artifacts info "grails.app" // Set for a specific controller in the default package debug "grails.app.controllers.YourController" // Set for a specific domain class debug "grails.app.domain.org.example.Book" // Set for all taglibs info "grails.app.taglib" }

The standard artifact names used in the logging configuration are: conf - For anything under grails-app/conf such as BootStrap.groovy (but excluding filters) filters - For filters taglib - For tag libraries services - For service classes controllers - For controllers domain - For domain entities

Grails itself generates plenty of logging information and it can sometimes be helpful to see that. Here are some Grails internals that you can use, especially when tracking down problems with your application: org.codehaus.groovy.grails.commons - Core artifact information such as class loading etc. org.codehaus.groovy.grails.web - Grails web request processing org.codehaus.groovy.grails.web.mapping - URL mapping debugging org.codehaus.groovy.grails.plugins - Log plugin activity grails.spring - See what Spring beans Grails and plugins are defining org.springframework - See what Spring is doing org.hibernate - See what Hibernate is doing

So far, we've only looked at explicit configuration of loggers. But what about all those loggers that do configuration? Are they simply ignored? The answer lies with the root logger.

The Root Logger

All logger objects inherit their configuration from the root logger, so if no explicit configuration is provided for any messages that go to that logger are subject to the rules defined for the root logger. In other words, the roo default configuration for the logging system.

Grails automatically configures the root logger to only handle messages at 'error' level and above, and all the me the console (stdout for those with a C background). You can customise this behaviour by specifying a 'root' se configuration like so:

55

log4j = { root { info() } }

The above example configures the root logger to log messages at 'info' level and above to the default console ap configure the root logger to log to one or more named appenders (which we'll talk more about shortly):
log4j = { appenders { file name:'file', file:'/var/logs/mylog.log' } root { debug 'stdout', 'file' } }

In the above example, the root logger will log to two appenders - the default 'stdout' (console) appender and a cust

For power users there is an alternative syntax for configuring the root logger: the root org.apache.log4j. passed as an argument to the log4j closure. This lets you work with the logger directly:
log4j = { root -> root.level = org.apache.log4j.Level.DEBUG }

For more information on what you can do with this Logger instance, refer to the Log4j API documentation.

Those are the basics of logging pretty well covered and they are sufficient if you're happy to only send log messag what if you want to send them to a file? How do you make sure that messages from a particular logger go to a file These questions and more will be answered as we look into appenders.

Appenders

Loggers are a useful mechanism for filtering messages, but they don't physically write the messages anywhere. appender, of which there are various types. For example, there is the default one that writes messages to the conso them to a file, and several others. You can even create your own appender implementations! This diagram shows how they fit into the logging pipeline:

56

As you can see, a single logger may have several appenders attached to it. In a standard Grails configuration, named 'stdout' is attached to all loggers through the default root logger configuration. But that's the only one. Ad can be done within an 'appenders' block:
log4j = { appenders { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } }

The following appenders are available by default: Name jdbc console file Class JDBCAppender ConsoleAppender FileAppender Description Logs to a JDBC connection. Logs to the console. Logs to a single file.

rollingFile RollingFileAppender Logs to rolling files, for example a new file each day. Each named argument passed to an appender maps to a property of the underlying Appender implementation. So sets the name, maxFileSize and file properties of the RollingFileAppender instance.

You can have as many appenders as you like - just make sure that they all have unique names. You can even have the same appender type, for example several file appenders that log to different files.

If you prefer to create the appender programmatically or if you want to use an appender implementation that's above syntax, simply declare an appender entry with an instance of the appender you want:
import org.apache.log4j.* log4j = { appenders { appender new RollingFileAppender( name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log") } }

57

This approach can be used to configure JMSAppender, SocketAppender, SMTPAppender, and more. Once you have declared your extra appenders, you can attach them to specific loggers by passing the name as a level methods from the previous section:
error myAppender: "grails.app.controllers.BookController"

This will ensure that the 'grails.app.controllers.BookController' logger sends log messages to 'myAppender' as w configured for the root logger. To add more than one appender to the logger, then add them to the same level decla
error myAppender: myFileAppender: rollingFile: "grails.app.controllers.BookController", ["grails.app.controllers.BookController", "grails.app.services.BookService"], "grails.app.controllers.BookController"

The above example also shows how you can configure more than one logger at a time for a given appender ( myF using a list. Be aware that you can only configure a single level for a logger, so if you tried this code:
error myAppender: debug myFileAppender: fatal rollingFile: "grails.app.controllers.BookController" "grails.app.controllers.BookController" "grails.app.controllers.BookController"

you'd find that only 'fatal' level messages get logged for 'grails.app.controllers.BookController'. That's because t for a given logger wins. What you probably want to do is limit what level of messages an appender writes.

An appender that is attached to a logger configured with the 'all' level will generate a lot of logging information. file, but it makes working at the console difficult. So we configure the console appender to only write out mess above:
log4j = { appenders { console name: "stdout", threshold: org.apache.log4j.Level.INFO } }

The key here is the threshold argument which determines the cut-off for log messages. This argumen appenders, but do note that you currently have to specify a Level instance - a string such as "info" will not work.

Custom Layouts

By default the Log4j DSL assumes that you want to use a PatternLayout. However, there are other layouts availab

58

xml - Create an XML log file html - Creates an HTML log file simple - A simple textual log pattern - A Pattern layout You can specify custom patterns to an appender using the layout setting:
log4j = { appenders { console name: "customAppender", layout: pattern(conversionPattern: "%c{2} %m%n") } }

This also works for the built-in appender "stdout", which logs to the console:
log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") } }

Environment-specific configuration

Since the logging configuration is inside Config.groovy, you can put it inside an environment-specific block problem with this approach: you have to provide the full logging configuration each time you define the log words, you cannot selectively override parts of the configuration - it's all or nothing.

To get around this, the logging DSL provides its own environment blocks that you can put anywhere in the config

59

log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") environments { production { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } } } root { // } // other shared config info "grails.app.controller" environments { production { // Override previous setting for 'grails.app.controller' error "grails.app.controllers" } } }

The one place you can't put an environment block is inside the root definition, but you can put the root environment block.

Full stacktraces

When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.

When this happens, the full trace is always logged to the StackTrace logger, which by default writes its ou stacktrace.log. As with other loggers though, you can change its behaviour in the configuration. For exam stack traces to go to the console, add this entry:
error stdout: "StackTrace"

This won't stop Grails from attempting to create the stacktrace.log file - it just redirects where stack traces are writ approach is to change the location of the 'stacktrace' appender's file:
log4j = { appenders { rollingFile name: "stacktrace", maxFileSize: 1024, file: "/var/tmp/logs/myApp-stacktrace.log" } }

or, if you don't want to the 'stacktrace' appender at all, configure it as a 'null' appender:

60

log4j = { appenders { 'null' name: "stacktrace" } }

You can of course combine this with attaching the 'stdout' appender to the 'StackTrace' logger if you want all the o

Finally, you can completely disable stacktrace filtering by setting the grails.full.stacktrace VM proper
grails -Dgrails.full.stacktrace=true run-app

Masking Request Parameters From Stacktrace Logs

When Grails logs a stacktrace, the log message may include the names and values of all of the request param request. To mask out the values of secure request parameters, specify the parameter grails.exceptionresolver.params.exclude config property:
grails.exceptionresolver.params.exclude = ['password', 'creditCard']

Request parameter logging may be turned off altogether by s grails.exceptionresolver.logRequestParameters config property to false. The default valu application is running in DEVELOPMENT mode and false for all other modes.
grails.exceptionresolver.logRequestParameters=false

Logger inheritance

Earlier, we mentioned that all loggers inherit from the root logger and that loggers are hierarchical based on '.'-s this means is that unless you override a parent setting, a logger retains the level and the appenders configured fo this configuration:
log4j = { appenders { file name:'file', file:'/var/logs/mylog.log' } root { debug 'stdout', 'file' } }

all loggers in the application will have a level of 'debug' and will log to both the 'stdout' and 'file' appenders. Wha log to 'stdout' for a particular logger? Change the 'additivity' for a logger in that case.

61

Additivity simply determines whether a logger inherits the configuration from its parent. If additivity is false, then default for all loggers is true, i.e. they inherit the configuration. So how do you change this setting? Here's an exam
log4j = { appenders { } root { } info additivity: false stdout: ["grails.app.controllers.BookController", "grails.app.services.BookService"] }

So when you specify a log level, add an 'additivity' named argument. Note that you when you specify the configure the loggers for a named appender. The following syntax will not work:
info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]

Customizing stack trace printing and filtering

Stacktraces in general and those generated when using Groovy in particular are quite verbose and contain many st interesting when diagnosing problems. So Grails uses a implementatio org.codehaus.groovy.grails.exceptions.StackTraceFilterer interface to filter out irrelev customize the approach used for filtering, implement that interface in a class in src/groovy or src/java Config.groovy:
grails.logging.stackTraceFiltererClass = 'com.yourcompany.yourapp.MyStackTraceFilterer'

In addition, Grails customizes the display of the filtered stacktrace to make the information more readable implement the org.codehaus.groovy.grails.exceptions.StackTracePrinter interface in a c src/java and register it in Config.groovy:
grails.logging.stackTracePrinterClass = 'com.yourcompany.yourapp.MyStackTracePrinter'

Finally, to render error information in the error GSP, an HTML-generating printer implementation is implementation is org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinte as a Spring bean. To use your own implementation, either imp org.codehaus.groovy.grails.exceptions.StackTraceFilterer directly or ErrorsViewStackTracePrinter and register it in grails-app/conf/spring/resources.groov

62

import com.yourcompany.yourapp.MyErrorsViewStackTracePrinter beans = { errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter, ref('grailsResourceLocator')) }

Alternative logging libraries

By default, Grails uses Log4J to do its logging. For most people this is absolutely fine, and many users don't ev library is used. But if you're not one of those and want to use an alternative, such as the JDK logging package or so by simply excluding a couple of dependencies from the global set and adding your own:
grails.project.dependency.resolution = { inherits("global") { excludes "grails-plugin-logging", "log4j" } dependencies { runtime "ch.qos.logback:logback-core:0.9.29" } }

If you do this, you will get unfiltered, standard Java stacktraces in your log files and you won't be able to use the l DSL that's just been described. Instead, you will have to use the standard configuration mechanism for the library

4.1.3 GORM
Grails provides the following GORM configuration options:

grails.gorm.failOnError - If set to true, causes the save() method on domain cl grails.validation.ValidationException if validation fails during a save. This option may also Strings representing package names. If the value is a list of Strings then the failOnError behavior will only classes in those packages (including sub-packages). See the save method docs for more information. For example, to enable failOnError for all domain classes:
grails.gorm.failOnError=true

and to enable failOnError for domain classes by package:


grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']

grails.gorm.autoFlush = If set to true, causes the merge, save and delete methods to flush the s need to explicitly flush using save(flush: true).

63

4.2 Environments
Per Environment Configuration

Grails supports the concept of per environment configuration. The Config.groovy, DataSour BootStrap.groovy files in the grails-app/conf directory can use per-environment configuration using by ConfigSlurper. As an example consider the following default DataSource definition provided by Grails:
dataSource { pooled = false driverClassName = "org.h2.Driver" username = "sa" password = "" } environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }

Notice how the common configuration is provided at the top level and then an environments block speci settings for the dbCreate and url properties of the DataSource.

Packaging and Running for Different Environments

Grails' command line has built in capabilities to execute any command within the context of a specific environmen
grails [environment] [command name]

In addition, there are 3 preset environments known to Grails: dev, prod, and test for development, prod For example to create a WAR for the test environment you wound run:
grails test war

To target other environments you can pass a grails.env variable to any command:

64

grails -Dgrails.env=UAT run-app

Programmatic Environment Detection

Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environm
import grails.util.Environment ... switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }

Per Environment Bootstrapping

It's often desirable to run code when your application starts up on a per-environment basis. To do so grails-app/conf/BootStrap.groovy file's support for per-environment execution:
def init = { ServletContext ctx -> environments { production { ctx.setAttribute( "env", "prod") } development { ctx.setAttribute( "env", "dev") } } ctx.setAttribute("foo", "bar") }

Generic Per Environment Execution

The previous BootStrap example uses the grails.util.Environment class internally to execute. You c yourself to execute your own environment specific logic:
Environment.executeForCurrentEnvironment { production { // do something in production } development { // do something only in development } }

65

4.3 The DataSource

Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technolo for Java Database Connectivity).

If you use a database other than H2 you need a JDBC driver. For example for MySQL you would need Connector

Drivers typically come in the form of a JAR archive. It's best to use Ivy to resolve the jar if it's available in a M example you could add a dependency for the MySQL driver like this:
grails.project.dependency.resolution = { inherits("global") log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() mavenCentral() } dependencies { runtime 'mysql:mysql-connector-java:5.1.16' } }

Note that the built-in mavenCentral() repository is included here since that's a reliable location for this library If you can't use Ivy then just put the JAR in your project's lib directory.

Once you have the JAR resolved you need to get familiar Grails' DataSource descriptor grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the f driverClassName - The class name of the JDBC driver username - The username used to establish a JDBC connection password - The password used to establish a JDBC connection url - The JDBC URL of the database

dbCreate - Whether to auto-generate the database from the domain model - one of 'create-drop', 'create', 'up pooled - Whether to use a pool of connections (defaults to true) logSql - Enable SQL logging to stdout formatSql - Format logged SQL

dialect - A String or Class that represents the Hibernate dialect used to communicate with the org.hibernate.dialect package for available dialects.

readOnly - If true makes the DataSource read-only, which results in the connection pool calling setRe each Connection

properties - Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource d A typical configuration for MySQL may be something like:

66

dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" }

When configuring the DataSource do not include the type or the def keyword before any configuration settings as Groovy will treat these as local variable definitions and they will not be pro For example the following is invalid:

dataSource { boolean pooled = true // type declaration results in ignored local variable }

Example of advanced configuration using extra properties:


dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" properties { maxActive = 50 maxIdle = 25 minIdle = 5 initialSize = 5 minEvictableIdleTimeMillis = 60000 timeBetweenEvictionRunsMillis = 60000 maxWait = 10000 validationQuery = "/* ping */" } }

More on dbCreate

Hibernate can automatically create the database tables required for your domain model. You have some control o does this through the dbCreate property, which can take these values:

67

create - Drops the existing schemaCreates the schema on startup, dropping existing tables, indexes, etc. first. create-drop - Same as create, but also drops the tables when the application shuts down cleanly.

update - Creates missing tables and indexes, and updates the current schema without dropping any tables o can't properly handle many schema changes like column renames (you're left with the old column containing

validate - Makes no changes to your database. Compares the configuration with the existing database warnings. any other value - does nothing

You can also remove the dbCreate setting completely, which is recommended once your schema is relatively when your application and database are deployed in production. Database changes are then managed through pro with SQL scripts or a migration tool like Liquibase (the Database Migration plugin uses Liquibase and is tightly i and GORM).

4.3.1 DataSources and Environments


Grails' DataSource definition is "environment aware", however, so you can do:
dataSource { pooled = true driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect // other common settings here } environments { production { dataSource { url = "jdbc:mysql://liveip.com/liveDb" // other environment-specific settings here } } }

The previous example configuration assumes you want the same config for all environments: production, test, dev

4.3.2 JNDI DataSources


Referring to a JNDI DataSource

Most Java EE containers supply DataSource instances via Java Naming and Directory Interface (JNDI) definition of JNDI data sources as follows:
dataSource { jndiName = "java:comp/env/myDataSource" }

The format on the JNDI name may vary from container to container, but the way you define the DataSource same.

Configuring a Development time JNDI resource


68

The way in which you configure JNDI data sources at development time is plugin dependent. Using the Tomcat p JNDI resources using the grails.naming.entries setting in grails-app/conf/Config.groovy:
grails.naming.entries = [ "bean/MyBeanFactory": [ auth: "Container", type: "com.mycompany.MyBean", factory: "org.apache.naming.factory.BeanFactory", bar: "23" ], "jdbc/EmployeeDB": [ type: "javax.sql.DataSource", //required auth: "Container", // optional description: "Data source for Foo", //optional driverClassName: "org.h2.Driver", url: "jdbc:h2:mem:database", username: "dbusername", password: "dbpassword", maxActive: "8", maxIdle: "4" ], "mail/session": [ type: "javax.mail.Session, auth: "Container", "mail.smtp.host": "localhost" ] ]

4.3.3 Automatic Database Migration

The dbCreate property of the DataSource definition is important as it dictates what Grails should do at ru automatically generating the database tables from GORM classes. The options are described in the DataSource sec create create-drop update validate no value

In development mode dbCreate is by default set to "create-drop", but at some point in development (and cer production) you'll need to stop dropping and re-creating the database every time you start up your server.

It's tempting to switch to update so you retain existing data and only update the schema when your code cha update support is very conservative. It won't make any changes that could result in data loss, and doesn't detect tables, so you'll be left with the old one and will also have the new one. Grails supports Rails-style migrations via the Database Migration plugin which can be installed by running

grails install-plugin database-migration

The plugin uses Liquibase and and provides access to all of its functionality, and also has support for GORM (for change set by comparing your domain classes to a database).

69

4.3.4 Transaction-aware DataSource Proxy

The actual dataSource bean is wrapped in a transaction-aware proxy so you will be given the connection tha current transaction or Hibernate Session if one is active.

If this were not the case, then retrieving a connection from the dataSource would be a new connection, and yo see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. RE better).

The "real" unproxied dataSource is still available to you if you need access to it; its bean name is dataSourc You can access this bean like any other Spring bean, i.e. using dependency injection:
class MyService { def dataSourceUnproxied }

or by pulling it from the ApplicationContext:


def dataSourceUnproxied = ctx.dataSourceUnproxied

4.3.5 Database Console

The H2 database console is a convenient feature of H2 that provides a web-based interface to any database th driver for, and it's very useful to view the database you're developing against. It's especially useful when running a database.

You can access the console by navigating to http://localhost:8080/appname/dbconsole in a browser. The UR using the grails.dbconsole.urlRoot attribute in Config.groovy and defaults to '/dbconsole'.

The console is enabled by default in development mode and can be disabled or enabled in other environ grails.dbconsole.enabled attribute in Config.groovy. For example you could enable the console in prod
environments { production { grails.serverURL = "http://www.changeme.com" grails.dbconsole.enabled = true grails.dbconsole.urlRoot = '/admin/dbconsole' } development { grails.serverURL = "http://localhost:8080/${appName}" } test { grails.serverURL = "http://localhost:8080/${appName}" } }

If you enable the console in production be sure to guard access to it using a trusted security framewor

70

Configuration

By default the console is configured for an H2 database which will work with the default settings if you haven't c database - you just need to change the JDBC URL to jdbc:h2:mem:devDB. If you've configured an ex MySQL, Oracle, etc.) then you can use the Saved Settings dropdown to choose a settings template and username/password information from your DataSource.groovy.

4.3.6 Multiple Datasources

By default all domain classes share a single DataSource and a single database, but you have the option to p classes into two or more DataSources.

Configuring Additional DataSources

The default DataSource configuration in grails-app/conf/DataSource.groovy looks something lik


dataSource { pooled = true driverClassName = "org.h2.Driver" username = "sa" password = "" } hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider' } environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }

This configures a single DataSource with the Spring bean named dataSource. To configure extra DataSo dataSource block (at the top level, in an environment block, or both, just like the standard DataSource defi name, separated by an underscore. For example, this configuration adds a second DataSource, using MySQL environment and Oracle in production:

71

environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } dataSource_lookup { dialect = org.hibernate.dialect.MySQLInnoDBDialect driverClassName = 'com.mysql.jdbc.Driver' username = 'lookup' password = 'secret' url = 'jdbc:mysql://localhost/lookup' dbCreate = 'update' } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } dataSource_lookup { dialect = org.hibernate.dialect.Oracle10gDialect driverClassName = 'oracle.jdbc.driver.OracleDriver' username = 'lookup' password = 'secret' url = 'jdbc:oracle:thin:@localhost:1521:lookup' dbCreate = 'update' } } }

You can use the same or different databases as long as they're supported by Hibernate.

Configuring Domain Classes

If a domain class has no DataSource configuration, it defaults to the standard 'dataSource'. Set the data the mapping block to configure a non-default DataSource. For example, if you want to use the ZipCod 'lookup' DataSource, configure it like this;
class ZipCode { String code static mapping = { datasource 'lookup' } }

A domain class can also use two or more DataSources. Use the datasources property with a list of nam than one, for example:

72

class ZipCode { String code static mapping = { datasources(['lookup', 'auditing']) } }

If a domain class uses the default DataSource and one or more others, use the special name 'DEFAULT' to DataSource:
class ZipCode { String code static mapping = { datasources(['lookup', 'DEFAULT']) } }

If a domain class uses all configured DataSources use the special value 'ALL':
class ZipCode { String code static mapping = { datasource 'ALL' } }

Namespaces and GORM Methods

If a domain class uses more than one DataSource then you can use the namespace implied by each DataSo GORM calls for a particular DataSource. For example, consider this class which uses two DataSources:
class ZipCode { String code static mapping = { datasources(['lookup', 'auditing']) } }

The first DataSource specified is the default when not using an explicit namespace, so in this case we defaul can call GORM methods on the 'auditing' DataSource with the DataSource name, for example:
def zipCode = ZipCode.auditing.get(42) zipCode.auditing.save()

73

As you can see, you add the DataSource to the method call in both the static case and the instance case.

Hibernate Mapped Domain Classes

You can also partition annotated Java classes into separate datasources. Classes using the default datasour grails-app/conf/hibernate/hibernate.cfg.xml. To specify that an annotated class uses a no create a hibernate.cfg.xml file for that datasource with the file name prefixed with the datasource name. For example if the Book class is in the default grails-app/conf/hibernate/hibernate.cfg.xml: datasource, you would

reg

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Book'/> </session-factory> </hibernate-configuration>

and if the Library class is in the "ds2" grails-app/conf/hibernate/ds2_hibernate.cfg.xml:

datasource,

you

would

regi

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Library'/> </session-factory> </hibernate-configuration>

The process is the same for classes mapped with hbm.xml files - just list them in the appropriate hibernate.cfg.xml

Services

Like Domain classes, by default Services use the default DataSource and PlatformTransactionMana Service to use a different DataSource, use the static datasource property, for example:
class DataService { static datasource = 'lookup' void someMethod(...) { } }

A transactional service can only use a single DataSource, so be sure to only make changes for domain classes w is the same as the Service.

74

Note that the datasource specified in a service has no bearing on which datasources are used for domain classes; their declared datasources in the domain classes themselves. It's used to declare which transaction manager to use.

What you'll see is that if you have a Foo domain class in dataSource1 and a Bar domain class in dataSource2, an dataSource1, a service method that saves a new Foo and a new Bar will only be transactional for Foo since they The transaction won't affect the Bar instance. If you want both to be transactional you'd need to use two services for two-phase commit, e.g. with the Atomikos plugin.

XA and Two-phase Commit

Grails has no native support for XA DataSources or two-phase commit, but the Atomikos plugin makes it documentation for the simple changes needed in your DataSource definitions to reconfigure them as XA Data

4.4 Externalized Configuration

Some deployments require that configuration be sourced from more than one place and be changeable without r the application. In order to support deployment scenarios such as these the configuration can be externalized. To the locations of the configuration files that should be used by adding a grails.config.locations setting i , for example:
grails.config.locations = [ "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy", "file:${userHome}/.grails/${appName}-config.properties", "file:${userHome}/.grails/${appName}-config.groovy" ]

In the above example we're loading configuration files (both Java Properties files and ConfigSlurper configura places on the classpath and files located in USER_HOME. It is also possible to load config by specifying a class that is a config script.
grails.config.locations = [com.my.app.MyConfig]

This can be useful in situations where the config is either coming from a plugin or some other part of your appl for this is re-using configuration provided by plugins across multiple applications.

Ultimately all configuration files get merged into the config property of the GrailsApplication object and are h there.

Values that have the same name as previously defined values will overwrite the existing values, and the poin sources are loaded in the order in which they are defined.

Config Defaults

The configuration values contained in the locations described by the grails.config.locations proper values defined in your application Config.groovy file which may not be what you want. You may want to values be be loaded that can be overridden in either your application's Config.groovy file or in a named con you can use the grails.config.defaults.locations property.

75

This property supports the same values as the grails.config.locations property (i.e. paths to config scr classes), but the config described by grails.config.defaults.locations will be loaded before all therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration th include in your application config.

Grails also supports the concept of property place holders and property override configurers as defi Spring For more information on these see the section on Grails and Spring

4.5 Versioning
Versioning Basics

Grails has built in support for application versioning. The version of the application is set to 0.1 when you first with the create-app command. The version is stored in the application meta data file application.properti project. To change the version of your application you can edit the file manually, or run the set-version command:
grails set-version 0.2

The version is used in various commands including the war command which will append the application vers created WAR file.

Detecting Versions at Runtime

You can detect the application version using Grails' support for application metadata using the GrailsApplicatio within controllers there is an implicit grailsApplication variable that can be used:
def version = grailsApplication.metadata['app.version']

You can retrieve the the version of Grails that is running with:
def grailsVersion = grailsApplication.metadata['app.grails.version']

or the GrailsUtil class:


import grails.util.GrailsUtil def grailsVersion = GrailsUtil.grailsVersion

4.6 Project Documentation

Since Grails 1.2, the documentation engine that powers the creation of this documentation has been available projects. 76

The documentation engine uses a variation on the Textile syntax to automatically create project documentatio formatting etc.

Creating project documentation

To use the engine you need to follow a few conventions. First, you need to create a src/docs/guide d documentation source files will go. Then, you need to create the source docs themselves. Each chapter should hav should all numbered sub-sections. You will end up with something like:
+ + + + + + src/docs/guide/introduction.gdoc src/docs/guide/introduction/changes.gdoc src/docs/guide/gettingStarted.gdoc src/docs/guide/configuration.gdoc src/docs/guide/configuration/build.gdoc src/docs/guide/configuration/build/controllers.gdoc

Note that you can have all your gdoc files in the top-level directory if you want, but you can also put sub-sectio named after the parent section - as the above example shows.

Once you have your source files, you still need to tell the documentation engine what the structure of your user gu do that, you add a src/docs/guide/toc.yml file that contains the structure and titles for each section. T format and basically represents the structure of the user guide in tree form. For example, the above files could be r
introduction: title: Introduction changes: Change Log gettingStarted: Getting Started configuration: title: Configuration build: title: Build Config controllers: Specifying Controllers

The format is pretty straightforward. Any section that has sub-sections is represented with the corresponding filen extension) followed by a colon. The next line should contain title: plus the title of the section as seen by sub-section then has its own line after the title. Leaf nodes, i.e. those without any sub-sections, declare their title o section name but after the colon.

That's it. You can easily add, remove, and move sections within the toc.yml to restructure the generated user gu make sure that all section names, i.e. the gdoc filenames, should be unique since they are used for creating inte HTML filenames. Don't worry though, the documentation engine will warn you of duplicate section names.

Creating reference items

Reference items appear in the Quick Reference section of the documentation. Each reference item belongs to a ca is a directory located in the src/docs/ref directory. For example, suppose you have defined a new contr renderPDF. That belongs to the Controllers category so you would create a gdoc text file at the following l
+ src/docs/ref/Controllers/renderPDF.gdoc

77

Configuring Output Properties

There are various properties you can set within your grails-app/conf/Config.groovy file that custom documentation such as: grails.doc.title - The title of the documentation grails.doc.subtitle - The subtitle of the documentation grails.doc.authors - The authors of the documentation grails.doc.license - The license of the software grails.doc.copyright - The copyright message to display grails.doc.footer - The footer to use

Other properties such as the version are pulled from your project itself. If a title is not specified, the application na You can also customise the look of the documentation and provide images by setting a few other options: grails.doc.css - The location of a directory containing custom CSS files (type java.io.File) grails.doc.js - The location of a directory containing custom JavaScript files (type java.io.File)

grails.doc.style - The location of a directory containing custom HTML templates for the guide (type java.i

grails.doc.images - The location of a directory containing image files for use in the style templates and with pages themselves (type java.io.File)

One of the simplest ways to customise the look of the generated guide is to provide a value for grails.doc custom.css file in the corresponding directory. Grails will automatically include this CSS file in the guide. Y custom-pdf.css file in that directory. This allows you to override the styles for the PDF version of the guide.

Generating Documentation

Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an H documentation using the command:
grails doc

This command will output an docs/manual/index.html which can be opened in a browser to view your do

Documentation Syntax

As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections w syntax basics.
Basic Formatting

Monospace: monospace

78

@monospace@

Italic: italic
_italic_

Bold: bold
*bold*

Image:

!http://grails.org/images/new/grailslogo_topNav.png!

You can also link to internal images like so:


!someFolder/my_diagram.png!

This will link to an image stored locally within your project. There is currently no default location for doc images one with the grails.doc.images setting in Config.groovy like so:
grails.doc.images = new File("src/docs/images")

In this example, you would put the my_diagram.png file in the directory 'src/docs/images/someFolder'.
Linking

There are several ways to create links with the documentation generator. A basic external link can either be define textile style markup:
[SpringSource|http://www.springsource.com/]

or
"SpringSource":http://www.springsource.com/

For links to other sections inside the user guide you can use the guide: prefix with the name of the section you w

79

[Intro|guide:introduction]

The section name comes from the corresponding gdoc filename. The documentation engine will warn you if an your guide break. To link to reference items you can use a special syntax:
[controllers|renderPDF]

In this case the category of the reference item is on the left hand side of the | and the name of the reference item on Finally, to link to external APIs you can use the api: prefix. For example:
[String|api:java.lang.String]

The documentation engine will automatically create the appropriate javadoc link in this case. To add additional A can configure them in grails-app/conf/Config.groovy. For example:
grails.doc.api.org.hibernate= "http://docs.jboss.org/hibernate/stable/core/javadocs"

The above example configures classes within the org.hibernate package to link to the Hibernate website's AP
Lists and Headings

Headings can be created by specifying the letter 'h' followed by a number and then a dot:
h3.<space>Heading3 h4.<space>Heading4

Unordered lists are defined with the use of the * character:


* item 1 ** subitem 1 ** subitem 2 * item 2

Numbered lists can be defined with the # character:


# item 1

Tables can be created using the table macro: 80

Name Number Albert 46 Wilma 1348 James 12

{table} *Name* | *Number* Albert | 46 Wilma | 1348 James | 12 {table}

Code and Notes

You can define code blocks with the code macro:


class Book { String title }

{code} class Book { String title } {code}

The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML mark
<hello>world</hello>

{code:xml} <hello>world</hello> {code}

There are also a couple of macros for displaying notes and warnings: Note: This is a note!

81

{note} This is a note! {note}

Warning:

This is a warning!

{warning} This is a warning! {warning}

4.7 Dependency Resolution


You specify a grails.project.dependency.resolution property grails-app/conf/BuildConfig.groovy file that configures how dependencies are resolved:
grails.project.dependency.resolution = { // config here }

Grails features a dependency resolution DSL that lets you control how plugins and JAR dependencies are resolved

The default configuration looks like the following:

82

grails.project.class.dir = "target/classes" grails.project.test.class.dir = "target/test-classes" grails.project.test.reports.dir = "target/test-reports" //grails.project.war.file = "target/${appName}-${appVersion}.war" grails.project.dependency.resolution = { // inherit Grails' default dependencies inherits("global") { // uncomment to disable ehcache // excludes 'ehcache' } log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() // uncomment these to enable remote dependency resolution // from public Maven repositories //mavenCentral() //mavenLocal() //mavenRepo "http://snapshots.repository.codehaus.org" //mavenRepo "http://repository.codehaus.org" //mavenRepo "http://download.java.net/maven/2/" //mavenRepo "http://repository.jboss.com/maven2/" } dependencies { // specify dependencies here under either 'build', 'compile', // 'runtime', 'test' or 'provided' scopes eg. // runtime 'mysql:mysql-connector-java:5.1.16' } plugins { compile ":hibernate:$grailsVersion" compile ":jquery:1.6.1.1" compile ":resources:1.0" build ":tomcat:$grailsVersion" } }

The details of the above will be explained in the next few sections.

4.7.1 Configurations and Dependencies


Grails features five dependency resolution configurations (or 'scopes'): build: Dependencies for the build system only compile: Dependencies for the compile step runtime: Dependencies needed at runtime but not for compilation (see above) test: Dependencies needed for testing but not at runtime (see above) provided: Dependencies needed at development time, but not during WAR deployment

Within the dependencies block you can specify a dependency that falls into one of these configurations by c method. For example if your application requires the MySQL driver to function at runtime you can specify that
runtime 'com.mysql:mysql-connector-java:5.1.16'

83

This uses the string syntax: group:name:version. You can also use a Map-based syntax:
runtime group: 'com.mysql', name: 'mysql-connector-java', version: '5.1.16'

In Maven terminology, group corresponds to an artifact's groupId and name corresponds to its artifactId Multiple dependencies can be specified by passing multiple arguments:
runtime 'com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1' // Or runtime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.16'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )

Disabling transitive dependency resolution

By default, Grails will not only get the JARs and plugins that you declare, but it will also get their transitive d usually what you want, but there are occasions where you want a dependency without all its baggage. In such c transitive dependency resolution on a case-by-case basis:
runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { transitive = false } // Or runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.16', transitive:false

Excluding specific transitive dependencies

A far more common scenario is where you want the transitive dependencies, but some of them cause is dependencies or are unnecessary. For example, many Apache projects have 'commons-logging' as a transitiv shouldn't be included in a Grails project (we use SLF4J). That's where the excludes option comes in:
runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { excludes "xml-apis", "commons-logging" } // Or runtime(group:'com.mysql', name:'mysql-connector-java', version:'5.1.16') { excludes([ group: 'xml-apis', name: 'xml-apis'], [ group: 'org.apache.httpcomponents' ], [ name: 'commons-logging' ])

84

As you can see, you can either exclude dependencies by their artifact ID (also known as a module name) or any c and artifact IDs (if you use the Map notation). You may also come across exclude as well, but that can only ac Map:
runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { exclude "xml-apis" }

Using Ivy module configurations

If you use Ivy module configurations and wish to depend on a specific configuration of a module, dependencyConfiguration method to specify the configuration to use.
provided("my.org:web-service:1.0") { dependencyConfiguration "api" }

If the dependency configuration is not explicitly set, the configuration named "default" will be used (whi value for dependencies coming from Maven style repositories).

Where are the JARs?

With all these declarative dependencies, you may wonder where all the JARs end up. They have to go somewher Grails puts them into a directory, called the dependency cache, that resides on your local file system at user.ho You can change this either via the settings.groovy file:
grails.dependency.cache.dir = "${userHome}/.my-dependency-cache"

or in the dependency DSL:


grails.project.dependency.resolution = { cacheDir "target/ivy-cache" }

The settings.groovy option applies to all projects, so it's the preferred approach.

4.7.2 Dependency Repositories


Remote Repositories

Initially your BuildConfig.groovy does not use any remote public Maven repositories. There is a default grail that will locate the JAR files Grails needs from your Grails installation. To use a public repository, specify it in t block: 85

repositories { mavenCentral() }

In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Reposi ebr() method:
repositories { ebr() }

You can also specify a specific Maven repository to use by URL:


repositories { mavenRepo "http://repository.codehaus.org" }

and even give it a name:


repositories { mavenRepo name: "Codehaus", root: "http://repository.codehaus.org" }

so that you can easily identify it in logs.

Controlling Repositories Inherited from Plugins


A plugin you have installed may define a reference to a remote repository just as an application can. By default inherit this repository definition when you install the plugin. If you do not wish to inherit repository definitions from plugins then you can disable repository inheritance:
repositories { inherit false }

In this case your application will not inherit any repository definitions from plugins and it is down to you to (possibly internal) repository definitions.

Offline Mode

There are times when it is not desirable to connect to any remote repositories (whilst working on the train for ex you can use the offline flag to execute Grails commands and Grails will not connect to any remote repositories

86

grails --offline run-app

Note that this command will fail if you do not have the necessary dependencies in your local Ivy cach

You can also globally configure offline mode by setting grails.offline.mode to true in ~/.grails/s or in your project's BuildConfig.groovy file:
grails.offline.mode=true

Local Resolvers
If you do not wish to use a public Maven repository you can specify a flat file repository:
repositories { flatDir name:'myRepo', dirs:'/path/to/repo' }

To specify your local Maven cache (~/.m2/repository) as a repository:


repositories { mavenLocal() }

Custom Resolvers
If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:
/* * Configure our resolver. */ def libResolver = new org.apache.ivy.plugins.resolver.URLResolver() ['libraries', 'builds'].each { libResolver.addArtifactPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") libResolver.addIvyPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") } libResolver.name = "my-repository" libResolver.settings = ivySettings resolver libResolver

87

It's also possible to pull dependencies from a repository using SSH. Ivy comes with a dedicated resolver that y include in your project like so:
import org.apache.ivy.plugins.resolver.SshResolver repositories { ... def sshResolver = new SshResolver( name: "myRepo", user: "username", host: "dev.x.com", keyFile: new File("/home/username/.ssh/id_rsa"), m2compatible: true) sshResolver.addArtifactPattern( "/home/grails/repo/[organisation]/[artifact]/" + "[revision]/[artifact]-[revision].[ext]") sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy() sshResolver.changingPattern = ".*SNAPSHOT" sshResolver.setCheckmodified(true) resolver sshResolver }

Download the JSch JAR and add it to Grails' classpath to use the SSH resolver. You can do this by passing t command line:
grails -classpath /path/to/jsch compile|run-app|etc.

You can also add its path to the CLASSPATH environment variable but be aware this it affects many Java applic on Unix is to create an alias for grails -classpath ... so that you don't have to type the extra arguments

Authentication
If your repository requires authentication you can configure this using a credentials block:
credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" }

This can be placed in your USER_HOME/.grails/settings.groovy grails.project.ivy.authentication setting:

file

88

grails.project.ivy.authentication = { credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" } }

4.7.3 Debugging Resolution

If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underl log method:
// log level of Ivy resolver, either 'error', 'warn', // 'info', 'debug' or 'verbose' log "warn"

A common issue is that the checksums for a dependency don't match the associated JAR file, and so Ivy rejects helps ensure that the dependencies are valid. But for a variety of reasons some dependencies simply don't have va repositories, even if they are valid JARs. To get round this, you can disable Ivy's dependency checks like so:
grails.project.dependency.resolution = { log "warn" checksums false }

This is a global setting, so only use it if you have to.

4.7.4 Inherited Dependencies


By default every Grails application inherits several framework dependencies. This is done through the line:
inherits "global"

Inside the BuildConfig.groovy file. To exclude specific inherited dependencies you use the excludes me
inherits("global") { excludes "oscache", "ehcache" }

4.7.5 Providing Default Dependencies

89

Most Grails applications have runtime dependencies on several jar files that are provided by the Grails frame libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be in application may choose to exclude these jar files from the war. This is useful when the jar files will be provided would normally be the case if multiple Grails applications are deployed to the same container.

The dependency resolution DSL provides a mechanism to express that all of the default dependencies will container. This is done by invoking the defaultDependenciesProvided method and passing true as an a
grails.project.dependency.resolution = { defaultDependenciesProvided true // all of the default dependencies will // be "provided" by the container inherits "global" // inherit Grails' default dependencies repositories { grailsHome() } dependencies { } }

defaultDependenciesProvided must come before inherits, otherwise the Grails depend will be included in the war.

4.7.6 Snapshots and Other Changing Dependencies

Typically, dependencies are constant. That is, for a given combination of group, name and version the jar (o to will never change. The Grails dependency management system uses this fact to cache dependencies in orde download them from the source repository each time. Sometimes this is not desirable. For example, many convention of a snapshot (i.e. a dependency with a version number ending in -SNAPSHOT) that can change fro still retaining the same version number. We call this a "changing dependency".

Whenever you have a changing dependency, Grails will always check the remote repository for a new version. Mo a changing dependency is encountered during dependency resolution its last modified timestamp in the local cach the last modified timestamp in the dependency repositories. If the version on the remote server is deemed to be n in the local cache, the new version will be downloaded and used.

{info} Be sure to read the next section on Dependency Resolution Caching in addition to this one as dependencies. {info}

All dependencies (jars and plugins) with a version number ending in -SNAPSHOT are implicitly considered to b You can also explicitly specify that a dependency is changing by setting the changing flag in the dependency DSL
runtime ('org.my:lib:1.2.3') { changing = true }

There is a caveat to the support for changing dependencies that you should be aware of. Grails will stop looking fo dependency once it finds a remote repository that has the dependency. Consider the following setup: 90

grails.project.dependency.resolution = { repositories { mavenLocal() mavenRepo "http://my.org/repo" } dependencies { compile "myorg:mylib:1.0-SNAPSHOT" }

In this example we are using the local maven repository and a remote network maven repository. Assuming dependency and the local Maven cache do not contain the dependency but the remote repository does, when we resolution the following actions will occur: maven local repository is searched, dependency not found maven network repository is searched, dependency is downloaded to the cache and used Note that the repositories are checked in the order they are defined in the BuildConfig.groovy file.

If we perform dependency resolution again without the dependency changing on the remote server, the following w maven local repository is searched, dependency not found maven network repository is searched, dependency is found to be the same age as the version in the updated (i.e. downloaded)

Later on, a new version of mylib 1.0-SNAPSHOT is published changing the version on the server. The n dependency resolution, the following will happen: maven local repository is searched, dependency not found

maven network repository is searched, dependency is found to newer than version in the cache so w downloaded to the cache) So far everything is working well.

Now we want to test some local changes to the mylib library. To do this we build it locally and install it to th (how doesn't particularly matter). The next time we perform a dependency resolution, the following will occur:

maven local repository is searched, dependency is found to newer than version in the cache so will be update the cache) maven network repository is NOT searched as we've already found the dependency This is what we wanted to occur.

Later on, a new version of mylib 1.0-SNAPSHOT is published changing the version on the server. The n dependency resolution, the following will happen:

maven local repository is searched, dependency is found to be the same age as the version in the cache s (i.e. downloaded) maven network repository is NOT searched as we've already found the dependency

This is likely to not be the desired outcome. We are now out of sync with the latest published snapshot and will c the version from the local maven repository. 91

The rule to remember is this: when resolving a dependency, Grails will stop searching as soon as it finds a re dependency at the specified version number. It will not continue searching all repositories trying to find a mo instance.

To remedy this situation (i.e. build against the newer version of mylib 1.0-SNAPSHOT in the remote repositor Delete the version from the local maven repository, or Reorder the repositories in the BuildConfig.groovy file

Where possible, prefer deleting the version from the local maven repository. In general, when you have finish locally built SNAPSHOT always try to clear it from the local maven repository.

This changing dependency behaviour is an unmodifiable characteristic of the underlying depen management system that Grails uses, Apache Ivy. It is currently not possible to have Ivy sea repositories to look for newer versions (in terms of modification date) of the same dependency (i.e. th combination of group, name and version).

4.7.7 Dependency Reports

As mentioned in the previous section a Grails application consists of dependencies inherited from the framework and the application dependencies itself. To obtain a report of an application's dependencies you can run the dependency-report command:
grails dependency-report

By default this will generate reports in the target/dependency-report directory. You can specify which you want a report for by passing an argument containing the configuration name:
grails dependency-report runtime

4.7.8 Plugin JAR Dependencies


Specifying Plugin JAR dependencies

The way in which you specify dependencies for a plugin is identical to how you specify dependencies in an applic is installed into an application the application automatically inherits the dependencies of the plugin. To define a dependency that is resolved for use with the plugin but not exported to the application then you property of the dependency:
test('org.spockframework:spock-core:0.5-groovy-1.8') { export = false }

92

In this case the Spock dependency will be available only to the plugin and not resolved as an application depende you're using the Map syntax:
test group: 'org.spockframework', name: 'spock-core', version: '0.5-groovy-1.8', export: false

You can use exported = false instead of export = false, but we recommend the latter b it's consistent with the Map argument.

Overriding Plugin JAR Dependencies in Your Application

If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can ov resolves its dependencies inside an application using exclusions. For example:
plugins { compile(":hibernate:$grailsVersion") { excludes "javassist" } } dependencies { runtime "javassist:javassist:3.4.GA" }

In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion u method, effectively excluding the javassist library as a dependency.

4.7.9 Maven Integration

When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed t dependencies with Maven's pom.xml file.

However, if you would like to continue using Grails regular commands like run-app, test-app and so on then command line to load dependencies from the Maven pom.xml file instead. To do so simply add the following line to your BuildConfig.groovy:
grails.project.dependency.resolution = { pom true .. }

The line pom true tells Grails to parse Maven's pom.xml and load dependencies from there.

4.7.10 Deploying to a Maven Repository


If you use Maven to build your Grails project, you can use the standard Maven targets mvn install and mvn can deploy a Grails project or plugin to a Maven repository using the maven-publisher plugin.

93

The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories additional targets added by the plugin: maven-install - Installs a Grails project or plugin into your local Maven cache maven-deploy - Deploys a Grails project or plugin to a remote Maven repository

By default this plugin will automatically generate a valid pom.xml for you unless a pom.xml is already pres project, in which case this pom.xml file will be used.

maven-install
The maven-install command will install the Grails project or plugin artifact into your local Maven cache:
grails maven-install

In the case of plugins, the plugin zip file will be installed, whilst for application the application WAR file will be i

maven-deploy
The maven-deploy command will deploy a Grails project or plugin into a remote Maven repository:
grails maven-deploy

It is assumed that you have specified the necessary <distributionManagement> configuration within a p specify the id of the remote repository to deploy to:
grails maven-deploy --repository=myRepo

The repository argument specifies the 'id' for the repository. Configure the details of the repository specifi your grails-app/conf/BuildConfig.groovy file or in your $USER_HOME/.grails/settings.g
grails.project.dependency.distribution = { localRepository = "/path/to/my/local" remoteRepository(id: "myRepo", url: "http://myserver/path/to/repo") }

The syntax for configuring remote repositories matches the syntax from the remoteRepository element in the A example the following XML:
<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>

Can be expressed as: 94

remoteRepository(id: "myRepo", url: "scp://localhost/www/repository") { authentication username: "...", privateKey: "${userHome}/.ssh/id_dsa" }

By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http: specify a different protocol you can do:
grails maven-deploy --repository=myRepo --protocol=webdav

The available protocols are: http scp scpexe ftp webdav

Groups, Artifacts and Versions

Maven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from conventions or plugin descriptor.
Projects

For applications this plugin will use the Grails application name and version provided by Grails when generating t change the version you can run the set-version command:
grails set-version 0.2

The Maven groupId will be the same as the project name, unless you specify a different one in Config.groovy:
grails.project.groupId="com.mycompany"

Plugins

With a Grails plugin the groupId and version are taken from the following properties in the Grail descriptor:
String groupId = 'myOrg' String version = '0.1'

95

The 'artifactId' is taken from the plugin name. For example if you have a plugin called FeedsGrailsPlugi will be "feeds". If your plugin does not specify a groupId then this defaults to "org.grails.plugins".

4.7.11 Plugin Dependencies

As of Grails 1.3 you can declaratively specify plugins as dependencies via the dependency DSL instead of us command:
grails.project.dependency.resolution = { repositories { } plugins { runtime ':hibernate:1.2.1' } dependencies { } }

If you don't specify a group id the default plugin group id of org.grails.plugins is used. You can spe version of a particular plugin by using "latest.integration" as the version number:
plugins { runtime ':hibernate:latest.integration' }

Integration vs. Release

The "latest.integration" version label will also include resolving snapshot versions. To not include snapshot v "latest.release" label:
plugins { runtime ':hibernate:latest.release' }

The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN Grails repository then you should use "latest.integration". And of course if you use a Maven repository with an alternative group id you can specify a group id:
plugins { runtime 'mycompany:hibernate:latest.integration' }

96

Plugin Exclusions

You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For examp
plugins { runtime(':weceem:0.8') { excludes "searchable" } }

Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" p excludes method you can tell Grails not to transitively install the searchable plugin. You can combine this te alternative version of a plugin:
plugins { runtime(':weceem:0.8') { excludes "searchable" // excludes most recent version } runtime ':searchable:0.5.4' // specifies a fixed searchable version }

You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolve
plugins { runtime(':weceem:0.8') { transitive = false } runtime ':searchable:0.5.4' // specifies a fixed searchable version }

4.7.12 Caching of Dependency Resolution Results

As a performance optimisation, Grails does not resolve dependencies for every command invocation. Even w dependencies downloaded and cached, resolution may take a second or two. To minimise this cost, Grails dependency resolution (i.e. the location on the local file system of all of the declared dependencies, typically in cache) and reuses this result for subsequent commands when it can reasonably expect that nothing has changed. Grails only performs dependency resolution under the following circumstances: The project is clean (i.e. fresh checkout or after grails clean) The BuildConfig.groovy file has changed since the last command was run The --refresh-dependencies command line switch is provided to the command (any command) The refresh-dependencies command is the command being executed

Generally, this strategy works well and you can ignore dependency resolution caching. Every time you change yo modify BuildConfig.groovy) Grails will do the right thing and resolve your new dependencies.

However, when you have changing or dynamic dependencies you will have to consider dependency resolution cac

97

{info} A changing dependency is one whose version number does not change, but its contents do (like a SNA dependency is one that is defined as one of many possible options (like a dependency with a version range, or sym like latest.integration). {info}

Both changing and dynamic dependencies are influenced by the environment. With caching active, any changes to effectively ignored. For example, your project may not automatically fetch the very latest version of a depe latest.integration. Or if you declare a SNAPSHOT dependency, you may not automatically get the latest server. To ensure you have the correct version of a changing or dynamic dependency in your project, you can: clean the project run the refresh-dependencies command run any command with the --refresh-dependencies switch; or make a change to BuildConfig.groovy

If you have your CI builds configured to not perform clean builds, it may be worth adding the --refresh-dep to the command you use to build your projects.

98

5 The Command Line


Grails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant. However, Grails takes it further through the use of convention and the grails command. When you type:
grails [command name]

Grails searches in the following directories for Gant scripts to execute: USER_HOME/.grails/scripts PROJECT_HOME/scripts PROJECT_HOME/plugins/*/scripts GRAILS_HOME/scripts Grails will also convert command names that are in lower case form such as run-app into camel case. So typing
grails run-app

Results in a search for the following files: USER_HOME/.grails/scripts/RunApp.groovy PROJECT_HOME/scripts/RunApp.groovy PLUGINS_HOME/*/scripts/RunApp.groovy GLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovy GRAILS_HOME/scripts/RunApp.groovy If multiple matches are found Grails will give you a choice of which one to execute.

When Grails executes a Gant script, it invokes the "default" target defined in that script. If there is no default, Gr error. To get a list of all commands and some help about the available commands type:
grails help

which outputs usage instructions and the list of commands Grails is aware of:

99

Usage (optionals marked with *): grails [environment]* [target] [arguments]* Examples: grails dev run-app grails create-app books Available Targets (type grails help 'target-name' for more info): grails bootstrap grails bug-report grails clean grails compile ...

Refer to the Command Line reference in the Quick Reference menu of the reference guide fo information about individual commands

It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with runfor example want to set a higher maximum heap size. The Grails command will use any JVM options prov JAVA_OPTS environment variable, but you can also specify a Grails-specific environment variable too:
export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m" grails run-app

non-interactive mode

When you run a script manually and it prompts you for information, you can answer the questions and continue ru when you run a script as part of an automated process, for example a continuous integration build server, there's the questions. So you can pass the --non-interactive switch to the script command to tell Grails to accept t any questions, for example whether to install a missing plugin. For example:
grails war --non-interactive

5.1 Interactive Mode

Interactive mode is the a feature of the Grails command line which keeps the JVM running and allows for commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a li

100

If you need to open a file whilst within interactive mode you can use the open command which will TAB comple

101

Even better, the open command understands the logical aliases 'test-report' and 'dep-report', which will open the dependency reports respectively. In other words, to open the test report in a browser simply execute open tes even open multiple files at once: open test-report test/unit/MyTests.groovy will open the HTM browser and the MyTests.groovy source file in your text editor. TAB completion also works for class names after the create-* commands:

If you need to run an external process whilst interactive mode is running you can do so by starting the command w

102

Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate o as 'ls', 'cat', 'git', etc.

5.2 Creating Gant Scripts

You can create your own Gant scripts by running the create-script command from the root of your project. For e command:
grails create-script compile-sources

Will create a script called scripts/CompileSources.groovy. A Gant script itself is similar to a regular that it supports the concept of "targets" and dependencies between them:
target(default:"The default target is the one that gets executed by Grails") { depends(clean, compile) } target(clean:"Clean out things") { ant.delete(dir:"output") } target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }

As demonstrated in the script above, there is an implicit ant variable (an instance of groovy.util.AntBu access to the Apache Ant API. 103

In previous versions of Grails (1.0.3 and below), the variable was Ant, i.e. with a capital first letter.

You can also "depend" on other targets using the depends method demonstrated in the default target above.

The default target

In the example above, we specified a target with the explicit name "default". This is one way of defining the defa An alternative approach is to use the setDefaultTarget() method:
target("clean-compile": "Performs a clean compilation on the app source") { depends(clean, compile) } target(clean:"Clean out things") { ant.delete(dir:"output") } target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") } setDefaultTarget("clean-compile")

This lets you call the default target directly from other scripts if you wish. Also, although we hav setDefaultTarget() at the end of the script in this example, it can go anywhere as long as it comes after ("clean-compile" in this case).

Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major adva One thing we would say is that if you want to allow other scripts to call your "default" target, you should move that doesn't have a default target at all. We'll talk some more about this in the next section.

5.3 Re-using Grails scripts

Grails ships with a lot of command line functionality out of the box that you may find useful in your own scrip line reference in the reference guide for info on all the commands). Of particular use are the compile, package and The bootstrap script for example lets you bootstrap a Spring ApplicationContext instance to get access to the data integration tests use this):
includeTargets << grailsScript("_GrailsBootstrap") target ('default': "Database stuff") { depends(configureProxy, packageApp, classpath, loadApp, configureApp) Connection c try { c = appCtx.getBean('dataSource').getConnection() // do something with connection } finally { c?.close() } }

104

Pulling in targets from other scripts

Gant lets you pull in all targets (except "default") from another Gant script. You can then depend upon or invoke t had been defined in the current script. The mechanism for doing this is the includeTargets property. Simp class to it using the left-shift operator:
includeTargets << new File("/path/to/my/script.groovy") includeTargets << gant.tools.Ivy

Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant d

Core Grails targets

As you saw in the example at the beginning of this section, you use neither the File- nor the clas includeTargets when including core Grails targets. Instead, you should use the special grailsScrip provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).

The syntax for the grailsScript() method is pretty straightforward: simply pass it the name of the Gra without any path information. Here is a list of Grails scripts that you could reuse: Script _GrailsSettings _GrailsEvents _GrailsClasspath _GrailsProxy _GrailsArgParsing _GrailsTest _GrailsRun Description

You really should include this! Fortunately, it is included automatically by all other G _GrailsProxy, so you usually don't have to include it explicitly.

Include this to fire events. Adds an event(String eventName, List args) meth by almost all other Grails scripts.

Configures compilation, test, and runtime classpaths. If you want to use or play with them Again, included by almost all other Grails scripts.

If you don't have direct access to the internet and use a proxy, include this script to configure proxy. Provides a parseArguments target that does what it says on the tin: parses the arguments when they run your script. Adds them to the argsMap property. Contains all the shared test code. Useful if you want to add any extra tests. Provides all you need to run the application in the configured servlet container, either runAppHttps) or from a WAR file (runWar/runWarHttps).

There are many more scripts provided by Grails, so it is worth digging into the scripts themselves to find out wh available. Anything that starts with an "_" is designed for reuse.

Script architecture

You maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way script is internal , or in other words that it has not corresponding "command". So you can't run "grails _grails-s That is also why they don't have a default target.

105

Internal scripts are all about code sharing and reuse. In fact, we recommend you take a similar approach in you your targets into an internal script that can be easily shared, and provide simple command scripts that pars arguments and delegate to the targets in the internal script. For example if you have a script that runs some fun split it like this:
./scripts/FunctionalTests.groovy: includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy") target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) } ./scripts/_FunctionalTests.groovy: includeTargets << grailsScript("_GrailsTest") target(runFunctionalTests: "Run functional tests.") { depends(...) }

Here are a few general guidelines on writing scripts: Split scripts into a "command" script and an internal one. Put the bulk of the implementation in the internal script. Put argument parsing into the "command" script. To pass arguments to a target, create some script variables and initialise them before calling the target.

Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass ar closures.

5.4 Hooking into Events

Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails targ

The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.

Defining event handlers

Event handlers are defined in scripts called _Events.groovy. Grails searches for these scripts in the following USER_HOME/.grails/scripts - user-specific event handlers PROJECT_HOME/scripts - applicaton-specific event handlers PLUGINS_HOME/*/scripts - plugin-specific event handlers GLOBAL_PLUGINS_HOME/*/scripts - event handlers provided by global plugins

Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of h automatically by Grails, so you just need to declare them in the relevant _Events.groovy file.

Event handlers are blocks defined in _Events.groovy, with a name beginning with "event". The following e your /scripts directory to demonstrate the feature: 106

eventCreatedArtefact = { type, name -> println "Created $type $name" } eventStatusUpdate = { msg -> println msg } eventStatusFinal = { msg -> println msg }

You can see here the three handlers eventCreatedArtefact, eventStatusUpdate, eventStatusFi some standard events, which are documented in the command line reference guide. For example the compil following events: CompileStart - Called when compilation starts, passing the kind of compile - source or tests CompileEnd - Called when compilation is finished, passing the kind of compile - source or tests

Triggering events
To trigger an event simply include the Init.groovy script and call the event() closure:
includeTargets << grailsScript("_GrailsEvents") event("StatusFinal", ["Super duper plugin action complete!"])

Common Events
Below is a table of some of the common events that can be leveraged:

107

Event StatusUpdate StatusError StatusFinal

Parameters message message message

Description Passed a string indicating current script status/progress Passed a string indicating an error message from the current script Passed a string indicating the final script status message, i.e. when even if the target does not exit the scripting environment

CreatedArtefact artefactType,artefactName Called when a create-xxxx script has completed and created an artef CreatedFile Exiting fileName returnCode

Called whenever a project source filed is created, not including files by Grails Called when the scripting environment is about to exit cleanly Called after a plugin has been installed

PluginInstalled pluginName CompileStart CompileEnd DocStart DocEnd kind kind kind kind

Called when compilation starts, passing the kind of compile - source

Called when compilation is finished, passing the kind of compile - s Called when documentation generation is about to start - javadoc or

Called when documentation generation has ended - javadoc or groov

SetClasspath

rootLoader

Called during classpath initialization so plugins can augment rootLoader.addURL(...). Note that this augments the classpath aft loaded so you cannot use this to load a class that your event scr although you can do this if you load the class by name.

PackagingEnd

none

Called at the end of packaging (which is called prior to the Tomcat and after web.xml is generated)

5.5 Customising the build

Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mea it. In this section, we look at how you can influence and modify the standard Grails build.

The defaults

The core of the Grails build configuration is the grails.util.BuildSettings class, which contains information. It controls where classes are compiled to, what dependencies the application has, and other such settin Here is a selection of the configuration options and their default values:

108

Property grailsWorkDir projectWorkDir classesDir testClassesDir testReportsDir resourcesDir

Config option grails.work.dir grails.project.work.dir grails.project.class.dir grails.project.test.class.dir grails.project.test.reports.dir grails.project.resource.dir

Default value $USER_HOME/.grails/<grailsVersion> <grailsWorkDir>/projects/<baseDirName> <projectWorkDir>/classes <projectWorkDir>/test-classes <projectWorkDir>/test/reports <projectWorkDir>/resources <projectWorkDir>/plugins <grailsWorkDir>/global-plugins

projectPluginsDir grails.project.plugins.dir globalPluginsDir grails.global.plugins.dir verboseCompile

grails.project.compile.verbose false

The BuildSettings class has some other properties too, but they should be treated as read-only: Property baseDir userHome grailsHome grailsVersion grailsEnv config Description The location of the project. The user's home directory. The location of the Grails installation in use (may be null). The version of Grails being used by the project. The current Grails environment.

The configuration settings defined in the project's BuildConfig.groovy file. Acc same way as you access runtime settings: grailsSettings.config.foo.bar.he

compileDependencies A list of compile-time project dependencies as File instances. testDependencies A list of test-time project dependencies as File instances.

runtimeDependencies A list of runtime-time project dependencies as File instances. Of course, these properties aren't much good if you can't get hold of them. Fortunately that's easy to BuildSettings is available to your scripts as the grailsSettings script variable. You can also access using the grails.util.BuildSettingsHolder class, but this isn't recommended.

Overriding the defaults

All of the properties in the first table can be overridden by a system property or a configuration option - simply us name. For example, to change the project working directory, you could either run this command:
grails -Dgrails.project.work.dir=work compile

or add this option to your grails-app/conf/BuildConfig.groovy file:

109

grails.project.work.dir = "work"

Note that the default values take account of the property values they depend on, so setting the project working dire also relocate the compiled classes, test classes, resources, and plugins.

What happens if you use both a system property and a configuration option? Then the system property w precedence over the BuildConfig.groovy file, which in turn takes precedence over the default values.

The BuildConfig.groovy file is a sibling of grails-app/conf/Config.groovy - the former conta affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the opt either: you will find build configuration options dotted around the documentation, such as ones for specify embedded servlet container runs on or for determining what files get packaged in the WAR file.

Available build settings


Name grails.server.port.http grails.server.port.https grails.config.base.webXml Description Port to run the embedded servlet container on ("run-app" and "run-war"). Integer.

Port to run the embedded servlet container on for HTTPS ("run-app --https" and Integer.

Path to a custom web.xml file to use for the application (alternative to using the we

Legacy approach to adding extra dependencies to the compiler classpath. Set it to "fileset()" entries. These entries will be processed by an AntBuilder so the s grails.compiler.dependencies form of the corresponding XML elements in an Ant build file, e.g. "$basedir/lib", include: "**/*.class). grails.testing.patterns grails.testing.nameSuffix grails.project.war.file grails.war.dependencies grails.war.copyToWebApp

A list of Ant path patterns that let you control which files are included in the tests. not include the test case suffix, which is set by the next property.

By default, tests are assumed to have a suffix of "Tests". You can change it to a setting this option. For example, another common suffix is "Test". A string containing the file path of the generated WAR file, along with its extension). For example, "target/my-app.war".

A closure containing "fileset()" entries that allows you complete control over wha "WEB-INF/lib" directory.

A closure containing "fileset()" entries that allows you complete control over wha the WAR. It overrides the default behaviour of including everything under "web-ap

grails.war.resources grails.project.web.xml

A closure that takes the location of the staging directory as its first argument. Y tasks to do anything you like. It is typically used to remove files from the staging directory is jar'd up into a WAR. The location to generate Grails' web.xml to

Reloading Agent Cache Directory

110

Grails uses an agent based reloading system in the development environment that allows source code changes to b application is running. This reloading agent caches information needed to carry out the reloading efficien information is stored under <USER_HOME_DIR>/.grails/.slcache/. The GRAILS_AGENT_CACH variable may be assigned a value to cause this cache information to be stored somewhere else. Note that this is environment variable, not a JVM system property or a property which may be defined in BuildConfig.groo be defined as an environment variable because the agent cache directory must be configured very early in the before any Grails code is executed.

5.6 Ant and Maven

If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, y sheep of the family when you use the Grails command line to build your application. Fortunately, you can easil build system into the main build tools in use today (well, the ones in use in Java projects at least).

Ant Integration
When you create a Grails application with the create-app command, Grails doesn't automatically create an Ant you can generate one with the integrate-with command:

grails integrate-with --ant

This creates a build.xml file containing the following targets: clean - Cleans the Grails application compile - Compiles your application's source code test - Runs the unit tests run - Equivalent to "grails run-app" war - Creates a WAR file deploy - Empty by default, but can be used to implement automatic deployment Each of these can be run by Ant, for example:
ant war

The build file is configured to use Apache Ivy for dependency management, which means that it will automatic requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to particularly useful for continuous integration systems such as CruiseControl or Jenkins.

It uses the Grails Ant task to hook into the existing Grails build system. The task lets you run any Grails script th the ones used by the generated build file. To use the task, you must first declare it:
<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>

111

This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR art be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to table shows you what attributes are available: Attribute home classpathref script args environment includeRuntimeClasspath Description The location of the Grails installation directory to use for the build. Required

Yes, unless class

Classpath to load Grails from. Must include the "grails-bootstrap" Yes, unless hom artifact and should include "grails-scripts". classpath ele The name of the Grails script to run, e.g. "TestApp". The arguments to pass to the script, e.g. "-unit -xml". The Grails environment to run the script in. Yes.

No. Defaults to "

No. Defaults to t

Advanced setting: adds the application's runtime classpath to the No. Defaults to t build classpath if true.

The task also supports the following nested elements, all of which are standard Ant path structures: classpath - The build classpath (used to load Gant and the Grails scripts). compileClasspath - Classpath used to compile the application's classes.

runtimeClasspath - Classpath used to run the application and package the WAR. Typically inc @compileClasspath.

testClasspath - Classpath used to compile and run the tests. Typically includes everything in runtime

How you populate these paths is up to you. If you use the home attribute and put your own dependencies in the you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for

Maven Integration
Grails provides integration with Maven 2 with a Maven plugin.

Preparation

In order to use the Maven plugin, all you need is Maven 2 installed and set up. This is because you no longer n separately to use it with Maven!

The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It w work with earlier versions.

The default mvn setup DOES NOT supply sufficient memory to run the Grails environmen recommend that you add the following environment variable setting to prevent poor performance: export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"

Creating a Grails Maven Project


112

Using the create-pom command you can generate a valid Maven pom.xml file for any existing Grails projec an example:
$ grails create-app myapp $ cd myapp $ grails create-pom com.mycompany

The create-pom command expects a group id as an argument. The name and the version are application.properties of the application. The Maven plugin will keep the version in the pom.xml in in application.properties. The following standard Maven commands are then possible: compile - Compiles a Grails project package - Builds a WAR file from the Grails project. install - Builds a WAR file (or plugin zip/jar if a plugin) and installs it into your local Maven cache test - Runs the tests of a Grails project clean - Cleans the Grails project Other standard Maven commands will likely work too. You can also use some of the Grails commands that have been wrapped as Maven goals: grails:create-controller - Calls the create-controller command grails:create-domain-class - Calls the create-domain-class command grails:create-integration-test - Calls the create-integration-test command grails:create-pom - Creates a new Maven POM for an existing Grails project grails:create-script - Calls the create-script command grails:create-service - Calls the create-service command grails:create-taglib - Calls the create-tag-lib command grails:create-unit-test - Calls the create-unit-test command grails:exec - Executes an arbitrary Grails command line script grails:generate-all - Calls the generate-all command grails:generate-controller - Calls the generate-controller command grails:generate-views - Calls the generate-views command grails:install-templates - Calls the install-templates command grails:list-plugins - Calls the list-plugins command grails:package - Calls the package command grails:run-app - Calls the run-app command

113

For a complete, up to date list, run mvn grails:help

Creating a Grails Maven Project using the Archetype


You can create a Maven Grails project without having Grails installed, simply run the following command:
mvn archetype:generate -DarchetypeGroupId=org.grails \ -DarchetypeArtifactId=grails-maven-archetype \ -DarchetypeVersion=2.1.0.RC1 \ -DgroupId=example -DartifactId=my-app

Choose whichever grails version, group ID and artifact ID you want for your application, but everything else mu will create a new Maven project with a POM and a couple of other files. What you won't see is anything tha application. So, the next step is to create the project structure that you're used to. But first, to set target JDK to Open my-app/pom.xml and change
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin>

to
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin>

Then you're ready to create the project structure:


cd my-app mvn initialize

Defining Plugin Dependencies

All Grails plugins are published to a standard Maven repository located at . When using the Maven plugin for G that this repository is declared in your list of remote repositories:
<repository> <id>grails-plugins</id> <name>grails-plugins</name> <url>http://repo.grails.org/grails/plugins</url> </repository>

114

With this done you can declare plugin dependencies within your pom.xml file:
<dependency> <groupId>org.grails.plugins</groupId> <artifactId>database-migration</artifactId> <version>1.1</version> <scope>runtime</scope> <type>zip</type> </dependency>

Note that the type element must be set to zip.

Forked Grails Execution

By default the Maven plugin will run Grails commands in-process, meaning that the Grails process occupies t Maven process. This can put strain on the Maven process for particularly large applications.

In this case it is recommended to use forked execution. Forked execution can be configured in the configura plugin:
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>${grails.version}</version> <configuration> <!-- Whether for Fork a JVM to run Grails commands --> <fork>true</fork> </configuration> <extensions>true</extensions> </plugin>

With this configuration in place a separate JVM will be forked when running Grails commands. If you wish to d forked you can add the forkDebug element:
<!-- Whether for Fork a JVM to run Grails commands --> <fork>true</fork> <forkDebug>true</forkDebug>

If you need to customize the memory of the forked process the following elements are available: forkMaxMemory - The maximum amount of heap (default 1024) forkMinMemory - The minimum amount of heap (default 512) forkPermGen - The amount of permgen (default 256)

Multi Module Maven Builds


The Maven plugin can be used to power multi-module Grails builds. The easiest way to set this create-multi-project-build command:

115

$ $ $ $

grails grails grails grails

create-app myapp create-plugin plugin1 create-plugin plugin2 create-multi-project-build org.mycompany:parent:1.0

Running mvn install will build all projects together. To enable the 'grails' command to read the POM BuildConfig.groovy to use the POM and resolve dependencies from your Maven local cache:
grails.project.dependency.resolution = { pom true repositories { mavenLocal() } }

By reading the pom.xml file you can do an initial mvn install from the parent project to build all plugins your local maven cache and then cd into your project and use the regular grails run-app command to run previously built plugins will be resolved from the local Maven cache.

Adding Grails commands to phases

The standard POM created for you by Grails already attaches the appropriate core Grails commands to their phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help thou attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure tests (using which ever plugin you have decided on) are run during the "integration-test" phase?

Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution"
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>2.1.0.RC2</version> <extensions>true</extensions> <executions> <execution> <goals> </goals> </execution> <!-- Add the "functional-tests" command to the "integration-test" phase --> <execution> <id>functional-tests</id> <phase>integration-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <command>functional-tests</command> </configuration> </execution> </executions> </plugin>

116

This also demonstrates the grails:exec goal, which can be used to run any Grails command. Simply p command as the command system property, and optionally specify the arguments with the args property:
mvn grails:exec -Dcommand=create-webtest -Dargs=Book

Debugging a Grails Maven Project

Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in deb
mvnDebug grails:run-app

The process will be suspended on startup and listening for a debugger on port 8000.

If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variabl with the default "mvn" command:
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005" mvn grails:run-app

Raising issues

If you come across any problems with the Maven integration, please raise a |http://jira.grails.org/browse/MAVEN.

5.7 Grails Wrapper

The Grails Wrapper allows a Grails application to built without having to install Grails and configure a GRAILS_ variable. The wrapper includes a small shell script and a couple of small bootstrap jar files that typically would be code control along with the rest of the project. The first time the wrapper is executed it will download an installation. This wrapper makes it more simple to setup a development environment, configure CI and manag versions of Grails. When the application is upgraded to the next version of Grails, the wrapper is updated and che code control system and the next time developers update their workspace and run the wrapper, they will autom correct version of Grails.

Generating The Wrapper

The wrapper command can be used to generate the wrapper shell scripts and supporting jar files. Execute the wra top of an existing Grails project.
grails wrapper

In order to do this of course Grails must be installed and configured. This is only a requirement for bootstrappin the wrapper is generated there is no need to have a Grails installation configured in order to use the wrapper. See the wrapper command documentation for details about command line arguments.

117

By default the wrapper command will generate a grailsw shell script and grailsw.bat batch file at the addition to those, a wrapper/ directory (the name of the directory is configurable via command line options contains some support files which are necessary to run the wrapper. All of these files should be checked into the system along with the rest of the project. This allows developers to check the project out of source code control a using the wrapper to execute Grails commands without having to install and configure Grails.

Using The Wrapper


The wrapper scripts except all of the same arguments the normal grails command supports.
./grailsw create-domain-class com.demo.Person ./grailsw run-app ./grailsw test-app unit: etc...

118

6 Object Relational Mapping (GORM)

Domain classes are core to any business application. They hold state about business processes and hopefully also They are linked together through relationships; one-to-one, one-to-many, or many-to-many.

GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along of Grails, there is far less configuration involved in creating Grails domain classes.

You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write doma still use dynamic persistent methods. Below is a preview of GORM in action:
def book = Book.findByTitle("Groovy in Action") book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()

6.1 Quick Start Guide


A domain class can be created with the create-domain-class command:
grails create-domain-class helloworld.Person

If no package is specified with the create-domain-class script, Grails automatically uses the appl name as the package name.

This will create a class at the location grails-app/domain/helloworld/Person.groovy such as the o


package helloworld class Person { }

If you have the dbCreate property set to "update", "create" or "create-drop" on your DataSource, will automatically generate/modify the database tables for you. You can customize the class by adding properties:
class Person { String name Integer age Date lastVisit }

119

Once you have a domain class try and manipulate it with the shell or console by typing:
grails console

This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext

6.1.1 Basic CRUD


Try performing some basic CRUD (Create/Read/Update/Delete) operations.

Create
To create a domain class use Map constructor to set its properties and call save:
def p = new Person(name: "Fred", age: 40, lastVisit: new Date()) p.save()

The save method will persist your class to the database using the underlying Hibernate ORM layer.

Read
Grails transparently adds an implicit id property to your domain class which you can use for retrieval:
def p = Person.get(1) assert 1 == p.id

This uses the get method that expects a database identifier to read the Person object back from the database. object in a read-only state by using the read method:
def p = Person.read(1)

In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persis explicitly call the save method then the object is placed back into a read-write state. In addition, you can also load a proxy for an instance by using the load method:
def p = Person.load(1)

This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied i exception if no record is found for the specified id.

Update

120

To update an instance, change some properties and then call save again:
def p = Person.get(1) p.name = "Bob" p.save()

Delete
To delete an instance use the delete method:
def p = Person.get(1) p.delete()

6.2 Domain Modelling in GORM

When building Grails applications you have to consider the problem domain you are trying to solve. For example an Amazon-style bookstore you would be thinking about books, authors, customers and publishers to name a few.

These are modeled in GORM as Groovy classes, so a Book class may have a title, a release date, an ISBN numbe few sections show how to model the domain in GORM. To create a domain class you run the create-domain-class command as follows:
grails create-domain-class org.bookstore.Book

The result will be a class at grails-app/domain/org/bookstore/Book.groovy:


package org.bookstore class Book { }

This class will map automatically to a table in the database called book (the same name as the class). This beha through the ORM Domain Specific Language Now that you have a domain class you can define its properties as Java types. For example:
package org.bookstore class Book { String title Date releaseDate String ISBN }

Each property is mapped to a column in the database, where the convention for column names is all low underscores. For example releaseDate maps onto a column release_date. The SQL types are auto-de types, but can be customized with Constraints or the ORM DSL. 121

6.2.1 Association in GORM

Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relat the direction it is defined.

6.2.1.1 Many-to-one and one-to-one

A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain example:
Example A

class Face { Nose nose }

class Nose { }

In this case we have a unidirectional many-to-one relationship from Face to Nose. To make this relationship bi other side as follows:
Example B

class Face { Nose nose }

class Nose { static belongsTo = [face:Face] }

In this case we use the belongsTo setting to say that Nose "belongs to" Face. The result of this is that we can a Nose instance to it and when we save or delete the Face instance, GORM will save or delete the Nose. In ot deletes will cascade from Face to the associated Nose:
new Face(nose:new Nose()).save()

The example above will save both face and nose. Note that the inverse is not true and will result in an error due to
new Nose(face:new Face()).save() // will cause an error

122

Now if we delete the Face instance, the Nose will go too:


def f = Face.get(1) f.delete() // both Face and Nose deleted

To make the relationship a true one-to-one, use the hasOne property on the owning side, e.g. Face:
Example C

class Face { static hasOne = [nose:Nose] }

class Nose { Face face }

Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the f stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relations Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:
class Face { static hasOne = [nose:Nose] static constraints = { nose unique: true } }

class Nose { Face face }

6.2.1.2 One-to-many

A one-to-many relationship is when one class, example Author, has many instances of another class, example Bo define such a relationship with the hasMany setting:
class Author { static hasMany = [books: Book] String name }

123

class Book { String title }

In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join

The ORM DSL allows mapping unidirectional relationships using a foreign key association instead

Grails will automatically inject a property of type java.util.Set into the domain class based on the hasMan used to iterate over the collection:
def a = Author.get(1) for (book in a.books) { println book.title }

The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily init on first access. This can lead to the n+1 problem if you are not careful. If you need "eager" fetching you can use the ORM DSL or specify eager fetching as part of a query

The default cascading behaviour is to cascade saves and updates, but not deletes unless a belongsTo is also spec
class Author { static hasMany = [books: Book] String name }

class Book { static belongsTo = [author: Author] String title }

If you have two properties of the same type on the many side of a one-to-many you have to use mappedBy collection is mapped:
class Airport { static hasMany = [flights: Flight] static mappedBy = [flights: "departureAirport"] }

124

class Flight { Airport departureAirport Airport destinationAirport }

This is also true if you have multiple collections that map to different properties on the many side:
class Airport { static hasMany = [outboundFlights: Flight, inboundFlights: Flight] static mappedBy = [outboundFlights: "departureAirport", inboundFlights: "destinationAirport"] }

class Flight { Airport departureAirport Airport destinationAirport }

6.2.1.3 Many-to-many

Grails supports many-to-many relationships by defining a hasMany on both sides of the relationship and havin the owned side of the relationship:
class Book static static String } { belongsTo = Author hasMany = [authors:Author] title

class Author { static hasMany = [books:Book] String name }

Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this responsibility for persisting the relationship and is the only side that can cascade saves across. For example this will work and cascade saves:
new Author(name:"Stephen King") .addToBooks(new Book(title:"The Stand")) .addToBooks(new Book(title:"The Shining")) .save()

However this will only save the Book and not the authors!

125

new Book(name:"Groovy in Action") .addToAuthors(new Author(name:"Dierk Koenig")) .addToAuthors(new Author(name:"Guillaume Laforge")) .save()

This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibil relationship.

Grails' Scaffolding feature does not currently support many-to-many relationship and hence you mus the code to manage the relationship yourself

6.2.1.4 Basic Collection Types

As well as associations between different domain classes, GORM also supports mapping of basic collection typ following class creates a nicknames association that is a Set of String instances:
class Person { static hasMany = [nicknames: String] }

GORM will map an association like the above using a join table. You can alter various aspects of how the join t the joinTable argument:
class Person { static hasMany = [nicknames: String] static mapping = { hasMany joinTable: [name: 'bunch_o_nicknames', key: 'person_id', column: 'nickname', type: "text"] } }

The example above will map to a table that looks like the following: bunch_o_nicknames Table
--------------------------------------------| person_id | nickname | --------------------------------------------| 1 | Fred | ---------------------------------------------

6.2.2 Composition in GORM

As well as association, Grails supports the notion of composition. In this case instead of mapping classes onto s can be "embedded" within the current table. For example:

126

class Person { Address homeAddress Address workAddress static embedded = ['homeAddress', 'workAddress'] } class Address { String number String code }

The resulting mapping would looking like this:

If you define the Address class in a separate Groovy file in the grails-app/domain directo will also get an address table. If you don't want this to happen use Groovy's ability to define m classes per file and include the Address class below the Person class in grails-app/domain/Person.groovy file

6.2.3 Inheritance in GORM


GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:
class Content { String author }

class BlogEntry extends Content { URL url }

class Book extends Content { String ISBN }

class PodCast extends Content { byte[] audioStream }

127

In the above example we have a parent Content class and then various child classes with more specific behaviou

Considerations

At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called clas (Content) and its subclasses (BlogEntry, Book etc.), share the same table.

Table-per-hierarchy mapping has a down side in that you cannot have non-nullable properties with inher alternative is to use table-per-subclass which can be enabled with the ORM DSL

However, excessive use of inheritance and table-per-subclass can result in poor query performance due to the use In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy

Polymorphic Queries

The upshot of inheritance is that you get the ability to polymorphically query. For example using the list meth super class will return all subclasses of Content:
def content = Content.list() // list all blog entries, books and podcasts content = Content.findAllByAuthor('Joe Bloggs') // find all by author def podCasts = PodCast.list() // list only podcasts

6.2.4 Sets, Lists and Maps


Sets of Objects

By default when you define a relationship with GORM it is a java.util.Set which is an unordered collectio duplicates. In other words when you have:
class Author { static hasMany = [books: Book] }

The books property that GORM injects is a java.util.Set. Sets guarantee uniquenes but not order, which want. To have custom ordering you configure the Set as a SortedSet:
class Author { SortedSet books static hasMany = [books: Book] }

In this case a java.util.SortedSet implementation is used which means you must implement java.lan your Book class:

128

class Book implements Comparable { String title Date releaseDate = new Date() int compareTo(obj) { releaseDate.compareTo(obj.releaseDate) } }

The result of the above class is that the Book instances in the books collection of the Author class will be ordered b

Lists of Objects
To keep objects in the order which they were added and to be able to reference them by index like an array collection type as a List:
class Author { List books static hasMany = [books: Book] }

In this case when you add new elements to the books collection the order is retained in a sequential list indexed fro
author.books[0] // get the first book

The way this works at the database level is Hibernate creates a books_idx column where it saves the index o collection to retain this order at the database level. When using a List, elements must be added to the collection before being saved, otherwise Hibernate will org.hibernate.HibernateException: null index column for collection):
// This won't work! def book = new Book(title: 'The Shining') book.save() author.addToBooks(book) // Do it this way instead. def book = new Book(title: 'Misery') author.addToBooks(book) author.save()

Bags of Objects

If ordering and uniqueness aren't a concern (or if you manage these explicitly) then you can use the Hibernate B mapped collections. The only change required for this is to define the collection type as a Collection:

129

class Author { Collection books static hasMany = [books: Book] }

Since uniqueness and order aren't managed by Hibernate, adding to or removing from collections mapped as a Ba of all existing instances from the database, so this approach will perform better and require less memory than using

Maps of Objects
If you want a simple map of string/value pairs GORM can map this with the following:
class Author { Map books // map of ISBN:book names } def a = new Author() a.books = ["1590597583":"Grails Book"] a.save()

In this case the key and value of the map MUST be strings. If you want a Map of objects then you can do this:
class Book { Map authors static hasMany = [authors: Author] } def a = new Author(name:"Stephen King") def book = new Book() book.authors = [stephen:a] book.save()

The static hasMany property defines the type of the elements within the Map. The keys for the map must be strin

A Note on Collection Types and Performance

The Java Set type doesn't allow duplicates. To ensure uniqueness when adding an entry to a Set association Hib entire associations from the database. If you have a large numbers of entries in the association this can b performance.

The same behavior is required for List types, since Hibernate needs to load the entire association to maintain recommended that if you anticipate a large numbers of records in the association that you make the association bi link can be created on the inverse side. For example consider the following code:

130

def book = new Book(title:"New Grails Book") def author = Author.get(1) book.author = author book.save()

In this example the association link is being created by the child (Book) and hence it is not necessary to man directly resulting in fewer queries and more efficient code. Given an Author with a large number of associated B were to write code like the following you would see an impact on performance:
def book = new Book(title:"New Grails Book") def author = Author.get(1) author.addToBooks(book) author.save()

You could also model the collection as a Hibernate Bag as described above.

6.3 Persistence Basics

A key thing to remember about Grails is that under the surface Grails is using Hibernate for persistence. If yo background of using ActiveRecord or iBatis/MyBatis, Hibernate's "session" model may feel a little strange.

Grails automatically binds a Hibernate session to the currently executing request. This lets you use the save and d as other GORM methods transparently.

Transactional Write-Behind

A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call save necessarily perform any SQL operations at that point. Hibernate batches up SQL statements and executes them often at the end of the request when flushing and closing the session. This is typically done for you automatic manages your Hibernate session.

Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush i flush is triggered programmatically. One common case where Hibernate will flush cached updates is when perform cached information might be included in the query results. But as long as you're doing non-conflicting saves, they'll be batched until the session is flushed. This can be a significant performance boost for applications that writes.

Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a will execute SQL updates but the database will save the changes in its transaction queue and only finalize t transaction commits.

6.3.1 Saving and Updating


An example of using the save method can be seen below:
def p = Person.get(1) p.save()

131

This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. Bu when you want to control when those statements are executed or, in Hibernate terminology, when the session i you can use the flush argument to the save method:
def p = Person.get(1) p.save(flush: true)

Note that in this case all pending SQL statements including previous saves, deletes, etc. will be synchronized w also lets you catch any exceptions, which is typically useful in highly concurrent scenarios involving optimistic loc
def p = Person.get(1) try { p.save(flush: true) } catch (org.springframework.dao.DataIntegrityViolationException e) { // deal with exception }

Another thing to bear in mind is that Grails validates a domain instance every time you save it. If that valida instance will not be persisted to the database. By default, save() will simply return null in this case, but if y throw an exception you can use the failOnError argument:
def p = Person.get(1) try { p.save(failOnError: true) } catch (ValidationException e) { // deal with exception }

You can even change the default behaviour with a setting in Config.groovy, as described in the section o remember that when you are saving domain instances that have been bound with data provided by the user, the lik exceptions is quite high and you won't want those exceptions propagating to the end user. You can find out more about the subtleties of saving data in this article - a must read!

6.3.2 Deleting Objects


An example of the delete method can be seen below:
def p = Person.get(1) p.delete()

As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-pl flush argument:
def p = Person.get(1) p.delete(flush: true)

132

Using the flush argument lets you catch any errors that occur during a delete. A common error that may occ database constraint, although this is normally down to a programming or schema error. The following example s DataIntegrityViolationException that is thrown when you violate the database constraints:
def p = Person.get(1) try { p.delete(flush: true) } catch (org.springframework.dao.DataIntegrityViolationException e) { flash.message = "Could not delete person ${p.name}" redirect(action: "show", id: p.id) }

Note that Grails does not supply a deleteAll method as deleting data is discouraged and can often be avoi flags/logic. If you really need to batch delete data you can use the executeUpdate method to do batch DML statements:
Customer.executeUpdate("delete Customer c where c.name = :oldName", [oldName: "Fred"])

6.3.3 Understanding Cascading Updates and Deletes

It is critical that you understand how cascading updates and deletes work when using GORM. The key part belongsTo setting which controls which class "owns" a relationship.

Whether it is a one-to-one, one-to-many or many-to-many, defining belongsTo will result in updates cascad class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relations cascade. If you do not define belongsTo then no cascades will happen and you will have to manually save each object the one-to-many, in which case saves will cascade automatically if a new instance is in a hasMany collection). Here is an example:
class Airport { String name static hasMany = [flights: Flight] }

class Flight { String number static belongsTo = [airport: Airport] }

If I now create an Airport and add some Flights to it I can save the Airport and have the updates cascaded hence saving the whole object graph:

133

new Airport(name: "Gatwick") .addToFlights(new Flight(number: "BA3430")) .addToFlights(new Flight(number: "EZ0938")) .save()

Conversely if I later delete the Airport all Flights associated with it will also be deleted:
def airport = Airport.findByName("Gatwick") airport.delete()

However, if I were to remove belongsTo then the above cascading deletion code would not work. To unders look at the summaries below that describe the default behaviour of GORM with regards to specific associations. A GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.
Bidirectional one-to-many with belongsTo

class A { static hasMany = [bees: B] }

class B { static belongsTo = [a: A] }

In the case of a bidirectional one-to-many where the many side defines a belongsTo then the cascade strategy i one side and "NONE" for the many side.
Unidirectional one-to-many

class A { static hasMany = [bees: B] }

class B {

In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascad "SAVE-UPDATE".
Bidirectional one-to-many, no belongsTo

class A { static hasMany = [bees: B] }

class B { A a }

134

In the case of a bidirectional one-to-many where the many side does not define a belongsTo then the casc "SAVE-UPDATE" for the one side and "NONE" for the many side.
Unidirectional one-to-one with belongsTo

class A {

class B { static belongsTo = [a: A] }

In the case of a unidirectional one-to-one association that defines a belongsTo then the cascade strategy is owning side of the relationship (A->B) and "NONE" from the side that defines the belongsTo (B->A) Note that if you need further control over cascading behaviour, you can use the ORM DSL.

6.3.4 Eager and Lazy Fetching


Associations in GORM are by default lazy. This is best explained by example:
class Airport { String name static hasMany = [flights: Flight] }

class Flight { String number Location destination static belongsTo = [airport: Airport] }

class Location { String city String country }

Given the above domain classes and the following code:


def airport = Airport.findByName("Gatwick") for (flight in airport.flights) { println flight.destination.city }

GORM will execute a single SQL query to fetch the Airport instance, another to get its flights, and then 1 iteration over the flights association to get the current flight's destination. In other words you get N+1 querie original one to get the airport).

135

Configuring Eager Fetching


An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:
class Airport { String name static hasMany = [flights: Flight] static mapping = { flights lazy: false } }

In this case the flights association will be loaded at the same time as its Airport instance, although a executed to fetch the collection. You can also use fetch: 'join' instead of lazy: false , in which c execute a single query to get the airports and their flights. This works well for single-ended associations, but y with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of res point, you will likely end up with fewer results than you were expecting. The reason for this is quite technic problem arises from GORM using a left outer join.

So, the recommendation is currently to use fetch: 'join' for single-ended associations and lazy: false Be careful how and where you use eager loading because you could load your entire database into memory associations. You can find more information on the mapping options in the section on the ORM DSL.

Using Batch Fetching

Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you load your entire database into memory resulting in performance and memory problems. An alternative to eager fe fetching. You can configure Hibernate to lazily fetch results in "batches". For example:
class Airport { String name static hasMany = [flights: Flight] static mapping = { flights batchSize: 10 } }

In this case, due to the batchSize argument, when you iterate over the flights association, Hibernate will fe of 10. For example if you had an Airport that had 30 flights, if you didn't configure batch fetching you would the Airport and then 30 queries to fetch each flight. With batch fetching you get 1 query to fetch the Airp fetch each Flight in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strateg also be configured at the class level as follows:
class Flight { static mapping = { batchSize 10 } }

136

Check out part 3 of the GORM Gotchas series for more in-depth coverage of this tricky topic.

6.3.5 Pessimistic and Optimistic Locking


Optimistic Locking

By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate whi version value in a special version column in the database that is incremented after each update.

The version column gets read into a version property that contains the current versioned state of persisten can access:
def airport = Airport.get(10) println airport.version

When you perform updates Hibernate will automatically check the version property against the version column they differ will throw a StaleObjectException. This will roll back the transaction if one is active.

This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flush
def airport = Airport.get(10) try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }

The way you deal with the exception depends on the application. You could attempt a programmatic merge of t the user and ask them to resolve the conflict. Alternatively, if it becomes a problem you can resort to pessimistic locking.

The version will only be updated after flushing the session.

Pessimistic Locking

Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in t the implication that other read operations will be blocking until the lock is released. In Grails pessimistic locking is performed on an existing instance with the lock method:
def airport = Airport.get(10) airport.lock() // lock for update airport.name = "Heathrow" airport.save()

137

Grails will automatically deal with releasing the lock for you once the transaction has been committed. Howev what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread cou the record in between the call to get() and the call to lock(). To get around this problem you can use the static lock method that takes an id just like get:
def airport = Airport.lock(10) // lock for update airport.name = "Heathrow" airport.save()

In this case only SELECT..FOR UPDATE is issued. As well as the lock method you can also obtain a pessimistic locking using queries. For example using a dynamic
def airport = Airport.findByName("Heathrow", [lock: true])

Or using criteria:
def airport = Airport.createCriteria().get { eq('name', 'Heathrow') lock true }

6.3.6 Modification Checking

Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve you try to reload the instance using get Hibernate will return the current modified instance from its Session ca another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So G methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty che

isDirty
You can use the isDirty method to check if any field has been modified:
def airport = Airport.get(10) assert !airport.isDirty() airport.properties = params if (airport.isDirty()) { // do something based on changed state }

isDirty() does not currently check collection associations, but it does check all other per properties and associations. You can also check if individual fields have been modified: 138

def airport = Airport.get(10) assert !airport.isDirty() airport.properties = params if (airport.isDirty('name')) { // do something based on changed name }

getDirtyPropertyNames

You can use the getDirtyPropertyNames method to retrieve the names of modified fields; this may be empty but w
def airport = Airport.get(10) assert !airport.isDirty() airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { // do something based on changed value }

getPersistentValue
You can use the getPersistentValue method to retrieve the value of a modified field:
def airport = Airport.get(10) assert !airport.isDirty() airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { def currentValue = airport."$fieldName" def originalValue = airport.getPersistentValue(fieldName) if (currentValue != originalValue) { // do something based on changed value } }

6.4 Querying with GORM

GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object ori HQL. Depending on the complexity of the query you have the following options in order of flexibility and power: Dynamic Finders Where Queries Criteria Queries Hibernate Query Language (HQL)

In addition, Groovy's ability to manipulate collections with GPath and methods like sort, findAll and so on co results in a powerful combination. 139

However, let's start with the basics.

Listing instances
Use the list method to obtain all instances of a given class:
def books = Book.list()

The list method supports arguments to perform pagination:


def books = Book.list(offset:10, max:20)

as well as sorting:
def books = Book.list(sort:"title", order:"asc")

Here, the sort argument is the name of the domain class property that you wish to sort on, and the order argum ascending or desc for descending.

Retrieval by Database Identifier


The second basic form of retrieval is by database identifier using the get method:
def book = Book.get(23)

You can also obtain a list of instances for a set of identifiers using getAll:
def books = Book.getAll(23, 93, 81)

6.4.1 Dynamic Finders

GORM supports the concept of dynamic finders. A dynamic finder looks like a static method invocation, but the don't actually exist in any form at the code level.

Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a g example the Book class:
class Book { String title Date releaseDate Author author }

140

class Author { String name }

The Book class has properties such as title, releaseDate and author. These can be used by the fi methods in the form of "method expressions":
def book = Book.findByTitle("The Stand") book = Book.findByTitleLike("Harry Pot%") book = Book.findByReleaseDateBetween(firstDate, secondDate) book = Book.findByReleaseDateGreaterThan(someDate) book = Book.findByTitleLikeOrReleaseDateLessThan("%Something%", someDate)

Method Expressions

A method expression in GORM is made up of the prefix such as findBy followed by an expression that co properties. The basic form is:
Book.findBy([Property][Comparator][Boolean Operator])?[Property][Comparator]

The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:
def book = Book.findByTitle("The Stand") book = Book.findByTitleLike("Harry Pot%")

In the above example the first query is equivalent to equality whilst the latter, due to the Like comparator, is like expression. The possible comparators include:

141

InList - In the list of given values LessThan - less than a given value LessThanEquals - less than or equal a give value GreaterThan - greater than a given value GreaterThanEquals - greater than or equal a given value Like - Equivalent to a SQL like expression Ilike - Similar to a Like, except case insensitive NotEqual - Negates equality Between - Between two values (requires two arguments) IsNotNull - Not a null value (doesn't take an argument) IsNull - Is a null value (doesn't take an argument)

Notice that the last three require different numbers of method arguments compared to the rest, as demonstra example:
def now = new Date() def lastWeek = now - 7 def book = Book.findByReleaseDateBetween(lastWeek, now) books = Book.findAllByReleaseDateIsNull() books = Book.findAllByReleaseDateIsNotNull()

Boolean logic (AND/OR)


Method expressions can also use a boolean operator to combine two or more criteria:
def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan( "%Java%", new Date() - 30)

In this case we're using And in the middle of the query to make sure both conditions are satisfied, but you could eq
def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan( "%Java%", new Date() - 30)

You can combine as many criteria as you like, but they must all be combined with And or all Or. If you need to or if the number of criteria creates a very long method name, just convert the query to a Criteria or HQL query.

Querying Associations
Associations can also be used within queries:

142

def author = Author.findByName("Stephen King") def books = author ? Book.findAllByAuthor(author) : []

In this case if the Author instance is not null we use it in a query to obtain all the Book instances for the given A

Pagination and Sorting

The same pagination and sorting parameters available on the list method can also be used with dynamic finders b the final parameter:
def books = Book.findAllByTitleLike("Harry Pot%", [max: 3, offset: 2, sort: "title", order: "desc"])

6.4.2 Where Queries

The where method, introduced in Grails 2.0, builds on the support for Detached Criteria by providing an enh checked query DSL for common queries. The where method is more flexible than dynamic finders, less verb provides a powerful mechanism to compose queries.

Basic Querying

The where method accepts a closure that looks very similar to Groovy's regular collection methods. The clos logical criteria in regular Groovy syntax, for example:
def query = Person.where { firstName == "Bart" } Person bart = query.find()

The returned object is a DetachedCriteria instance, which means it is not associated with any particular da session. This means you can use the where method to define common queries at the class level:
class Person { static simpsons = where { lastName == "Simpson" } } Person.simpsons.each { println it.firstname }

Query execution is lazy and only happens upon usage of the DetachedCriteria instance. If you want to execute immediately there are variations of the findAll and find methods to accomplish this:

143

def results = Person.findAll { lastName == "Simpson" } def results = Person.findAll(sort:"firstName") { lastName == "Simpson" } Person p = Person.find { firstName == "Bart" }

Each Groovy operator maps onto a regular criteria method. The following table provides a map of Groovy operato Operator Criteria Method Description == != > < >= <= in ==~ =~ eq ne gt lt ge le inList like ilike Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to Contained within the given list Like a given string Case insensitive like

It is possible use regular Groovy comparison operators and logic to formulate complex queries:
def query = Person.where { (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9) } def results = query.list(sort:"firstName")

The Groovy regex matching operators map onto like and ilike queries unless the expression on the right hand object, in which case they map onto an rlike query:
def query = Person.where { firstName ==~ ~/B.+/ }

Note that rlike queries are only supported if the underlying database supports regular expressions

A between criteria query can be done by combining the in keyword with a range:
def query = Person.where { age in 18..65 }

144

Finally, you can do isNull and isNotNull style queries by using null with regular comparison operators:
def query = Person.where { middleName == null }

Query Composition

Since the return value of the where method is a DetachedCriteria instance you can compose new queries from the
def query = Person.where { lastName == "Simpson" } def bartQuery = query.where { firstName == "Bart" } Person p = bartQuery.find()

Note that you cannot pass a closure defined as a variable into the where method unless it has been DetachedCriteria instance. In other words the following will produce an error:
def callable = { lastName == "Simpson" } def query = Person.where(callable)

The above must be written as follows:


import grails.gorm.DetachedCriteria def callable = { lastName == "Simpson" } as DetachedCriteria<Person> def query = Person.where(callable)

As you can see the closure definition is cast (using the Groovy as keyword) to a DetachedCriteria instance tar class.

Conjunction, Disjunction and Negation

As mentioned previously you can combine regular Groovy logical operators (|| and &&) to form conjunctions and
def query = Person.where { (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9) }

You can also negate a logical comparison using !: 145

def query = Person.where { firstName == "Fred" && !(lastName == 'Simpson') }

Property Comparison Queries

If you use a property name on both the left hand and right side of a comparison expression then the appropriate criteria is automatically used:
def query = Person.where { firstName == lastName }

The following table described how each comparison operator maps onto each criteria property comparison method Operator Criteria Method Description == != > < >= <= eqProperty neProperty gtProperty ltProperty geProperty leProperty Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to

Querying Associations

Associations can be queried by using the dot operator to specify the property name of the association to be queried
def query = Pet.where { owner.firstName == "Joe" || owner.firstName == "Fred" }

You can group multiple criterion inside a closure method call where the name of the method matches the associati
def query = Person.where { pets { name == "Jack" || name == "Joe" } }

This technique can be combined with other top-level criteria:

146

def query = Person.where { pets { name == "Jack" } || firstName == "Ed" }

For collection associations it is possible to apply queries to the size of the collection:
def query = Person.where { pets.size() == 2 }

The following table shows which operator maps onto which criteria method for each size() comparison: Operator Criteria Method Description == != > < >= <= sizeEq sizeNe sizeGt sizeLt sizeGe sizeLe The collection size is equal to The collection size is not equal to The collection size is greater than The collection size is less than The collection size is greater than or equal to The collection size is less than or equal to

Subqueries

It is possible to execute subqueries within where queries. For example to find all the people older than the avera query can be used:
final query = Person.where { age > avg(age) }

The following table lists the possible subqueries: Method Description avg sum max min count The average of all values The sum of all values The maximum value The minimum value The count of all values

property Retrieves a property of the resulting entities You can apply additional criteria to any subquery by using the of method and passing in a closure containing the 147

def query = Person.where { age > avg(age).of { lastName == "Simpson" } && firstName == "Homer" }

Since the property subquery returns multiple results, the criterion used compares all results. For example the find all people younger than people with the surname "Simpson":
Person.where { age < property(age).of { lastName == "Simpson" } }

Other Functions

There are several functions available to you within the context of a query. These are summarized in the table below Method Description second The second of a date property minute The minute of a date property hour day month year lower upper length trim The hour of a date property The day of the month of a date property The month of a date property The year of a date property Converts a string property to upper case Converts a string property to lower case The length of a string property Trims a string property

Currently functions can only be applied to properties or associations of domain classes. You cann example, use a function on a result of a subquery. For example the following query can be used to find all pet's born in 2011:
def query = Pet.where { year(birthDate) == 2011 }

You can also apply functions to associations:

148

def query = Person.where { year(pets.birthDate) == 2009 }

Batch Updates and Deletes

Since each where method call returns a DetachedCriteria instance, you can use where queries to execute batc batch updates and deletes. For example, the following query will update all people with the surname "Simpson" "Bloggs":
def query = Person.where { lastName == 'Simpson' } int total = query.updateAll(lastName:"Bloggs")

Note that one limitation with regards to batch operations is that join queries (queries that query associ are not allowed. To batch delete records you can use the deleteAll method:
def query = Person.where { lastName == 'Simpson' } int total = query.deleteAll()

6.4.3 Criteria

Criteria is an advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a m than building up query strings using a StringBuffer.

Criteria can be used either with the createCriteria or withCriteria methods. The builder uses Hibernate's Criteria A builder map the static methods found in the Restrictions class of the Hibernate Criteria API. For example:
def c = Account.createCriteria() def results = c { between("balance", 500, 1000) eq("branch", "London") or { like("holderFirstName", "Fred%") like("holderFirstName", "Barney%") } maxResults(10) order("holderLastName", "desc") }

This criteria will select up to 10 Account objects in a List matching the following criteria:

149

balance is between 500 and 1000 branch is 'London' holderFirstName starts with 'Fred' or 'Barney' The results will be sorted in descending order by holderLastName. If no records are found with the above criteria, an empty List is returned.

Conjunctions and Disjunctions


As demonstrated in the previous example you can group criteria in a logical OR using an or { } block:
or { between("balance", 500, 1000) eq("branch", "London") }

This also works with logical AND:


and { between("balance", 500, 1000) eq("branch", "London") }

And you can also negate using logical NOT:


not { between("balance", 500, 1000) eq("branch", "London") }

All top level conditions are implied to be AND'd together.

Querying Associations

Associations can be queried by having a node that matches the property name. For example say the Accou Transaction objects:
class Account { static hasMany = [transactions: Transaction] }

We can query this association by using the property name transaction as a builder node:

150

def c = Account.createCriteria() def now = new Date() def results = c.list { transactions { between('date', now - 10, now) } }

The above code will find all the Account instances that have performed transactions within the last 10 da such association queries within logical blocks:
def c = Account.createCriteria() def now = new Date() def results = c.list { or { between('created', now - 10, now) transactions { between('date', now - 10, now) } } }

Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created

Querying with Projections

Projections may be used to customise the results. Define a "projections" node within the criteria builder tree to u are equivalent methods within the projections node to the methods found in the Hibernate Projections class:
def c = Account.createCriteria() def numberOfBranches = c.get { projections { countDistinct('branch') } }

When multiple fields are specified in the projection, a List of values will be returned. A single value will be return

Using SQL Restrictions


You can access Hibernate's SQL Restrictions capabilities.
def c = Person.createCriteria() def peopleWithShortFirstNames = c.list { sqlRestriction "char_length(first_name) <= 4" }

SQL Restrictions may be parameterized to deal with SQL injection vulnerabilities related to dynamic restrictions.

151

def c = Person.createCriteria()

def peopleWithShortFirstNames = c.list { sqlRestriction "char_length(first_name) < ? AND char_length(first_name) > ?", [maxV }

Note that the parameter there is SQL. The first_name attribute referenced in the example refers persistence model, not the object model like in HQL queries. The Person property named firstN mapped to the first_name column in the database and you must refer to that in the sqlRestric string. Also note that the SQL used here is not necessarily portable across databases.

Using Scrollable Results


You can use Hibernate's ScrollableResults feature by calling the scroll method:
def results = crit.scroll { maxResults(10) } def f = results.first() def l = results.last() def n = results.next() def p = results.previous() def future = results.scroll(10) def accountNumber = results.getLong('number')

To quote the documentation of Hibernate ScrollableResults:

A result iterator that allows moving around within the results by arbitrary increments. The Query / Sc pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods o are similar to the similarly named methods on ResultSet. Contrary to JDBC, columns of results are numbered from zero.

Setting properties in the Criteria instance

If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Crite allows full access to all the properties in this class. This example calls setMaxResults and setFirstRe instance:
import org.hibernate.FetchMode as FM def results = c.list { maxResults(10) firstResult(50) fetchMode("aRelationship", FM.JOIN) }

152

Querying with Eager Fetching

In the section on Eager and Lazy Fetching we discussed how to declaratively specify fetching to avoid the N+ However, this can also be achieved using a criteria query:
def criteria = Task.createCriteria() def tasks = criteria.list{ eq "assignee.id", task.assignee.id join 'assignee' join 'project' order 'priority', 'asc' }

Notice the usage of the join method: it tells the criteria API to use a JOIN to fetch the named associations with It's probably best not to use this for one-to-many associations though, because you will most likely end up w Instead, use the 'select' fetch mode:
import org.hibernate.FetchMode as FM def results = Airport.withCriteria { eq "region", "EMEA" fetchMode "flights", FM.SELECT }

Although this approach triggers a second query to get the flights association, you will get reliable resu maxResults option.

fetchMode and join are general settings of the query and can only be specified at the top-level, i cannot use them inside projections or association constraints. An important point to bear in mind is that if you include associations in the query constraints, those associations eagerly loaded. For example, in this query:
def results = Airport.withCriteria { eq "region", "EMEA" flights { like "number", "BA%" } }

the flights collection would be loaded eagerly via a join even though the fetch mode has not been explicitly se

Method Reference
If you invoke the builder with no method name such as:
c { }

The build defaults to listing all the results and hence the above is equivalent to: 153

c.list { }

Method list get scroll listDistinct count

Description This is the default method. It returns all matching rows.

Returns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only q method is not to be confused with a limit to just the first row. Returns a scrollable result set.

If subqueries or associations are used, one may end up with the same row multiple times in the r listing only distinct entities and is equivalent to DISTINCT_ROOT_ENTITY of the CriteriaSpecific Returns the number of matching rows.

6.4.4 Detached Criteria

Detached Criteria are criteria queries that are not associated with any given database session/connection. Suppo Detached Criteria queries have many uses including allowing you to create common reusable criteria queries, ex execute batch updates/deletes.

Building Detached Criteria Queries

The primary point of entry for using the Detached Criteria is the grails.gorm.DetachedCriteria c domain class as the only argument to its constructor:
import grails.gorm.* def criteria = new DetachedCriteria(Person)

Once you have obtained a reference to a detached criteria instance you can execute where queries or criteria qu appropriate query. To build a normal criteria query you can use the build method:
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' }

Note that methods on the DetachedCriteria instance do not mutate the original object but instead return a words, you have to use the return value of the build method to obtain the mutated criteria object:
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def bartQuery = criteria.build { eq 'firstName', 'Bart' }

154

Executing Detached Criteria Queries

Unlike regular criteria, Detached Criteria are lazy, in that no query is executed at the point of definition. Once query has been constructed then there are a number of useful query methods which are summarized in the table be Method list get count exists deleteAll Description List all matching entities Return a single matching result Count all matching records Return true if any matching records exist Delete all matching records

updateAll(Map) Update all matching records with the given properties As an example the following code will list the first 4 matching records sorted by the firstName property:
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def results = criteria.list(max:4, sort:"firstName")

You can also supply additional criteria to the list method:


def results = criteria.list(max:4, sort:"firstName") { gt 'age', 30 }

To retrieve a single result you can use the get or find methods (which are synonyms):
Person p = criteria.find() // or criteria.get()

The DetachedCriteria class itself also implements the Iterable interface which means that it can be treat
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } criteria.each { println it.firstName }

In this case the query is only executed when the each method is called. The same applies to all other Groov methods. You can also execute dynamic finders on DetachedCriteria just like on domain classes. For example:

155

def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def bart = criteria.findByFirstName("Bart")

Using Detached Criteria for Subqueries

Within the context of a regular criteria query you can use DetachedCriteria to execute subquery. For examp all people who are older than the average age the following query will accomplish that:
def results = Person.withCriteria { gt "age", new DetachedCriteria(Person).build { projections { avg "age" } } order "firstName" }

Notice that in this case the subquery class is the same as the original criteria query class (ie. Person) and he shortened to:
def results = Person.withCriteria { gt "age", { projections { avg "age" } } order "firstName" }

If the subquery class differs from the original criteria query then you will have to use the original syntax.

In the previous example the projection ensured that only a single result was returned (the average age). If y multiple results then there are different criteria methods that need to be used to compare the result. For example older than the ages 18 to 65 a gtAll query can be used:
def results = Person.withCriteria { gtAll "age", { projections { property "age" } between 'age', 18, 65 } order "firstName" }

The following table summarizes criteria methods for operating on subqueries that return multiple results:

156

Method Description gtAll geAll ltAll leAll eqAll neAll greater than all subquery results greater than or equal to all subquery results less than all subquery results less than or equal to all subquery results equal to all subquery results not equal to all subquery results

Batch Operations with Detached Criteria


The DetachedCriteria class can be used to execute batch operations such as batch updates and delet following query will update all people with the surname "Simpson" to have the surname "Bloggs":
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } int total = criteria.updateAll(lastName:"Bloggs")

Note that one limitation with regards to batch operations is that join queries (queries that query associ are not allowed within the DetachedCriteria instance.

To batch delete records you can use the deleteAll method:


def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } int total = criteria.deleteAll()

6.4.5 Hibernate Query Language (HQL)

GORM classes also support Hibernate's query language HQL, a very complete reference for which can be fo documentation of the Hibernate documentation.

GORM provides a number of methods that work with HQL including find, findAll and executeQuery. An exam seen below:
def results = Book.findAll("from Book as b where b.title like 'Lord of the%'")

Positional and Named Parameters


In this case the value passed to the query is hard coded, however you can equally use positional parameters: 157

def results = Book.findAll("from Book as b where b.title like ?", ["The Shi%"])

def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = ?", [author])

Or even named parameters:


def results = Book.findAll("from Book as b " + "where b.title like :search or b.author like :search", [search: "The Shi%"])

def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = :author", [author: author])

Multiline Queries
Use the line continuation character to separate the query across multiple lines:
def results = Book.findAll("\ from Book as b, \ Author as a \ where b.author = a and a.surname = ?", ['Smith'])

Triple-quoted Groovy multiline Strings will NOT work with HQL queries.

Pagination and Sorting

You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination op end of the method call and include an "ORDER BY" clause in the HQL:
def results = Book.findAll("from Book as b where " + "b.title like 'Lord of the%' " + "order by b.title asc", [max: 10, offset: 20])

158

6.5 Advanced GORM Features


The following sections cover more advanced usages of GORM including caching, custom mapping and events.

6.5.1 Events and Auto Timestamping

GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, ins following is a list of supported events: beforeInsert - Executed before an object is initially persisted to the database beforeUpdate - Executed before an object is updated beforeDelete - Executed before an object is deleted beforeValidate - Executed before an object is validated afterInsert - Executed after an object is persisted to the database afterUpdate - Executed after an object has been updated afterDelete - Executed after an object has been deleted onLoad - Executed when an object is loaded from the database To add an event simply register the relevant closure with your domain class.

Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events ar during flushing this will cause a StackOverflowError.

Event types
The beforeInsert event
Fired before an object is saved to the database
class Person { Date dateCreated def beforeInsert() { dateCreated = new Date() } }

The beforeUpdate event


Fired before an existing object is updated

159

class Person { Date dateCreated Date lastUpdated def beforeInsert() { dateCreated = new Date() } def beforeUpdate() { lastUpdated = new Date() } }

The beforeDelete event


Fired before an object is deleted.
class Person { String name Date dateCreated Date lastUpdated def beforeDelete() { ActivityTrace.withNewSession { new ActivityTrace(eventName:"Person Deleted",data:name).save() } } }

Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushi methods like save() and delete() won't result in objects being saved unless you run your operations with a n

Fortunately the withNewSession method lets you share the same transactional JDBC connection even th different underlying Session.

The beforeValidate event


Fired before an object is validated.
class Person { String name static constraints = { name size: 5..45 } def beforeValidate() { name = name?.trim() } }

The beforeValidate method is run before any validators are run.

160

Validation may run more often than you think. It is triggered by the validate() and save() m as you'd expect, but it is also typically triggered just before the view is rendered as well. So when w beforeValidate() implementations, make sure that they can handle being called multiple time the same property values.

GORM supports an overloaded version of beforeValidate which accepts a List parameter which may inc properties which are about to be validated. This version of beforeValidate will be called when the valida invoked and passed a List of property names as an argument.
class Person { String name String town Integer age static constraints = { name size: 5..45 age range: 4..99 } def beforeValidate(List propertiesBeingValidated) { // do pre validation work based on propertiesBeingValidated } } def p = new Person(name: 'Jacob Brown', age: 10) p.validate(['age', 'name'])

Note that when validate is triggered indirectly because of a call to the save method th validate method is being invoked with no arguments, not a List that includes all of the p names.

Either or both versions of beforeValidate may be defined in a domain class. GORM will prefer the List passed to validate but will fall back on the no-arg version if the List version does not exist. Likewise, G no-arg version if no arguments are passed to validate but will fall back on the List version if the no-arg vers that case, null is passed to beforeValidate.

The onLoad/beforeLoad event


Fired immediately before an object is loaded from the database:
class Person { String name Date dateCreated Date lastUpdated def onLoad() { log.debug "Loading ${id}" } }

beforeLoad() is effectively a synonym for onLoad(), so only declare one or the other.

161

The afterLoad event


Fired immediately after an object is loaded from the database:
class Person { String name Date dateCreated Date lastUpdated def afterLoad() { name = "I'm loaded" } }

Custom Event Listeners

As of Grails 2.0 there is a new API for plugins and applications to register and listen for persistence events. T Hibernate and also works for other persistence plugins such as the MongoDB plugin for GORM.

To use this API you need to subclass AbstractPersistenceEventListener org.grails.datastore.mapping.engine.event ) and implement a single method called onPersistenceEvent. T implementation can be seen below:
@Override protected void onPersistenceEvent(final AbstractPersistenceEvent event) { switch(event.eventType) { case PreInsert: println "PRE INSERT ${event.entityObject}" break case PostInsert: println "POST INSERT ${event.entityObject}" break case PreUpdate: println "PRE UPDATE ${event.entityObject}" break; case PostUpdate: println "POST UPDATE ${event.entityObject}" break; case PreDelete: println "PRE DELETE ${event.entityObject}" break; case PostDelete: println "POST DELETE ${event.entityObject}" break; case PreLoad: println "PRE LOAD ${event.entityObject}" break; case PostLoad: println "POST LOAD ${event.entityObject}" break; } }

The AbstractPersistenceEvent class has many subclasses (PreInsertEvent, PostInsertEven further information specific to the event. A cancel() method is also provided on the event which allows y update or delete operation.

Once you have created your event listener you need to register it with the ApplicationContext. T BootStrap.groovy: 162

def init = { applicationContext.addApplicationListener(new MyPersistenceListener()) }

Hibernate Events

It is generally encouraged to use the non-Hibernate specific API described above, but if you need access to mo events then you can define custom Hibernate-specific event listeners.

You can also register event handler classes in an application's grails-app/conf/spring/resources doWithSpring closure in a plugin descriptor by registering a Spring bean named hibernateEventListe one property, listenerMap which specifies the listeners to register for various Hibernate events.

The values of the Map are instances of classes that implement one or more Hibernate listener interfaces. You c implements all of the required interfaces, or one concrete class per interface, or any combination. The corresponding interfaces are listed here:

163

Name auto-flush merge create create-onflush delete dirty-check evict flush flush-entity load load-collection lock refresh replicate save-update save update pre-load pre-update pre-delete pre-insert

Interface AutoFlushEventListener MergeEventListener PersistEventListener PersistEventListener DeleteEventListener DirtyCheckEventListener EvictEventListener FlushEventListener FlushEntityEventListener LoadEventListener InitializeCollectionEventListener LockEventListener RefreshEventListener ReplicateEventListener SaveOrUpdateEventListener SaveOrUpdateEventListener SaveOrUpdateEventListener PreLoadEventListener PreUpdateEventListener PreDeleteEventListener PreInsertEventListener

pre-collection-recreate PreCollectionRecreateEventListener pre-collection-remove pre-collection-update post-load post-update post-delete post-insert post-commit-update post-commit-delete post-commit-insert PreCollectionRemoveEventListener PreCollectionUpdateEventListener PostLoadEventListener PostUpdateEventListener PostDeleteEventListener PostInsertEventListener PostUpdateEventListener PostDeleteEventListener PostInsertEventListener

post-collection-recreate PostCollectionRecreateEventListener post-collection-remove PostCollectionRemoveEventListener post-collection-update PostCollectionUpdateEventListener

164

For example, you could register a class AuditEventListener which implements PostInsertE PostUpdateEventListener, and PostDeleteEventListener using the following in an application:
beans = { auditListener(AuditEventListener) hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }

or use this in a plugin:


def doWithSpring = { auditListener(AuditEventListener) hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }

Automatic timestamping

The examples above demonstrated using events to update a lastUpdated and dateCreated property to kee objects. However, this is actually not necessary. By defining a lastUpdated and dateCreated pro automatically updated for you by GORM. If this is not the behaviour you want you can disable this feature with:
class Person { Date dateCreated Date lastUpdated static mapping = { autoTimestamp false } }

If you put nullable: false constraints on either dateCreated or lastUpdated, your d instances will fail validation - probably not what you want. Leave constraints off these properties unle have disabled automatic timestamping.

6.5.2 Custom ORM Mapping

Grails domain classes can be mapped onto many legacy schemas with an Object Relational Mapping DSL (doma The following sections takes you through what is possible with the ORM DSL.

165

None of this is necessary if you are happy to stick to the conventions defined by GORM for table column names and so on. You only needs this functionality if you need to tailor the way GORM map legacy schemas or configures caching Custom mappings are defined using a static mapping block defined within your domain class:
class Person { static mapping = { version false autoTimestamp false } }

You can also configure global mappings in Config.groovy (or an external config file) using this setting:
grails.gorm.default.mapping = { version false autoTimestamp false }

It has the same syntax as the standard mapping block but it applies to all your domain classes! You can then o within the mapping block of a domain class.

6.5.2.1 Table and Column Names


Table names
The database table name which the class maps to can be customized using the table method:
class Person { static mapping = { table 'people' } }

In this case the class would be mapped to a table called people instead of the default name of person.

Column names

It is also possible to customize the mapping for individual columns onto the database. For example to change the n

166

class Person { String firstName static mapping = { table 'people' firstName column: 'First_Name' } }

Here firstName is a dynamic method within the mapping Closure that has a single Map parameter. Since its a domain class persistent field, the parameter values (in this case just "column") are used to configure the mappi

Column type

GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes spec implement the Hibernate org.hibernate.usertype.UserType interface, which allows complete customization of ho As an example if you had a PostCodeType you could use it as follows:
class Address { String number String postCode static mapping = { postCode type: PostCodeType } }

Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails
class Address { String number String postCode static mapping = { postCode type: 'text' } }

This would make the postCode column map to the default large-text type for the database you're using (fo CLOB). See the Hibernate documentation regarding Basic Types for further information.

Many-to-One/One-to-One Mappings

In the case of associations it is also possible to configure the foreign keys used to map associations. In the case one-to-one association this is exactly the same as any regular column. For example consider the following:

167

class Person { String firstName Address address static mapping = { table 'people' firstName column: 'First_Name' address column: 'Person_Address_Id' } }

By default the address association would map to a foreign key column called address_id. By using the abo changed the name of the foreign key column to Person_Adress_Id.

One-to-Many Mapping

With a bidirectional one-to-many you can change the foreign key column used by changing the column name on association as per the example in the previous section on one-to-one associations. However, with unidirectional as key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship b Address the following code will change the foreign key in the address table:
class Person { String firstName static hasMany = [addresses: Address] static mapping = { table 'people' firstName column: 'First_Name' addresses column: 'Person_Address_Id' } }

If you don't want the column to be in the address table, but instead some intermediate join table you can u parameter:
class Person { String firstName static hasMany = [addresses: Address] static mapping = { table 'people' firstName column: 'First_Name' addresses joinTable: [name: 'Person_Addresses', key: 'Person_Id', column: 'Address_Id'] } }

Many-to-Many Mapping

Grails, by default maps a many-to-many association using a join table. For example consider this many-to-many a

168

class Group { static hasMany = [people: Person] }

class Person { static belongsTo = Group static hasMany = [groups: Group] }

In this case Grails will create a join table called group_person containing foreign keys called person_ referencing the person and group tables. To change the column names you can specify a column within th class.
class Group { static mapping = { people column: 'Group_Person_Id' } } class Person { static mapping = { groups column: 'Group_Group_Id' } }

You can also specify the name of the join table to use:
class Group { static mapping = { people column: 'Group_Person_Id', joinTable: 'PERSON_GROUP_ASSOCIATIONS' } } class Person { static mapping = { groups column: 'Group_Group_Id', joinTable: 'PERSON_GROUP_ASSOCIATIONS' } }

6.5.2.2 Caching Strategy


Setting up caching

Hibernate features a second-level cache with a customizable cache provider. This needs to be c grails-app/conf/DataSource.groovy file as follows:

169

hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='org.hibernate.cache.EhCacheProvider' }

You can customize any of these settings, for example to use a distributed caching mechanism.

For further reading on caching and in particular Hibernate's second-level cache, refer to the Hib documentation on the subject.

Caching instances
Call the cache method in your mapping block to enable caching with the default settings:
class Person { static mapping = { table 'people' cache true } }

This will configure a 'read-write' cache that includes both lazy and non-lazy properties. You can customize this fur
class Person { static mapping = { table 'people' cache usage: 'read-only', include: 'non-lazy' } }

Caching associations

As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (ass For example:
class Person { String firstName static hasMany = [addresses: Address] static mapping = { table 'people' version false addresses column: 'Address', cache: true } }

170

class Address { String number String postCode }

This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:
cache: 'read-write' // or 'read-only' or 'transactional'

to further configure the cache usage.

Caching Queries

You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the cac
def person = Person.findByFirstName("Fred", [cache: true])

In order for the results of the query to be cached, you must enable caching in your mapping as discu the previous section. You can also cache criteria queries:
def people = Person.withCriteria { like('firstName', 'Fr%') cache true }

Cache usages
Below is a description of the different cache settings and their usages:

read-only - If your application needs to read but never modify instances of a persistent class, a read-only c read-write - If the application needs to update data, a read-write cache might be appropriate.

nonstrict-read-write - If the application only occasionally needs to update data (ie. if it is ve transactions would try to update the same item simultaneously) and strict transaction isolation nonstrict-read-write cache might be appropriate.

transactional - The transactional cache strategy provides support for fully transactional cac JBoss TreeCache. Such a cache may only be used in a JTA environment and yo hibernate.transaction.manager_lookup_class in the grails-app/conf/DataSour hibernate config.

171

6.5.2.3 Inheritance Strategies

By default GORM classes use table-per-hierarchy inheritance mapping. This has the disadvantage that co NOT-NULL constraint applied to them at the database level. If you would prefer to use a table-per-su strategy you can do so as follows:
class Payment { Integer amount static mapping = { tablePerHierarchy false } } class CreditCardPayment extends Payment { String cardNumber }

The mapping of the root Payment class specifies that it will not be using table-per-hierarchy mapping f

6.5.2.4 Custom Database Identity

You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies o mechanism for generating ids. This is by far the best approach, but there are still many schemas that have dif identity. To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the follows:
class Person { static mapping = { table 'people' version false id generator: 'hilo', params: [table: 'hi_value', column: 'next_value', max_lo: 100] } }

In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.

For more information on the different Hibernate generators refer to the Hibernate reference document

Although you don't typically specify the id field (Grails adds it for you) you can still configure its mapping like For example to customise the column for the id property you can do:

172

class Person { static mapping = { table 'people' version false id column: 'person_id' } }

6.5.2.5 Composite Primary Keys

GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is recommend, but is available to you if you need it:
import org.apache.commons.lang.builder.HashCodeBuilder class Person implements Serializable { String firstName String lastName boolean equals(other) { if (!(other instanceof Person)) { return false } other.firstName == firstName && other.lastName == lastName } int hashCode() { def builder = new HashCodeBuilder() builder.append firstName builder.append lastName builder.toHashCode() } static mapping = { id composite: ['firstName', 'lastName'] } }

The above will create a composite id of the firstName and lastName properties of the Person class. To retri you use a prototype of the object itself:
def p = Person.get(new Person(firstName: "Fred", lastName: "Flintstone")) println p.firstName

Domain classes mapped with composite primary keys must implement the Serializable interface and overr hashCode methods, using the properties in the composite key for the calculations. The example above uses a H for convenience but it's fine to implement it yourself.

Another important consideration when using composite primary keys is associations. If for example you association where the foreign keys are stored in the associated table then 2 columns will be present in the associate For example consider the following domain class:

173

class Address { Person person }

In this case the address table will have an additional two columns called person_first_name and pers you wish the change the mapping of these columns then you can do so using the following technique:
class Address { Person person static mapping = { person { column: "FirstName" column: "LastName" } } }

6.5.2.6 Database Indices

To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which which indexes:
class Person { String firstName String address static mapping = { table 'people' version false id column: 'person_id' firstName column: 'First_Name', index: 'Name_Idx' address column: 'Address', index: 'Name_Idx,Address_Index' } }

Note that you cannot have any spaces in the value of the index attribute; in this example in Address_Index' will cause an error.

6.5.2.7 Optimistic Locking and Versioning

As discussed in the section on Optimistic and Pessimistic Locking, by default GORM uses optimistic locking and a version property into every class which is in turn mapped to a version column at the database level.

If you're mapping to a legacy schema that doesn't have version columns (or there's some other reason why you feature) you can disable this with the version method:
class Person { static mapping = { table 'people' version false } }

174

If you disable optimistic locking you are essentially on your own with regards to concurrent updates a open to the risk of users losing data (due to data overriding) unless you use pessimistic locking

Version columns types

By default Grails maps the version property as a Long that gets incremented by one each time an instance is up also supports using a Timestamp, for example:
import java.sql.Timestamp class Person { Timestamp version static mapping = { table 'people' } }

There's a slight risk that two updates occurring at nearly the same time on a fast server can end up with the same this risk is very low. One benefit of using a Timestamp instead of a Long is that you combine the op last-updated semantics into a single column.

6.5.2.8 Eager and Lazy Fetching


Lazy Collections
As discussed in the section on Eager and Lazy fetching, GORM collections are lazily loaded by default but behaviour with the ORM DSL. There are several options available to you, but the most common ones are: lazy: false fetch: 'join' and they're used like this:
class Person { String firstName Pet pet static hasMany = [addresses: Address] static mapping = { addresses lazy: false pet fetch: 'join' } }

175

class Address { String street String postCode }

class Pet { String name }

The first option, lazy: false , ensures that when a Person instance is loaded, its addresses collection time with a second SELECT. The second option is basically the same, except the collection is loaded with a JOI SELECT. Typically you want to reduce the number of queries, so fetch: 'join' is the more appropriate hand, it could feasibly be the more expensive approach if your domain model and data result in more and larg otherwise be necessary. For more advanced users, the other settings available are: 1. batchSize: N 2. lazy: false, batchSize: N

where N is an integer. These let you fetch results in batches, with one query per batch. As a simple example, cons Person:
class Person { String firstName Pet pet static mapping = { pet batchSize: 5 } }

If a query returns multiple Person instances, then when we access the first pet property, Hibernate will fetch t next ones. You can get the same behaviour with eager loading by combining batchSize with the lazy: fa find out more about these options in the Hibernate user guide and this primer on fetching strategies. Note that currently support the "subselect" fetching strategy.

Lazy Single-Ended Associations

In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can you load many entities because each non-lazy association will result in an extra SELECT statement. If the associa non-lazy associations, the number of queries grows significantly! Use the same technique as for lazy collections to make a one-to-one or many-to-one association non-lazy/eager:
class Person { String firstName }

176

class Address { String street String postCode static belongsTo = [person: Person] static mapping = { person lazy: false } }

Here we configure GORM to load the associated Person instance (through the person property) whenever an A

Lazy Single-Ended Associations and Proxies

Hibernate uses runtime-generated proxies to facilitate single-ended lazy associations; Hibernate dynamically subc to create the proxy.

Consider the previous example but with a lazily-loaded person association: Hibernate will set the person prop a subclass of Person. When you call any of the getters (except for the id property) or setters on that proxy, H entity from the database. Unfortunately this technique can produce surprising results. Consider the following example classes:
class Pet { String name }

class Dog extends Pet { }

class Person { String name Pet pet }

and assume that we have a single Person instance with a Dog as the pet. The following code will work as you w
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.get(person.petId) instanceof Dog

But this won't:


def person = Person.get(1) assert person.pet instanceof Dog assert Pet.list()[0] instanceof Dog

177

The second assertion fails, and to add to the confusion, this will work:
assert Pet.list()[0] instanceof Dog

What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate sessi load the Person instance, Hibernate creates a proxy for its pet relation and attaches it to the session. Once tha you retrieve that Pet instance with a query, a get(), or the pet relation within the same session , Hibernate giv

Fortunately for us, GORM automatically unwraps the proxy when you use get() and findBy*(), or when y relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn returned with a query that returns a list, such as list() and findAllBy*(). However, if Hibernate hasn't atta session, those queries will return the real instances - hence why the last example works. You can protect yourself to a degree from this problem by using the instanceOf method by GORM:
def person = Person.get(1) assert Pet.list()[0].instanceOf(Dog)

However, it won't help here if casting is involved. For example, the following code will throw a ClassCastExc first pet in the list is a proxy instance with a class that is neither Dog nor a sub-class of Dog:
def person = Person.get(1) Dog pet = Pet.list()[0]

Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you properties or methods on the instance without any problems.

These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you w error occurs and be able to work around it.

6.5.2.9 Custom Cascade Behaviour

As described in the section on cascading updates, the primary mechanism to control the way updates and dele association to another is the static belongsTo property.

However, the ORM DSL gives you complete access to Hibernate's transitive persistence capabilities using the cas Valid settings for the cascade attribute include:

178

merge - merges the state of a detached association save-update - cascades only saves and updates to an association delete - cascades only deletes to an association lock - useful if a pessimistic lock should be cascaded to its associations refresh - cascades refreshes to an association evict - cascades evictions (equivalent to discard() in GORM) to associations if set all - cascade all operations to associations all-delete-orphan - Applies only to one-to-many associations and indicates that when a child association then it should be automatically deleted. Children are also deleted when the parent is.

It is advisable to read the section in the Hibernate documentation on transitive persistence to obtain a understanding of the different cascade styles and recommendations for their usage

To specify the cascade attribute simply define one or more (comma-separated) of the aforementioned settings as it
class Person { String firstName static hasMany = [addresses: Address] static mapping = { addresses cascade: "all-delete-orphan" } }

class Address { String street String postCode }

6.5.2.10 Custom Hibernate Types

You saw in an earlier section that you can use composition (with the embedded property) to break a table into can achieve a similar effect with Hibernate's custom user types. These are not domain classes themselves, but classes. Each of these types also has a corresponding "meta-type" class that implements org.hibernate.usertype.Us

The Hibernate reference manual has some information on custom types, but here we will focus on how to map start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:

179

class Book { String title String author Rating rating static mapping = { rating type: RatingUserType } }

All we have done is declare the rating field the enum type and set the property's type in the custom mapping UserType implementation. That's all you have to do to start using your custom type. If you want, you can also settings such as "column" to change the column name and "index" to add it to an index.

Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In suc define in the mapping what columns to use, since Hibernate can only use the property name for a single column lets you map multiple columns to a property using this syntax:
class Book { String title Name author Rating rating static mapping = { name type: NameUserType, { column name: "first_name" column name: "last_name" } rating type: RatingUserType } }

The above example will create "first_name" and "last_name" columns for the author property. You'll be plea can also use some of the normal column/property mapping attributes in the column definitions. For example:
column name: "first_name", index: "my_idx", unique: true

The column definitions do not support the following attributes: type, cascade, lazy, cache, and joinTabl

One thing to bear in mind with custom types is that they define the SQL types for the corresponding database colu the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQ columns? In that case, override the column's SQL type using the sqlType attribute:

180

class Book { String title Name author Rating rating static mapping = { name type: NameUserType, { column name: "first_name", sqlType: "text" column name: "last_name", sqlType: "text" } rating type: RatingUserType, sqlType: "text" } }

Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varcha but overriding "text" with "yes_no" isn't going to work.

6.5.2.11 Derived Properties

A derived property is one that takes its value from a SQL expression, often but not necessarily based on the value persistent properties. Consider a Product class like this:
class Product { Float price Float taxRate Float tax }

If the tax property is derived based on the value of price and taxRate properties then is probably no nee property. The SQL used to derive the value of a derived property may be expressed in the ORM DSL like this:
class Product { Float price Float taxRate Float tax static mapping = { tax formula: 'PRICE * TAX_RATE' } }

Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the p the object model, which is why the example refers to PRICE and TAX_RATE instead of price and taxRate.

With that in place, when a Product is retrieved with something like Product.get(42), the SQL that is gen will look something like this:

181

select product0_.id as id1_0_, product0_.version as version1_0_, product0_.price as price1_0_, product0_.tax_rate as tax4_1_0_, product0_.PRICE * product0_.TAX_RATE as formula1_0_ from product product0_ where product0_.id=?

Since the tax property is derived at runtime and not stored in the database it might seem that the same effect adding a method like getTax() to the Product class that simply returns the product of the taxRate and pr an approach like that you would give up the ability query the database based on the value of the tax prope property allows exactly that. To retrieve all Product objects that have a tax value greater than 21.12 you could this:
Product.findAllByTaxGreaterThan(21.12)

Derived properties may be referenced in the Criteria API:


Product.withCriteria { gt 'tax', 21.12f }

The SQL that is generated to support either of those would look something like this:
select this_.id as id1_0_, this_.version as version1_0_, this_.price as price1_0_, this_.tax_rate as tax4_1_0_, this_.PRICE * this_.TAX_RATE as formula1_0_ from product this_ where this_.PRICE * this_.TAX_RATE>?

Because the value of a derived property is generated in the database and depends on the execution o code, derived properties may not have GORM constraints applied to them. If constraints are specifie derived property, they will be ignored.

6.5.2.12 Custom Naming Strategy

By default Grails uses Hibernate's ImprovedNamingStrategy to convert domain class Class and field nam column names by converting from camel-cased Strings to ones that use underscores as word separators. You can per-class basis in the mapping closure but if there's a consistent pattern you can specify a different NamingStr

Configure the class name to be used in grails-app/conf/DataSource.groovy in the hibernate secti 182

dataSource { pooled = true dbCreate = "create-drop" } hibernate { cache.use_second_level_cache = true naming_strategy = com.myco.myproj.CustomNamingStrategy }

You can also specify the name of the class and it will be loaded for you:
hibernate { naming_strategy = 'com.myco.myproj.CustomNamingStrategy' }

A third option is to provide an instance if there is some configuration required beyond calling the default construct
hibernate { def strategy = new com.myco.myproj.CustomNamingStrategy() // configure as needed naming_strategy = strategy }

You can use an existing class or write your own, for example one that prefixes table names and column names:
package com.myco.myproj import org.hibernate.cfg.ImprovedNamingStrategy import org.hibernate.util.StringHelper class CustomNamingStrategy extends ImprovedNamingStrategy { String classToTableName(String className) { "table_" + StringHelper.unqualify(className) } String propertyToColumnName(String propertyName) { "col_" + StringHelper.unqualify(propertyName) } }

6.5.3 Default Sort Order


You can sort objects using query arguments such as those found in the list method:
def airports = Airport.list(sort:'name')

However, you can also declare the default sort order for a collection in the mapping: 183

class Airport { static mapping = { sort "name" } }

The above means that all collections of Airport instances will by default be sorted by the airport name. If you the sort order , use this syntax:
class Airport { static mapping = { sort name: "desc" } }

Finally, you can configure sorting at the association level:


class Airport { static hasMany = [flights: Flight] static mapping = { flights sort: 'number', order: 'desc' } }

In this case, the flights collection will always be sorted in descending order of flight number.

These mappings will not work for default unidirectional one-to-many or many-to-many relatio because they involve a join table. See this issue for more details. Consider using a SortedSet or with sort parameters to fetch the data you need.

6.6 Programmatic Transactions

Grails is built on Spring and uses Spring's Transaction abstraction for dealing with programmatic transaction classes have been enhanced to make this simpler with the withTransaction method. This method has a single p which has a single parameter which is a Spring TransactionStatus instance. Here's an example of using withTransaction in a controller methods:

184

def transferFunds() { Account.withTransaction { status -> def source = Account.get(params.from) def dest = Account.get(params.to) def amount = params.amount.toInteger() if (source.active) { if (dest.active) { source.balance -= amount dest.amount += amount } else { status.setRollbackOnly() } } } }

In this example we rollback the transaction if the destination account is not active. Also, if an unchecked Excep not a checked Exception, even though Groovy doesn't require that you catch checked exceptions) is thrown d transaction will automatically be rolled back. You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback This can be achieved through the use of Spring's SavePointManager interface.

The withTransaction method deals with the begin/commit/rollback logic for you within the scope of the bloc

6.7 GORM and Constraints


Although constraints are covered in the Validation section, it is important to mention them here as some of the the way in which the database schema is generated.

Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the c class properties. Consider the following example. Suppose we have a domain model with the following properties:
String name String description

By default, in MySQL, Grails would define these columns as Column name Data Type varchar(255)

description varchar(255)

But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length. we would likely define the column as follows if we were creating the table with an SQL script. Column Data Type

description TEXT

185

Chances are we would also want to have some application-based validation to make sure we don't exceed that before we persist any records. In Grails, we achieve this validation with constraints. We would add the following to the domain class.
static constraints = { description maxSize: 1000 }

This constraint would provide both the application-based validation we want and it would also cause the schem shown above. Below is a description of the other constraints that influence schema generation.

Constraints Affecting String Properties


inList maxSize size

If either the maxSize or the size constraint is defined, Grails sets the maximum column length based on the con

In general, it's not advisable to use both constraints on the same domain class property. However, if both the max the size constraint are defined, then Grails sets the column length to the minimum of the maxSize constraint an the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will error.)

If the inList constraint is defined (and the maxSize and the size constraints are not defined), then Grai column length based on the length of the longest string in the list of valid values. For example, given a list inc "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy

Constraints Affecting Numeric Properties


min max range

If the max, min, or range constraint is defined, Grails attempts to set the column precision based on the c success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)

In general, it's not advisable to combine the pair min/max and range constraints together on the same do However, if both of these constraints is defined, then Grails uses the minimum precision value from the constra minimum of the two, because any length that exceeds that minimum precision will result in a validation error.) scale

If the scale constraint is defined, then Grails attempts to set the column scale based on the constraint value. Thi floating point numbers (i.e., java.lang.Float, java.Lang.Double, java.lang.BigDecimal java.lang.BigDecimal). The success of this attempted influence is largely dependent on how Hiberna underlying DBMS.

186

The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of precision. Keep in mind that specifying only one of min/max constraints will not affect schema generation (sinc negative value of property with max:100, for example), unless the specified constraint value requires more digits t column precision is (19 at the moment). For example:
someFloatValue max: 1000000, scale: 3

would yield:
someFloatValue DECIMAL(19, 3) // precision is default

but
someFloatValue max: 12345678901234567890, scale: 5

would yield:
someFloatValue DECIMAL(25, 5) // precision = digits in max + scale

and
someFloatValue max: 100, min: -100000

would yield:
someFloatValue DECIMAL(8, 2) // precision = digits in min + default scale

187

7 The Web Layer


7.1 Controllers

A controller handles requests and creates or prepares the response. A controller can generate the response dire view. To create a controller, simply create a class whose name ends with Controller in the grails-a directory (in a subdirectory if it's in a package).

The default URL Mapping configuration ensures that the first part of your controller name is mapped to a URI an within your controller maps to URIs within the controller name URI.

7.1.1 Understanding Controllers and Actions


Creating a controller

Controllers can be created with the create-controller or generate-controller command. For example try running the from the root of a Grails project:
grails create-controller book

The command will create a controller at the location grails-app/controllers/myapp/BookControll


package myapp class BookController { def index() { } }

where "myapp" will be the name of your application, the default package name if one isn't specified. BookController by default maps to the /book URI (relative to your application root).

The create-controller and generate-controller commands are just for convenience a can just as easily create controllers using your favorite text editor or IDE

Creating Actions
A controller can have multiple public action methods; each one maps to a URI:

188

class BookController { def list() { // do controller logic // create model return model } }

This example maps to the /book/list URI by default thanks to the property being named list.

Public Methods as Actions

In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferre methods. Leveraging methods instead of Closure properties has some advantages: Memory efficient Allow use of stateless controllers (singleton scope)

You can override actions from subclasses and call the overridden superclass method with super.actionN

Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with C fields.

If you prefer the Closure syntax or have older controller classes created in earlier versions of Grails and still w using methods, you can set the grails.compile.artefacts.closures.convert prop BuildConfig.groovy:
grails.compile.artefacts.closures.convert = true

and a compile-time AST transformation will convert your Closures to methods in the generated bytecode.

If a controller class extends some other class which is not defined under grails-app/controllers/ directory, methods inherited from that class are not conver controller actions. If the intent is to expose those inherited methods as controller actions the method be overridden in the subclass and the subclass method may invoke the method in the super class.

The Default Action


A controller has the concept of a default URI that maps to the root URI of the controller, for example /book for The action that is called when the default URI is requested is dictated by the following rules: If there is only one action, it's the default If you have an action named index, it's the default Alternatively you can set it explicitly with the defaultAction property:

189

static defaultAction = "list"

7.1.2 Controllers and Scopes


Available Scopes
Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:

servletContext - Also known as application scope, this scope lets you share state across the entire w servletContext is an instance of ServletContext

session - The session allows associating state with a given user and typically uses cookies to associate a sess session object is an instance of HttpSession

request - The request object allows the storage of objects for the current request only. The request obje HttpServletRequest params - Mutable map of incoming request query string or POST parameters flash - See below

Accessing Scopes

Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even by the Servlet API such as the HttpServletRequest:
class BookController { def find() { def findBy = params["findBy"] def appContext = request["foo"] def loggedUser = session["logged_user"] } }

You can also access values within scopes using the de-reference operator, making the syntax even more clear:
class BookController { def find() { def findBy = params.findBy def appContext = request.foo def loggedUser = session.logged_user } }

This is one of the ways that Grails unifies access to the different scopes.

Using Flash Scope

Grails supports the concept of flash scope as a temporary store to make attributes available for this request and t Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:

190

def delete() { def b = Book.get(params.id) if (!b) { flash.message = "User not found for id ${params.id}" redirect(action:list) } // remaining code }

When the list action is requested, the message value will be in scope and can be used to display an informatio removed from the flash scope after this second request. Note that the attribute name can be anything you want, and the values are often strings used to display messages, type.

Scoped Controllers

By default, a new controller instance is created for each request. In fact, because the controller is prototype sc since each request happens on its own thread. You can change this behaviour by placing a controller in a particular scope. The supported scopes are:

prototype (default) - A new controller will be created for each request (recommended for actions as Closu session - One controller is created for the scope of a user session singleton - Only one instance of the controller ever exists (recommended for actions as methods)

To enable one of the scopes, add a static scope property to your class with one of the valid scope values listed ab
static scope = "singleton"

You can define the default strategy under in Config.groovy with the grails.controllers.defa example:
grails.controllers.defaultScope = "singleton"

Use scoped controllers wisely. For instance, we don't recommend having any properties singleton-scoped controller since they will be shared for all requests. Setting a default scope othe prototype may also lead to unexpected behaviors if you have controllers provided by installed p that expect that the scope is prototype.

7.1.3 Models and Views


Returning the Model

A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names ac There are a couple of ways to return a model. First, you can explicitly return a Map instance: 191

def show() { [book: Book.get(params.id)] }

The above does not reflect what you should use with the scaffolding views - see the scaffolding sect more details.

If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write cod
class BookController { List books List authors def list() { books = Book.list() authors = Author.list() } }

This is possible due to the fact that controllers are prototype scoped. In other words a new contr created for each request. Otherwise code such as the above would not be thread-safe, and all users share the same data. In the above example the books and authors properties will be available in the view. A more advanced approach is to return an instance of the Spring ModelAndView class:
import org.springframework.web.servlet.ModelAndView def index() { // get some books just for the index page, perhaps your favorites def favoriteBooks = ... // forward to the list view to show them return new ModelAndView("/book/list", [ bookList : favoriteBooks ]) }

One thing to bear in mind is that certain variable names can not be used in your model: attributes application

Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.

Selecting the View

192

In both of the previous two examples there was no code that specified which view to render. So how does Grail pick? The answer lies in the conventions. Grails will look for a view at the location grails-app/views/b this list action:
class BookController { def show() { [book: Book.get(params.id)] } }

To render a different view, use the render method:


def show() { def map = [book: Book.get(params.id)] render(view: "display", model: map) }

In this case Grails will attempt to render a view at the location grails-app/views/book/display.gs automatically qualifies the view location with the book directory of the grails-app/views directory. This access shared views you need instead you can use an absolute path instead of a relative one:
def show() { def map = [book: Book.get(params.id)] render(view: "/shared/display", model: map) }

In this case Grails will attempt to render a view at the location grails-app/views/shared/display.gsp

Grails also supports JSPs as views, so if a GSP isn't found in the expected location but a JSP is, it will be used inst

Rendering a Response

Sometimes it's easier (for example with Ajax applications) to render snippets of text or code to the respon controller. For this, the highly flexible render method can be used:
render "Hello World!"

The above code writes the text "Hello World!" to the response. Other examples include:
// write some markup render { for (b in books) { div(id: b.id, b.title) } }

193

// render a specific view render(view: 'show')

// render a template for each item in a collection render(template: 'book_template', collection: Book.list())

// render some text with encoding and content type render(text: "<xml>some xml</xml>", contentType: "text/xml", encoding: "UTF-8")

If you plan on using Groovy's MarkupBuilder to generate HTML for use with the render method be caref between HTML elements and Grails tags, for example:
import groovy.xml.MarkupBuilder def login() { def writer = new StringWriter() def builder = new MarkupBuilder(writer) builder.html { head { title 'Log in' } body { h1 'Hello' form { } } } def html = writer.toString() render html }

This will actually call the form tag (which will return some text that will be ignored by the MarkupBuilder). T <form> element, use the following:
def login() { // body { h1 'Hello' builder.form { } } // }

7.1.4 Redirects and Chaining


Redirects
Actions can be redirected using the redirect controller method:

194

class OverviewController { def login() {} def find() { if (!session.user) redirect(action: 'login') return } } }

Internally the redirect method uses the HttpServletResponse object's sendRedirect method. The redirect method expects one of: Another closure within the same controller class:

// Call the login action within the same class redirect(action: login)

The name of an action (and controller name if the redirect isn't to an action in the current controller):

// Also redirects to the index action in the home controller redirect(controller: 'home', action: 'index')

A URI for a resource relative the application context path:

// Redirect to an explicit URI redirect(uri: "/login.html")

Or a full URL:

// Redirect to a URL redirect(url: "http://grails.org")

Parameters can optionally be passed from one action to the next using the params argument of the method:
redirect(action: 'myaction', params: [myparam: "myvalue"])

These parameters are made available through the params dynamic property that accesses request parameters. If a p with the same name as a request parameter, the request parameter is overridden and the controller parameter is use

Since the params object is a Map, you can use it to pass the current request parameters from one action to the nex

195

redirect(action: "next", params: params)

Finally, you can also include a fragment in the target URI:


redirect(controller: "test", action: "show", fragment: "profile")

which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".

Chaining

Actions can also be chained. Chaining allows the model to be retained from one action to the next. For examp action in this action:
class ExampleChainController { def first() { chain(action: second, model: [one: 1]) } def second () { chain(action: third, model: [two: 2]) } def third() { [three: 3]) } }

results in the model:


[one: 1, two: 2, three: 3]

The model can be accessed in subsequent controller actions in the chain using the chainModel map. This dy exists in actions following the call to the chain method:
class ChainController { def nextInChain() { def model = chainModel.myModel } }

Like the redirect method you can also pass parameters to the chain method:
chain(action: "action1", model: [one: 1], params: [myparam: "param1"])

196

7.1.5 Controller Interceptors


Often it is useful to intercept processing based on either request, session or application state. This can be interceptors. There are currently two types of interceptors: before and after.

If your interceptor is likely to apply to more than one controller, you are almost certainly better off w Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic o controller

Before Interception

The beforeInterceptor intercepts processing before the action is executed. If it returns false then the in not be executed. The interceptor can be defined for all actions in a controller as follows:
def beforeInterceptor = { println "Tracing action ${actionUri}" }

The above is declared inside the body of the controller definition. It will be executed before all actions and do processing. A common use case is very simplistic authentication:
def beforeInterceptor = [action: this.&auth, except: 'login'] // defined with private scope, so it's not considered an action private auth() { if (!session.user) { redirect(action: 'login') return false } } def login() { // display login page }

The above code defines a method called auth. A private method is used so that it is not exposed as an action to th beforeInterceptor then defines an interceptor that is used on all actions except the login action and i method. The auth method is referenced using Groovy's method pointer syntax. Within the method it detects whe the session, and if not it redirects to the login action and returns false, causing the intercepted action to not be

After Interception
Use the afterInterceptor property to define an interceptor that is executed after an action:
def afterInterceptor = { model -> println "Tracing action ${actionUri}" }

The after interceptor takes the resulting model as an argument and can hence manipulate the model or response. 197

An after interceptor may also modify the Spring MVC ModelAndView object prior to rendering. In this case becomes:
def afterInterceptor = { model, modelAndView -> println "Current view is ${modelAndView.viewName}" if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview" println "View is now ${modelAndView.viewName}" }

This allows the view to be changed based on the model returned by the current action. Note that the modelAndV the action being intercepted called redirect or render.

Interception Conditions

Rails users will be familiar with the authentication example and how the 'except' condition was used when exec (interceptors are called 'filters' in Rails; this terminology conflicts with Servlet filter terminology in Java):
def beforeInterceptor = [action: this.&auth, except: 'login']

This executes the interceptor for all actions except the specified action. A list of actions can also be defined as foll
def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]

The other supported condition is 'only', this executes the interceptor for only the specified action(s):
def beforeInterceptor = [action: this.&auth, only: ['secure']]

7.1.6 Data Binding

Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire g binding should deal with all necessary type conversion since request parameters, which are typically delivered b are always strings whilst the properties of a Groovy or Java object may well not be. Grails uses Spring's underlying data binding capability to perform data binding.

Binding Request Data to the Model


There are two ways to bind request parameters onto the properties of a domain class. The first involves using a constructor:
def save() { def b = new Book(params) b.save() }

198

The data binding happens within the code new Book(params). By passing the params object to the domain cl automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request lik
/book/save?title=The%20Stand&author=Stephen%20King

Then the title and author request parameters would automatically be set on the domain class. You can use th to perform data binding onto an existing instance:
def save() { def b = Book.get(params.id) b.properties = params b.save() }

This has the same effect as using the implicit constructor.

These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, th bind all non-transient, typed instance properties of the target object, including ones that you may no bound. Just because the form in your UI doesn't submit all the properties, an attacker can still send data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks section titled "Data Binding and Security concerns" for more information.

Data binding and Single-ended Associations

If you have a one-to-one or many-to-one association you can use Grails' data binding capability to upda too. For example if you have an incoming request such as:
/book/save?author.id=20

Grails will automatically detect the .id suffix on the request parameter and look up the Author instance for the data binding such as:
def b = new Book(params)

An association property can be set to null by passing the literal String "null". For example:
/book/save?author.id=null

Data Binding and Many-ended Associations

If you have a one-to-many or many-to-many association there are different techniques for data binding dependi type. 199

If you have a Set based association (the default for a hasMany) then the simplest way to populate an associati identifiers. For example consider the usage of <g:select> below:
<g:select name="books" from="${Book.list()}" size="5" multiple="yes" optionKey="id" value="${author?.books}" />

This produces a select box that lets you select multiple values. In this case if you submit the form Grails will a identifiers from the select box to populate the books association.

However, if you have a scenario where you want to update the properties of the associated objects the this te Instead you use the subscript operator:
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" />

However, with Set based association it is critical that you render the mark-up in the same order that you plan to d is because a Set has no concept of order, so although we're referring to books0 and books1 it is not guarantee association will be correct on the server side unless you apply some explicit sorting yourself.

This is not a problem if you use List based associations, since a List has a defined order and an index you can true of Map based associations. Note also that if the association you are binding to has a size of two and you refer to an element that is outside the
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[2].title" value="Red Madder" />

Then Grails will automatically create a new instance for you at the defined position. If you "skipped" a few elemen
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[5].title" value="Red Madder" />

Then Grails will automatically create instances in between. For example in the above case Grails will create 4 a the association being bound had a size of 2.

You can bind existing instances of the associated type to a List using the same .id syntax as you would use association. For example:
<g:select name="books[0].id" from="${bookList}" value="${author?.books[0]?.id}" /> <g:select name="books[1].id" from="${bookList}" value="${author?.books[1]?.id}" /> <g:select name="books[2].id" from="${bookList}" value="${author?.books[2]?.id}" />

200

Would allow individual entries in the books List to be selected separately. Entries at particular indexes can be removed in the same way too. For example:
<g:select name="books[0].id" from="${Book.list()}" value="${author?.books[0]?.id}" noSelection="['null': '']"/>

Will render a select box that will remove the association at books0 if the empty option is chosen. Binding to a Map property works the same way except that the list index in the parameter name is replaced by the
<g:select name="images[cover].id" from="${Image.list()}" value="${book?.images[cover]?.id}" noSelection="['null': '']"/>

This would bind the selected image into the Map property images under a key of "cover".

Data binding with Multiple domain classes


It is possible to bind data to multiple domain objects from the params object. For example so you have an incoming request to:
/book/save?book.title=The%20Stand&author.name=Stephen%20King

You'll notice the difference with the above request is that each parameter has a prefix such as author. or boo isolate which parameters belong to which type. Grails' params object is like a multi-dimensional hash and yo isolate only a subset of the parameters to bind.
def b = new Book(params.book)

Notice how we use the prefix before the first dot of the book.title parameter to isolate only parameters bel We could do the same with an Author domain class:
def a = new Author(params.author)

Data Binding and Action Arguments

Controller action arguments are subject to request parameter data binding. There are 2 categories of controller a first category is command objects. Complex types are treated as command objects. See the Command Objects sec for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding java.lang.String. The default behavior is to map request parameters to action arguments by name: 201

class AccountingController { // accountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(String accountNumber, int accountType) { // } }

For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type carried out before the request parameter value can be bound to the action argument. The type conversion happen case like the example shown above, the params.accountType request parameter has to be converted to an in fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper booleans and zero for numbers) and a corresponding error will be added to the errors property of the defining c
/accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue

Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller's erro will be true, the controller's errors.errorCount will be equal to 1 and t errors.getFieldError('accountType') will contain the corresponding error.

If the argument name does not match the name of the request parameter then the @grails.web.RequestPa may be applied to an argument to express the name of the request parameter which should be bound to that argume
import grails.web.RequestParameter class AccountingController { // mainAccountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(@RequestParameter('accountNumber') String mainAccountNumber, int // } }

Data binding and type conversion errors

Sometimes when performing data binding it is not possible to convert a particular String into a particular target t type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class.
class Book { URL publisherURL }

Here we have a domain class Book that uses the java.net.URL class to represent URLs. Given an incoming re
/book/save?publisherURL=a-bad-url

202

it is not possible to bind the string a-bad-url to the publisherURL property as a type mismatch error occu these like this:
def b = new Book(params) if (b.hasErrors()) { println "The value ${b.errors.getFieldError('publisherURL').rejectedValue}" + " is not a valid URL!" }

Although we have not yet covered error codes (for more information see the section on Validation), for type c would want a message from the grails-app/i18n/messages.properties file to use for the error. Y error message handler such as:
typeMismatch.java.net.URL=The field {0} is not a valid URL

Or a more specific one:


typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL

Data Binding and Security concerns

When batch updating properties from request parameters you need to be careful not to allow clients to bind mali classes and be persisted in the database. You can limit what properties are bound to a given domain class using the
def p = Person.get(1) p.properties['firstName','lastName'] = params

In this case only the firstName and lastName properties will be bound.

Another way to do this is is to use Command Objects as the target of data binding instead of domain classes. Alte the flexible bindData method. The bindData method allows the same data binding capability, but to arbitrary objects:
def p = new Person() bindData(p, params)

The bindData method also lets you exclude certain parameters that you don't want updated:
def p = new Person() bindData(p, params, [exclude: 'dateOfBirth'])

203

Or include only certain properties:


def p = new Person() bindData(p, params, [include: ['firstName', 'lastName]])

Note that if an empty List is provided as a value for the include parameter then all fields will be to binding if they are not explicitly excluded.

7.1.7 XML and JSON Responses


Using the render method to output XML
Grails supports a few different ways to produce XML and JSON responses. The first is the render method. The render method can be passed a block of code to do mark-up building in XML:
def list() { def results = Book.list() render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }

The result of this code would be something like:


<books> <book title="The Stand" /> <book title="The Shining" /> </books>

Be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:
def list() { def books = Book.list() // naming conflict here

render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }

This is because there is local variable books which Groovy attempts to invoke as a method. 204

Using the render method to output JSON


The render method can also be used to output JSON:
def list() { def results = Book.list() render(contentType: "text/json") { books = array { for (b in results) { book title: b.title } } } }

In this case the result would be something along the lines of:
[ {title:"The Stand"}, {title:"The Shining"} ]

The same dangers with naming conflicts described above for XML also apply to JSON building.

Automatic XML Marshalling


Grails also supports automatic marshalling of domain classes to XML using special converters. To start off with, import the grails.converters package into your controller:
import grails.converters.*

Now you can use the following highly readable syntax to automatically convert domain classes to XML:
render Book.list() as XML

The resulting output would look something like the following::


<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>

205

An alternative to using the converters is to use the codecs feature of Grails. The codecs feature provides encodeAsJSON methods:
def xml = Book.list().encodeAsXML() render xml

For more information on XML marshalling see the section on REST

Automatic JSON Marshalling

Grails also supports automatic marshalling to JSON using the same mechanism. Simply substitute XML with JSON
render Book.list() as JSON

The resulting output would look something like the following:


[ {"id":1, "class":"Book", "author":"Stephen King", "title":"The Stand"}, {"id":2, "class":"Book", "author":"Stephen King", "releaseDate":new Date(1194127343161), "title":"The Shining"} ]

Again as an alternative you can use the encodeAsJSON to achieve the same effect.

7.1.8 More on JSONBuilder

The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom imple Grails.

JSONBuilder and Grails versions

JSONBuilder behaves different depending on the version of Grails you use. For version below 1 grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilder

For backwards compatibility the old JSONBuilder class is used with the render method for older app newer/better JSONBuilder class set the following in Config.groovy:
grails.json.legacy.builder = false

Rendering Simple Objects


206

To render a simple JSON object just set properties within the context of the Closure:
render(contentType: "text/json") { hello = "world" }

The above will produce the JSON:


{"hello":"world"}

Rendering JSON Arrays


To render a list of objects simple assign a list:
render(contentType: "text/json") { categories = ['a', 'b', 'c'] }

This will produce:


{"categories":["a","b","c"]}

You can also render lists of complex objects, for example:


render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }

This will produce:


{"categories":[ {"a":"A"} , {"b":"B"}] }

Use the special element method to return a list as the root:


render(contentType: "text/json") { element 1 element 2 element 3 }

The above code produces:

207

[1,2,3]

Rendering Complex Objects


Rendering complex objects can be done with Closures. For example:
render(contentType: "text/json") { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }

The above will produce the JSON:


{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}

Arrays of Complex Objects


As mentioned previously you can nest complex objects within arrays using Closures:
render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }

You can use the array method to build them up dynamically:


def results = Book.list() render(contentType: "text/json") { books = array { for (b in results) { book title: b.title } } }

Direct JSONBuilder API Access


If you don't have access to the render method, but still want to produce JSON you can use the API directly:

208

def builder = new JSONBuilder() def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } } // prints the JSON text println result.toString() def sw = new StringWriter() result.render sw

7.1.9 Uploading Files


Programmatic File Uploads

Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uplo multipart form like this:
Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>

The uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard

There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance d
def upload() { def f = request.getFile('myFile') if (f.empty) { flash.message = 'file cannot be empty' render(view: 'uploadForm') return } f.transferTo(new File('/some/local/dir/myfile.txt')) response.sendError(200, 'Done') }

This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an so on with the MultipartFile interface.

File Uploads through Data Binding


File uploads can also be performed using data binding. Consider this Image domain class:

209

class Image { byte[] myFile static constraints = { // Limit upload file size to 2MB myFile maxSize: 1024 * 1024 * 2 } }

If you create an image using the params object in the constructor as in the example below, Grails will automa contents as a byte to the myFile property:
def img = new Image(params)

It's important that you set the size or maxSize constraints, otherwise your database may be created with a small c handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for byte prop

It is also possible to set the contents of the file as a string by changing the type of the myFile property on the ima
class Image { String myFile }

7.1.10 Command Objects

Grails controllers support the concept of command objects. A command object is similar to a form bean in a fr They are useful for grouping a subset of request parameters into a single object using data binding.

Declaring Command Objects


Command object classes are defined just like any other class.
@grails.validation.Validateable class LoginCommand { String username String password static constraints = { username(blank: false, minSize: 6) password(blank: false, minSize: 6) } }

As this example shows, since the command object class is marked with Validateable you can define command objects just like in domain classes. Another way to make a comman validateable is to define it in the same source file as the controller whic class as a command object. If a command object class is not defined in th file as a controller which uses the class as a command object and the class with Validateable, the class will not be made validateable. It is not required that command object classes be vali

210

Using Command Objects

To use command objects, controller actions may optionally specify any number of command object parameters. must be supplied so that Grails knows what objects to create and initialize.

Before the controller action is executed Grails will automatically create an instance of the command object c properties by binding the request parameters. If the command object class is marked with @Validateable then the be validated. For example:
class LoginController { def login(LoginCommand cmd) { if (cmd.hasErrors()) { redirect(action: 'loginForm') return } // work with the command object data } }

Command Objects and Dependency Injection

Command objects can participate in dependency injection. This is useful if your command object has some cu which uses a Grails service:
@grails.validation.Validateable class LoginCommand { def loginService String username String password static constraints = { username validator: { val, obj -> obj.loginService.canLogin(obj.username, obj.password) } } }

In this example the command object interacts with the loginService bean which is injected by nam ApplicationContext.

7.1.11 Handling Duplicate Form Submissions

Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To ge token on the form tag:
<g:form useToken="true" ...>

Then in your controller code you can use the withForm method to handle valid and invalid requests:

211

withForm { // good request }.invalidToken { // bad request }

If you only provide the withForm method and not the chained invalidToken method then by default Grails token in a flash.invalidToken variable and redirect the request back to the original page. This can then be c
<g:if test="${flash.invalidToken}"> Don't click the button twice! </g:if>

The withForm tag makes use of the session and hence requires session affinity or clustered sessions in a cluster.

7.1.12 Simple Type Converters


Type Conversion Methods

If you prefer to avoid the overhead of Data Binding and simply want to convert incoming parameters (typically more appropriate type the params object has a number of convenience methods for each type:
def total = params.int('total')

The above example uses the int method, and there are also methods for boolean, long, char, short and methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the p

Each of the conversion methods allows a default value to be passed as an optional second argument. The default v if a corresponding entry cannot be found in the map or if an error occurs during the conversion. Example:
def total = params.int('total', 42)

These same type conversion methods are also available on the attrs parameter of GSP tags.

Handling Multi Parameters

A common use case is dealing with multiple request parameters of the same name. For example you could get a ?name=Bob&name=Judy.

In this case dealing with one parameter and dealing with many has different semantics since Groovy's iteration me iterate over each character. To avoid this problem the params object provides a list method that always returns a

212

for (name in params.list('name')) { println name }

7.1.13 Asynchronous Request Processing

Grails support asynchronous request processing as provided by the Servlet 3.0 specification. To enable the async set your servlet target version to 3.0 in BuildConfig.groovy:
grails.servlet.version = "3.0"

With that done ensure you do a clean re-compile as some async features are enabled at compile time.

With a Servlet target version of 3.0 you can only deploy on Servlet 3.0 containers such as Tomca above.

Asynchronous Rendering

You can render content (templates, binary data etc.) in an asynchronous manner by calling the startAsync me instance of the Servlet 3.0 AsyncContext. Once you have a reference to the AsyncContext you can use method to render content:
def index() { def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } }

Note that you must call the complete() method to terminate the connection.

Resuming an Async Request

You resume processing of an async request (for example to delegate to view rendering) by using the dispa AsyncContext class:
def index() { def ctx = startAsync() ctx.start { // do working // render view ctx.dispatch() } }

213

7.2 Groovy Server Pages

Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of tech and JSP, but to be far more flexible and intuitive.

GSPs live in the grails-app/views directory and are typically rendered automatically (by convention) or w such as:
render(view: "index")

A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.

Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered document, the practice is strongly discouraged. Mixing mark-up and code is a bad thing and mo pages contain no code and needn't do so.

A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to controller. For example consider the following controller action:
def show() { [book: Book.get(params.id)] }

This action will look up a Book instance and create a model that contains a key called book. This key can then the GSP view using the name book:
${book.title}

7.2.1 GSP Basics

In the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover so users of JSP and ASP should be familiar with. GSP supports the usage of <% %> scriptlet blocks to embed Groovy code (again this is discouraged):
<html> <body> <% out << "Hello GSP!" %> </body> </html>

You can also use the <%= %> syntax to output values:

214

<html> <body> <%="Hello GSP!" %> </body> </html>

GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the demonstrates:
<html> <body> <%-- This is my comment --%> <%="Hello GSP!" %> </body> </html>

7.2.1.1 Variables and Scopes


Within the <% %> brackets you can declare variables:
<% now = new Date() %>

and then access those variables later in the page:


<%=now%>

Within the scope of a GSP there are a number of pre-defined variables, including: application - The javax.servlet.ServletContext instance applicationContext The Spring ApplicationContext instance flash - The flash object grailsApplication - The GrailsApplication instance out - The response writer for writing to the output stream params - The params object for retrieving request parameters request - The HttpServletRequest instance response - The HttpServletResponse instance session - The HttpSession instance webRequest - The GrailsWebRequest instance

7.2.1.2 Logic and Iteration


215

Using the <% %> syntax you can embed loops and so on using this syntax:
<html> <body> <% [1,2,3,4].each { num -> %> <p><%="Hello ${num}!" %></p> <%}%> </body> </html>

As well as logical branching:


<html> <body> <% if (params.hello == 'true')%> <%="Hello!"%> <% else %> <%="Goodbye!"%> </body> </html>

7.2.1.3 Page Directives


GSP also supports a few JSP-style page directives.

The import directive lets you import classes into the page. However, it is rarely needed due to Groovy's default im
<%@ page import="java.awt.*" %>

GSP also supports the contentType directive:


<%@ page contentType="text/json" %>

The contentType directive allows using GSP to render other formats.

7.2.1.4 Expressions

In GSP the <%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP exp JSP EL expression or a Groovy GString and takes the form ${expr}:
<html> <body> Hello ${params.name} </body> </html>

216

However, unlike JSP EL you can have any Groovy expression within the ${..} block. Variables within the $ escaped by default, so any HTML in the variable's string is rendered directly to the page. To reduce the risk o (XSS) attacks, you can enable automatic HTML escaping with the grails.views.default.c grails-app/conf/Config.groovy:
grails.views.default.codec='html'

Other possible values are 'none' (for no default encoding) and 'base64'.

7.2.2 GSP Tags

Now that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, wh way to define GSP pages.

The section on Tag Libraries covers how to add your own custom tag libraries.

All built-in GSP tags start with the prefix g:. Unlike JSP, you don't specify any tag library imports. If a tag automatically assumed to be a GSP tag. An example GSP tag would look like:
<g:example />

GSP tags can also have a body such as:


<g:example> Hello world </g:example>

Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String val
<g:example attr="${new Date()}"> Hello world </g:example>

Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:
<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]"> Hello world </g:example>

Note that within the values of attributes you must use single quotes for Strings:

217

<g:example attr="${new Date()}" attr2="[one:'one', two:'two']"> Hello world </g:example>

With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.

7.2.2.1 Variables and Scopes


Variables can be defined within a GSP using the set tag:
<g:set var="now" value="${new Date()}" />

Here we assign a variable called now to the result of a GSP expression (which simply constructs a new java.ut You can also use the body of the <g:set> tag to define a variable:
<g:set var="myHTML"> Some re-usable code on: ${new Date()} </g:set>

Variables can also be placed in one of the following scopes: page - Scoped to the current page (default) request - Scoped to the current request flash - Placed within flash scope and hence available for the next request session - Scoped for the user session application - Application-wide scope. To specify the scope, use the scope attribute:
<g:set var="now" value="${new Date()}" scope="request" />

7.2.2.2 Logic and Iteration

GSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif tags for use with b
<g:if test="${session.role == 'admin'}"> <%-- show administrative functions --%> </g:if> <g:else> <%-- show basic functions --%> </g:else>

Use the each and while tags for iteration:

218

<g:each in="${[1,2,3]}" var="num"> <p>Number ${num}</p> </g:each> <g:set var="num" value="${1}" /> <g:while test="${num < 5 }"> <p>Number ${num++}</p> </g:while>

7.2.2.3 Search and Filtering

If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tas
Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>

The expr attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for class:
<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>

Or using a regular expression:


<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>

The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The collection of Book instances. Since each Book has a title, you can obtain a list of Book titles using the expres . Groovy will auto-magically iterate the collection, obtain each title, and return a new list!

7.2.2.4 Links and Resources

GSP also features tags to help you manage linking to controllers and actions. The link tag lets you specify contro pairing and it will automatically work out the link based on the URL Mappings, even if you change them! For exa

219

<g:link action="show" id="1">Book 1</g:link> <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book">Book Home</g:link> <g:link controller="book" action="list">Book List</g:link> <g:link url="[action: 'list', controller: 'book']">Book List</g:link> <g:link params="[sort: 'title', order: 'asc', author: currentBook.author]" action="list">Book List</g:link>

7.2.2.5 Forms and Fields


Form Basics

GSP supports many different tags for working with HTML forms and fields, the most basic of which is the controller/action aware version of the regular HTML form tag. The url attribute lets you specify which control to:
<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>

In this case we create a form called myForm that submits to the BookController's list action. Beyond HTML attributes apply.

Form Fields

In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, inclu textField - For input fields of type 'text' passwordField - For input fields of type 'password' checkBox - For input fields of type 'checkbox' radio - For input fields of type 'radio' hiddenField - For input fields of type 'hidden' select - For dealing with HTML select boxes Each of these allows GSP expressions for the value:
<g:textField name="myField" value="${myValue}" />

GSP also contains extended helper versions of the above tags such as radioGroup (for creating groups of radio currencySelect and timeZoneSelect (for selecting locales, currencies and time zones respectively).

Multiple Submit Buttons

220

The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the actio like a regular submit, but lets you specify an alternative action to submit to:
<g:actionSubmit value="Some update label" action="update" />

7.2.2.6 Tags as Method Calls

One major different between GSP tags and other tagging technologies is that GSP tags can be called as either regu calls from controllers, tag libraries or GSP views.

Tags as method calls from GSPs


Tags return their results as a String-like object (a StreamCharBuffer which has all of the same methods writing directly to the response when called as methods. For example:
Static Resource: ${createLinkTo(dir: "images", file: "logo.jpg")}

This is particularly useful for using a tag within an attribute:


<img src="${createLinkTo(dir: 'images', file: 'logo.jpg')}" />

In view technologies that don't support this feature you have to nest tags within tags, which becomes messy quic adverse effect of WYSWIG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed
<img src="<g:createLinkTo dir="images" file="logo.jpg" />" />

Tags as method calls from Controllers and Tag Libraries

You can also invoke tags from controllers and tag libraries. Tags within the default g: namespace can be invok and a StreamCharBuffer result is returned:
def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()

Prefix the namespace to avoid naming conflicts:


def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()

For tags that use a custom namespace, use that prefix for the method call. For example (from the FCK Editor plug

221

def editor = fckeditor.editor(name: "text", width: "100%", height: "400")

7.2.3 Views and Templates

Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, Layouts provide a highly re-usable mechanism for structured views.

Template Basics

Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For exam a template that renders Books located at grails-app/views/book/_bookTemplate.gsp:
<div class="book" id="${book?.id}"> <div>Title: ${book?.title}</div> <div>Author: ${book?.author?.name}</div> </div>

Use the render tag to render this template from one of the views in grails-app/views/book:
<g:render template="bookTemplate" model="[book: myBook]" />

Notice how we pass into a model to use using the model attribute of the render tag. If you have multiple Bo also render the template for each Book using the render tag with a collection attribute:
<g:render template="bookTemplate" var="book" collection="${bookList}" />

Shared Templates

In the previous example we had a template that was specific to the BookController a grails-app/views/book. However, you may want to share templates across your application.

In this case you can place them in the root views directory at grails-app/views or any subdirectory below that lo the template attribute use an absolute location starting with / instead of a relative location. For example if you h grails-app/views/shared/_mySharedTemplate.gsp, you would reference it as:
<g:render template="/shared/mySharedTemplate" />

You can also use this technique to reference templates in any directory from any view or controller:
<g:render template="/book/bookTemplate" model="[book: myBook]" />

222

The Template Namespace

Since templates are used so frequently there is template namespace, called tmpl, available that makes using temp for example the following usage pattern:
<g:render template="bookTemplate" model="[book:myBook]" />

This can be expressed with the tmpl namespace as follows:


<tmpl:bookTemplate book="${myBook}" />

Templates in Controllers and Tag Libraries

You can also render templates from controllers using the render controller method. This is useful for Ajax ap generate small HTML or data responses to partially update the current page instead of performing new request:
def bookData() { def b = Book.get(params.id) render(template:"bookTemplate", model:[book:b]) }

The render controller method writes directly to the response, which is the most common behaviour. To instead template as a String you can use the render tag:
def bookData() { def b = Book.get(params.id) String content = g.render(template:"bookTemplate", model:[book:b]) render content }

Notice the usage of the g namespace which tells Grails we want to use the tag as method call instead of the render

7.2.4 Layouts with Sitemesh


Creating Layouts

Grails leverages Sitemesh, a decorator engine, to support view layouts. Layouts are located in the grails-app directory. A typical layout can be seen below:

223

<html> <head> <title><g:layoutTitle default="An example decorator" /></title> <g:layoutHead /> </head> <body onload="${pageProperty(name:'body.onload')}"> <div class="menu"><!--my common menu goes here--></menu> <div class="body"> <g:layoutBody /> </div> </div> </body> </html>

The key elements are the layoutHead, layoutTitle and layoutBody tag invocations: layoutTitle - outputs the target page's title layoutHead - outputs the target page's head tag contents layoutBody - outputs the target page's body tag contents

The previous example also demonstrates the pageProperty tag which can be used to inspect and return aspects of t

Triggering Layouts
There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:
<html> <head> <title>An Example Page</title> <meta name="layout" content="main" /> </head> <body>This is my content!</body> </html>

In this case a layout called grails-app/views/layouts/main.gsp will be used to layout the page. I layout from the previous section the output would resemble this:
<html> <head> <title>An Example Page</title> </head> <body onload=""> <div class="menu"><!--my common menu goes here--></div> <div class="body"> This is my content! </div> </body> </html>

Specifying A Layout In A Controller

Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" propert example, if you have a controller such as: 224

class BookController { static layout = 'customer' def list() { } }

You can create a layout called grails-app/views/layouts/customer.gsp which will be applied t BookController delegates to. The value of the "layout" property may contain a directory structu grails-app/views/layouts/ directory. For example:
class BookController { static layout = 'custom/customer' def list() { } }

Views rendered from that controller would be decorated with the grails-app/views/layouts/custo template.

Layout by Convention
Another way to associate layouts is to use "layout by convention". For example, if you have this controller:
class BookController { def list() { } }

You can create a layout called grails-app/views/layouts/book.gsp, which will be applied to BookController delegates to. Alternatively, you can create a layout called grails-app/views/layouts/book/list.gsp which will list action within the BookController.

If you have both the above mentioned layouts in place the layout specific to the action will take precedence w executed.

If a layout may not be located using any of those conventions, the convention of last resort is to look for the appl which is grails-app/views/layouts/application.gsp. The name of the application default layou defining a property in grails-app/conf/Config.groovy as follows:
grails.sitemesh.default.layout = 'myLayoutName'

With that property in place, the application default layout will be grails-app/views/layouts/myLayout

Inline Layouts

Grails' also supports Sitemesh's concept of inline layouts with the applyLayout tag. This can be used to apply a URL or arbitrary section of content. This lets you even further modularize your view structure by "decorating" you 225

Some examples of usage can be seen below:


<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" /> <g:applyLayout name="myLayout" url="http://www.google.com" /> <g:applyLayout name="myLayout"> The content to apply a layout to </g:applyLayout>

Server-Side Includes

While the applyLayout tag is useful for applying layouts to external content, if you simply want to include ex current page you use the include tag:
<g:include controller="book" action="list" />

You can even combine the include tag and the applyLayout tag for added flexibility:
<g:applyLayout name="myLayout"> <g:include controller="book" action="list" /> </g:applyLayout>

Finally, you can also call the include tag from a controller or tag library as a method:
def content = include(controller:"book", action:"list")

The resulting content will be provided via the return value of the include tag.

7.2.5 Static Resources


Grails 2.0 integrates with the Resources plugin to provide sophisticated static resource management. This plugin in new Grails applications.

The basic way to include a link to a static resource in your application is to use the resource tag. This simple ap pointing to the file.

However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as we multiple Grails plugins) require something more powerful. The issues that the Resources framework tackles are:

226

Web application performance tuning is difficult Correct ordering of resources, and deferred inclusion of JavaScript Resources that depend on others that must be loaded first The need for a standard way to expose static resources in plugins and applications The need for an extensible processing chain to optimize resources Preventing multiple inclusion of the same resource

The plugin achieves this by introducing new artefacts and processing the resources using the server's local file syst

It adds artefacts for declaring resources, for declaring "mappers" that can process resources, and a servlet filte resources.

What you get is an incredibly advanced resource system that enables you to easily create highly optimized web the same in development and in production.

The Resources plugin documentation provides a more detailed overview of the concepts which will be benefic following guide.

7.2.5.1 Including resources using the resource tags


Pulling in resources with r:require

To use resources, your GSP page must indicate which resource modules it requires. For example with the j exposes a "jquery" resource module, to use jQuery in any page on your site you simply add:
<html> <head> <r:require module="jquery"/> <r:layoutResources/> </head> <body> <r:layoutResources/> </body> </html>

This will automatically include all resources needed for jQuery, including them at the correct locations in the plugin sets the disposition to be "head", so they load early in the page.

You can call r:require multiple times in a GSP page, and you use the "modules" attribute to provide a list of m
<html> <head> <r:require modules="jquery, main, blueprint, charting"/> <r:layoutResources/> </head> <body> <r:layoutResources/> </body> </html>

227

The above may result in many JavaScript and CSS files being included, in the correct order, with some JavaScri end of the body to improve the apparent page load time.

However you cannot use r:require in isolation - as per the examples you must have the <r:layoutResources/> tag to render.

Rendering the links to resources with r:layoutResources

When you have declared the resource modules that your GSP page requires, the framework needs to render the lin at the correct time.

To achieve this correctly, you must include the r:layoutResources tag twice in your page, or more commonly, in yo
<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>

This represents the simplest Sitemesh layout you can have that supports Resources. The Resources framework has the concept of a "disposition" for every resource. This is an indication of where in should be included.

The default disposition applied depends on the type of resource. All CSS must be rendered in <head> in HTM default for all CSS, and will be rendered by the first r:layoutResources. Page load times are improved when Java the page content, so the default for JavaScript files is "defer", which means it is rendered when the second invoked.

Note that both your GSP page and your Sitemesh layout (as well as any GSP template fragments) can call r: resources. The only limitation is that you must call r:require before the r:layoutResources that should render it.

Adding page-specific JavaScript code with r:script

Grails has the javascript tag which is adapted to defer to Resources plugin if installed, but it is recommended that directly when you need to include fragments of JavaScript code.

This lets you write some "inline" JavaScript which is actually not rendered inline, but either in the <head> or at based on the disposition. Given a Sitemesh layout like this:

228

<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>

...in your GSP you can inject some JavaScript code into the head or deferred regions of the page like this:
<html> <head> <title>Testing r:script magic!</title> </head> <body> <r:script disposition="head"> window.alert('This is at the end of <head>'); </r:script> <r:script disposition="defer"> window.alert('This is at the end of the body, and the page has loaded.'); </r:script> </body> </html>

The default disposition is "defer", so the disposition in the latter r:script is purely included for demonstration.

Note that such r:script code fragments always load after any modules that you have used, to ensure that any re loaded.

Linking to images with r:img


This tag is used to render <img> markup, using the Resources framework to process the resource on the fly (if e.g. make it eternally cacheable). This includes any extra attributes on the <img> tag if the resource has been previously declared in a module.

With this mechanism you can specify the width, height and any other attributes in the resource declaration in the m be pulled in as necessary. Example:
<html> <head> <title>Testing r:img</title> </head> <body> <r:img uri="/images/logo.png"/> </body> </html>

Note that Grails has a built-in g:img tag as a shortcut for rendering <img> tags that refer to a static resource. Resources-aware and will delegate to r:img if found. However it is recommended that you use r:img directly i plugin. 229

Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity. See r:resource documentation for full details.

7.2.5.2 Other resource tags


r:resource

This is equivalent to the Grails resource tag, returning a link to the processed static resource. Grails' own g:res to this implementation if found, but if your code requires the Resources plugin, you should use r:resource dire Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity. See r:resource documentation for full details.

r:external
This is a resource-aware version of Grails external tag which renders the HTML markup necessary to include an such as CSS, JS or a favicon. See r:resource documentation for full details.

7.2.5.3 Declaring resources

A DSL is provided for declaring resources and modules. This can go either in your Config.groo application-specific resources, or more commonly in a resources artefact in grails-app/conf.

Note that you do not need to declare all your static resources, especially images. However you must to establish d resources-specific attributes. Any resource that is not declared is called "ad-hoc" and will still be processed u resource type. Consider this example resource configuration file, grails-app/conf/MyAppResources.groovy:
modules = { core { dependsOn 'jquery, utils' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' resource url: '/js/utils.js' } forms { dependsOn 'core,utils' resource url: '/css/forms.css' resource url: '/js/forms.js' } }

230

This defines three resource modules; 'core', 'utils' and 'forms'. The resources in these modules will be automatical box according to the module name, resulting in fewer files. You can override this with bundle:'someOt resource, or call defaultBundle on the module (see resources plugin documentation). It declares dependencies between them using dependsOn, which controls the load order of the resources.

When you include an <r:require module="forms"/> in your GSP, it will pull in all the resources from 'c as 'jquery', all in the correct order.

You'll also notice the disposition:'head' on the core.js file. This tells Resources that while it can defe to the end of the body, this one must go into the <head>.

The CSS file for print styling adds custom attributes using the attrs map option, and these are passed through tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated li

There is no limit to the number of modules or xxxResources.groovy artefacts you can provide, and plugins can s modules to applications, which is exactly how the jQuery plugin works.

To define modules like this in your application's Config.groovy, you simply assign the DSL grails.resources.modules Config variable. For full details of the resource DSL please see the resources plugin documentation.

7.2.5.4 Overriding plugin resources


Because a resource module can define the bundle groupings and other attributes of resources, you may find that are not correct for your application.

For example, you may wish to bundle jQuery and some other libraries all together in one file. There is a lo trade-off here, but often it is the case that you'd like to override some of these settings.

To do this, the DSL supports an "overrides" clause, within which you can change the defaultBundle sett attributes of individual resources that have been declared with a unique id:

231

modules = { core { dependsOn 'jquery, utils' defaultBundle 'monolith' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' defaultBundle 'monolith' resource url: '/js/utils.js' } forms { dependsOn 'core,utils' defaultBundle 'monolith' resource url: '/css/forms.css' resource url: '/js/forms.js' } overrides { jquery { defaultBundle 'monolith' } } }

This will put all code into a single bundle named 'monolith'. Note that this can still result in multiple files, as required for head and defer dispositions, and JavaScript and CSS files are bundled separately.

Note that overriding individual resources requires the original declaration to have included a unique id for the reso For full details of the resource DSL please see the resources plugin documentation.

7.2.5.5 Optimizing your resources


The Resources framework uses "mappers" to mutate the resources into the final format served to the user.

The resource mappers are applied to each static resource once, in a specific order. You can create your own re several plugins provide some already for zipping, caching and minifying.

Out of the box, the Resources plugin provides bundling of resources into fewer files, which is achieved with a f perform CSS re-writing to handle when your CSS files are moved into a bundle.

Bundling multiple resources into fewer files

The 'bundle' mapper operates by default on any resource with a "bundle" defined - or inherited from a defaultB module. Modules have an implicit default bundle name the same as the name of the module. Files of the same kind will be aggregated into this bundle file. Bundles operate across module boundaries:

232

modules = { core { dependsOn 'jquery, utils' defaultBundle 'common' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js', bundle: 'ui' resource url: '/css/main.css', bundle: 'theme' resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' resource url: '/js/utils.js', bundle: 'common' } forms { dependsOn 'core,utils' resource url: '/css/forms.css', bundle: 'ui' resource url: '/js/forms.js', bundle: 'ui' } }

Here you see that resources are grouped into bundles; 'common', 'ui' and 'theme' - across module boundaries. Note that auto-bundling by module does not occur if there is only one resource in the module.

Making resources cache "eternally" in the client browser

Caching resources "eternally" in the client is only viable if the resource has a unique name that changes whenever and requires caching headers to be set on the response.

The cached-resources plugin provides a mapper that achieves this by hashing your files and renaming them base sets the caching headers on every response for those resources. To use, simply install the cached-resources plugin.

Note that the caching headers can only be set if your resources are being served by your application. If you have a the static content from your app (e.g. Apache HTTPD), configure it to send caching headers. Alternatively yo request and proxy the resources from your container.

Zipping resources
Returning gzipped resources is another way to reduce page load times and reduce bandwidth.

The zipped-resources plugin provides a mapper that automatically compresses your content, excluding by defaul formats such as gif, jpeg and png. Simply install the zipped-resources plugin and it works.

Minifying

There are a number of CSS and JavaScript minifiers available to obfuscate and reduce the size of your code. A none are publicly released but releases are imminent.

7.2.5.6 Debugging

233

When your resources are being moved around, renamed and otherwise mutated, it can be hard to debug client browsers, especially Safari, Chrome and Firefox have excellent tools that let you view all the resources requested the headers and other information about them. There are several debugging features built in to the Resources framework.

X-Grails-Resources-Original-Src Header

Every resource served in development mode will have the X-Grails-Resources-Original-Src: header added, in source file(s) that make up the response.

Adding the debug flag

If you add a query parameter _debugResources=y to your URL and request the page, Resources will bypass a you can see your original source files.

This also adds a unique timestamp to all your resource URLs, to defeat any caching that browsers may use. This m always see your very latest code when you reload the page.

Turning on debug all the time

You can turn on the aforementioned debug mechanism without requiring a query parameter, but turning it on in Co
grails.resources.debug = true

You can of course set this per-environment.

7.2.5.7 Preventing processing of resources

Sometimes you do not want a resource to be processed in a particular way, or even at all. Occasionally you may al resource mapping.

Preventing the application of a specific mapper to an individual resource


All resource declarations support a convention of noXXXX:true where XXXX is a mapper name. So for example to prevent the "hashandcache" mapper from being applied to a resource (which renames and breaking relative links written in JavaScript code), you would do this:
modules = { forms { resource url: '/css/forms.css', nohashandcache: true resource url: '/js/forms.js', nohashandcache: true } }

Excluding/including paths and file types from specific mappers

Mappers have includes/excludes Ant patterns to control whether they apply to a given resource. Mappers set sens based on their activity, for example the zipped-resources plugin's "zip" mapper is set to exclude images by default. 234

You can configure this in your Config.groovy using the mapper name e.g:
// We wouldn't link to .exe files using Resources but for the sake of example: grails.resources.zip.excludes = ['**/*.zip', '**/*.exe'] // Perhaps for some reason we want to prevent bundling on "less" CSS files: grails.resources.bundle.excludes = ['**/*.less']

There is also an "includes" inverse. Note that settings these replaces the default includes/excludes for that mapper

Controlling what is treated as an "ad-hoc" (legacy) resource

Ad-hoc resources are those undeclared, but linked to directly in your application without using the Grails or R (resource, img or external). These may occur with some legacy plugins or code with hardcoded paths in.

There is a Config.groovy setting grails.resources.adhoc.patterns which defines a list of Servlet API compliant which the Resources filter will use to detect such "ad-hoc resource" requests. By default this is set to:
grails.resources.adhoc.patterns = ['images/*', '*.js', '*.css']

7.2.5.8 Other Resources-aware plugins


At the time of writing, the following plugins include support for the Resources framework: jquery jquery-ui blueprint lesscss-resources zipped-resources cached-resources

7.2.6 Sitemesh Content Blocks

Although it is useful to decorate an entire page sometimes you may find the need to decorate independent section this you can use content blocks. To get started, partition the page to be decorated using the <content> tag:

235

<content tag="navbar"> draw the navbar here </content> <content tag="header"> draw the header here </content> <content tag="footer"> draw the footer here </content> <content tag="body"> draw the body here </content>

Then within the layout you can reference these components and apply individual layouts to each:
<html> <body> <div id="header"> <g:applyLayout name="headerLayout"> <g:pageProperty name="page.header" /> </g:applyLayout> </div> <div id="nav"> <g:applyLayout name="navLayout"> <g:pageProperty name="page.navbar" /> </g:applyLayout> </div> <div id="body"> <g:applyLayout name="bodyLayout"> <g:pageProperty name="page.body" /> </g:applyLayout> </div> <div id="footer"> <g:applyLayout name="footerLayout"> <g:pageProperty name="page.footer" /> </g:applyLayout> </div> </body> </html>

7.2.7 Making Changes to a Deployed Application

One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change that you redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it unnecessary work. For such simple requirements, Grails does have a solution: the grails.gsp.view.dir con How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep /var/www/grails/my-app directory. We add these two lines to grails-app/conf/Config.groovy
grails.gsp.enable.reload = true grails.gsp.view.dir = "/var/www/grails/my-app/"

The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, yo changes as you like but they won't be reflected in the running application until you restart. The second line tells the views and layouts from.

236

The trailing slash on the grails.gsp.view.dir value is important! Without it, Grails will lo views in the parent directory.

Setting "grails.gsp.view.dir" is optional. If it's not specified, you can update files directly to the application s directory. Depending on the application server, these files might get overwritten when the server is restarted. Mo support "exploded war deployment" which is recommended in this case.

With those settings in place, all you need to do is copy the views from your web application to the external direc system, this would look something like this:
mkdir -p /var/www/grails/my-app/grails-app/views cp -R grails-app/views/* /var/www/grails/my-app/grails-app/views

The key point here is that you must retain the view directory structure, including the grails-app/views bit the path /var/www/grails/my-app/grails-app/views/... .

One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So a eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended changes to the views. There are also some System properties to control GSP reloading: Name grails.gsp.enable.reload grails.gsp.reload.interval grails.gsp.reload.granularity Description

altervative system property for enabling the GSP reload mode without changing Con

interval between checking the lastmodified time of the gsp source file, unit is millise

the number of milliseconds leeway to give before deciding a file is out of date. thi because different roundings usually cause a 1000ms difference in lastmodified times

GSP reloading is supported for precompiled GSPs since Grails 1.3.5 .

7.2.8 GSP Debugging


Viewing the generated source code

Adding "?showSource=true" or "&showSource=true" to the url shows the generated Groovy source code fo rendering it. It won't show the source code of included templates. This only works in development mode

The saving of all generated source code can be activated by setting the property "grails.views.gsp.k Config.groovy) . It must point to a directory that exists and is writable.

During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gs ~/.grails/(grails_version)/projects/(project name)/gspcompile).

Debugging GSP code with a debugger


See Debugging GSP in STS

Viewing information about templates used to render a single url


237

GSP templates are reused in large web applications by using the g:render taglib. Several small templates ca single page. It might be hard to find out what GSP template actually renders the html seen in the result. The deb adds html comments to the output. The comments contain debug information about gsp templates used to render th

Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the res "debugTemplates" is restricted to development mode. It won't work in production. Here is an example of comments added by debugTemplates :
<!-- GSP #2 START template: /home/.../views/_carousel.gsp precompiled: false lastmodified: --> . . . <!-- GSP #2 END template: /home/.../views/_carousel.gsp rendering time: 115 ms -->

Each comment block has a unique id so that you can find the start & end of each template call.

7.3 Tag Libraries

Like Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library m elegant and completely reloadable at runtime. Quite simply, to create a tag library create a Groovy class that ends with the convention TagLib and grails-app/taglib directory:
class SimpleTagLib { }

Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:
class SimpleTagLib { def simple = { attrs, body -> } }

The attrs argument is a Map of the attributes of the tag, whilst the body argument is a Closure that returns th invoked:
class SimpleTagLib { def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }

As demonstrated above there is an implicit out variable that refers to the output Writer which you can use to response. Then you can reference the tag inside your GSP; no imports are necessary:

238

<g:emoticon happy="true">Hi John</g:emoticon>

To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you shou Javadoc comments to your tag closures with @attr descriptions. Since taglibs use Groovy code it difficult to reliably detect all usable attributes. For example:
class SimpleTagLib { /** * Renders the body with an emoticon. * * @attr happy whether to show a happy emoticon (' true') or * a sad emoticon ('false') */ def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }

and any mandatory attributes should include the REQUIRED keyword, e.g.
class SimpleTagLib { /** * Creates a new password field. * * @attr name REQUIRED the field name * @attr value the field value */ def passwordField = { attrs -> attrs.type = "password" attrs.tagName = "passwordField" fieldImpl(out, attrs) } }

7.3.1 Variables and Scopes


Within the scope of a tag library there are a number of pre-defined variables including:

239

actionName - The currently executing action name controllerName - The currently executing controller name flash - The flash object grailsApplication - The GrailsApplication instance out - The response writer for writing to the output stream pageScope - A reference to the pageScope object used for GSP rendering (i.e. the binding) params - The params object for retrieving request parameters pluginContextPath - The context path to the plugin that contains the tag library request - The HttpServletRequest instance response - The HttpServletResponse instance servletContext - The javax.servlet.ServletContext instance session - The HttpSession instance

7.3.2 Simple Tags


As demonstrated in the previous example it is easy to write simple tags that have no body and just output content. dateFormat style tag:
def dateFormat = { attrs, body -> out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date) }

The above uses Java's SimpleDateFormat class to format a date and then write it to the response. The tag can GSP as follows:
<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed
def formatBook = { attrs, body -> out << "<div id="${attrs.book.id}">" out << "Title : ${attrs.book.title}" out << "</div>" }

Although this approach may be tempting it is not very clean. A better approach would be to reuse the render tag:
def formatBook = { attrs, body -> out << render(template: "bookTemplate", model: [book: attrs.book]) }

240

And then have a separate GSP template that does the actual rendering.

7.3.3 Logical Tags

You can also create logical tags where the body of the tag is only output once a set of conditions have been me may be a set of security tags:
def isAdmin = { attrs, body -> def user = attrs.user if (user && checkUserPrivs(user)) { out << body() } }

The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set
<g:isAdmin user="${myUser}"> // some restricted content </g:isAdmin>

7.3.4 Iterative Tags


Iterative tags are easy too, since you can invoke the body multiple times:
def repeat = { attrs, body -> attrs.times?.toInteger()?.times { num -> out << body(num) } }

In this example we check for a times attribute and if it exists convert it to a number, then use Groovy's times specified number of times:
<g:repeat times="3"> <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>

Notice how in this example we use the implicit it variable to refer to the current number. This works because body we passed in the current value inside the iteration:
out << body(num)

That value is then passed as the default variable it to the tag. However, if you have nested tags this can lead should should instead name the variables that the body uses:

241

def repeat = { attrs, body -> def var = attrs.var ?: "num" attrs.times?.toInteger()?.times { num -> out << body((var):num) } }

Here we check if there is a var attribute and if there is use that as the name to pass into the body invocation on th
out << body((var):num)

Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes y using a String key and not referring to the variable itself. Now we can change the usage of the tag as follows:
<g:repeat times="3" var="j"> <p>Repeat this 3 times! Current repeat = ${j}</p> </g:repeat>

Notice how we use the var attribute to define the name of the variable j and then we are able to reference tha body of the tag.

7.3.5 Tag Namespaces

By default, tags are added to the default Grails namespace and are used with the g: prefix in GSP pages. Howev different namespace by adding a static property to your TagLib class:
class SimpleTagLib { static namespace = "my" def example = { attrs -> } }

Here we have specified a namespace of my and hence the tags in this tag lib must then be referenced from GSP
<my:example name="..." />

where the prefix is the same as the value of the static namespace property. Namespaces are particularly useful fo Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:

242

out << my.example(name:"foo")

This works from GSP, controllers or tag libraries

7.3.6 Using JSP Tag Libraries


In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do JSP to use with the taglib directive:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Then you can use it like any other tag:


<fmt:formatNumber value="${10}" pattern=".00"/>

With the added bonus that you can invoke JSP tags like methods:
${fmt.formatNumber(value:10, pattern:".00")}

7.3.7 Tag return value

Since Grails 1.2, a tag library call returns an instance of org.codehaus.groovy.grails.web.util.St class by default. This change improves performance by reducing object creation and optimizing buffering during r earlier Grails versions, a java.lang.String instance was returned.

Tag libraries can also return direct object values to the caller since Grails 1.2.. Object returning tag names a returnObjectForTags property in the tag library class. Example:
class ObjectReturningTagLib { static namespace = "cms" static returnObjectForTags = ['content'] def content = { attrs, body -> CmsContent.findByCode(attrs.code)?.content } }

7.4 URL Mappings

Throughout the documentation so far the convention used for URLs has been the default of /controller/ac this convention is not hard wired into Grails and is in fact controlled by a URL Mappings grails-app/conf/UrlMappings.groovy. The UrlMappings class contains a single property called mappings that has been assigned a block of code: 243

class UrlMappings { static mappings = { } }

7.4.1 Mapping to Controllers and Actions

To create a simple mapping simply use a relative URL as the method name and specify named parameters for the to map to:
"/product"(controller: "product", action: "list")

In this case we've mapped the URL /product to the list action of the ProductController. Omit the act to the default action of the controller:
"/product"(controller: "product")

An alternative syntax is to assign the controller and action to use within a block passed to the method:
"/product" { controller = "product" action = "list" }

Which syntax you use is largely dependent on personal preference. To rewrite one URI onto another explici controller/action pair) do something like this:
"/hello"(uri: "/hello.dispatch")

Rewriting specific URIs is often useful when integrating with other frameworks.

7.4.2 Embedded Variables


Simple Variables

The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tok of characters between each slash, '/'. A concrete token is one which is well defined such as as /product circumstances you don't know what the value of a particular token will be until runtime. In this case you can use within the URL for example:
static mappings = { "/product/$id"(controller: "product") }

244

In this case by embedding a $id variable as the second token Grails will automatically map the second token into a via the params object) called id. For example given the URL /product/MacBook, the following code will the response:
class ProductController { def index() { render params.id } }

You can of course construct more complex examples of mappings. For example the traditional blog URL forma follows:
static mappings = { "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show") }

The above mapping would let you do things like:


/graemerocher/2007/01/10/my_funky_blog_entry

The individual tokens in the URL would again be mapped into the params object with values available for year, so on.

Dynamic Controller and Action Names

Variables can also be used to dynamically construct the controller and action name. In fact the default Grails UR technique:
static mappings = { "/$controller/$action?/$id?"() }

Here the name of the controller, action and id are implicitly obtained from the variables controller, actio within the URL. You can also resolve the controller name and action name to execute dynamically using a closure:
static mappings = { "/$controller" { action = { params.goHere } } }

Optional Variables

245

Another characteristic of the default mapping is the ability to append a ? at the end of a variable to make it an further example this technique could be applied to the blog URL mapping to have more flexible linking:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }

With this mapping all of these URLs would match with only the relevant parameters being populated in the param

/graemerocher/2007/01/10/my_funky_blog_entry /graemerocher/2007/01/10 /graemerocher/2007/01 /graemerocher/2007 /graemerocher

Arbitrary Variables

You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the mapping:
"/holiday/win" { id = "Marrakech" year = 2007 }

This variables will be available within the params object passed to the controller.

Dynamically Resolved Variables

The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable base This is also possible by assigning a block to the variable name:
"/holiday/win" { id = { params.id } isEligible = { session.user != null } // must be logged in }

In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used all sorts of logic.

7.4.3 Mapping to Views

You can resolve a URL to a view without a controller or action involved. For example to map the root URL / to a grails-app/views/index.gsp you could use:

246

static mappings = { "/"(view: "/index") }

// map the root URL

Alternatively if you need a view that is specific to a given controller you could use:
static mappings = { "/help"(controller: "site", view: "help") // to a view for a controller }

7.4.4 Mapping to Response Codes

Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that match you are interested in:
static mappings = { "403"(controller: "errors", action: "forbidden") "404"(controller: "errors", action: "notFound") "500"(controller: "errors", action: "serverError") }

Or you can specify custom error pages:


static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(view: "/errors/serverError") }

Declarative Error Handling


In addition you can configure handlers for individual exceptions:
static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(controller: "errors", action: "illegalArgument", exception: IllegalArgumentException) "500"(controller: "errors", action: "nullPointer", exception: NullPointerException) "500"(controller: "errors", action: "customException", exception: MyException) "500"(view: "/errors/serverError") }

With this configuration, an IllegalArgumentException will be handled by the illegalArg ErrorsController, a NullPointerException will be handled by the nullPointer action, and a My handled by the customException action. Other exceptions will be handled by the catch-all /errors/serverError view. 247

You can access the exception from your custom error handing view or controller action using the request's exce so:
class ErrorController { def handleError() { def exception = request.exception // perform desired processing to handle the exception } }

If your error-handling controller action throws an exception as well, you'll end up w StackOverflowException.

7.4.5 Mapping to HTTP methods

URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). T RESTful APIs and for restricting mappings based on HTTP method. As an example the following mappings provide a RESTful API URL mappings for the ProductController:
static mappings = { "/product/$id"(controller:"product") { action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] } }

7.4.6 Mapping Wildcards

Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping
static mappings = { "/images/*.jpg"(controller: "image") }

This mapping will match all paths to images such as /image/logo.jpg. Of course you can achieve the same e
static mappings = { "/images/$name.jpg"(controller: "image") }

However, you can also use double wildcards to match more than one level below:
static mappings = { "/images/**.jpg"(controller: "image") }

248

In this cases the mapping will match /image/logo.jpg as well as /image/other/logo.jpg. Even double wildcard variable:
static mappings = { // will match /image/logo.jpg and /image/other/logo.jpg "/images/$name**.jpg"(controller: "image") }

In this case it will store the path matched by the wildcard inside a name parameter obtainable from the params obj
def name = params.name println name // prints "logo" or "other/logo"

If you use wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping proces provide an excludes setting inside the UrlMappings.groovy class:
class UrlMappings { static excludes = ["/images/*", "/css/*"] static mappings = { } }

In this case Grails won't attempt to match any URIs that start with /images or /css.

7.4.7 Automatic Link Re-Writing


Another great feature of URL mappings is that they automatically customize the behaviour of the link tag mappings don't require you to go and change all of your links.

This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So giv the blog one from an earlier section:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }

If you use the link tag as follows:


<g:link controller="blog" action="show" params="[blog:'fred', year:2007]"> My Blog </g:link> <g:link controller="blog" action="show" params="[blog:'fred', year:2007, month:10]"> My Blog - October 2007 Posts </g:link>

249

Grails will automatically re-write the URL in the correct format:


<a href="/fred/2007">My Blog</a> <a href="/fred/2007/10">My Blog - October 2007 Posts</a>

7.4.8 Applying Constraints

URL Mappings also support Grails' unified validation constraints mechanism, which lets you further "const matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }

This allows URLs such as:


/graemerocher/2007/01/10/my_funky_blog_entry

However, it would also allow:


/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry

This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings c further validate the URL tokens:
"/$blog/$year?/$month?/$day?/$id?" { controller = "blog" action = "show" constraints { year(matches:/\d{4}/) month(matches:/\d{2}/) day(matches:/\d{2}/) } }

In this case the constraints ensure that the year, month and day parameters match a particular valid pattern thus burden later on.

7.4.9 Named URL Mappings


URL Mappings also support named mappings, that is mappings which have a name associated with them. The refer to a specific mapping when links are generated. The syntax for defining a named mapping is as follows:

250

static mappings = { name <mapping name>: <url pattern> { // } }

For example:
static mappings = { name personList: "/showPeople" { controller = 'person' action = 'list' } name accountDetails: "/details/$acctNumber" { controller = 'product' action = 'accountDetails' } }

The mapping may be referenced in a link tag in a GSP.


<g:link mapping="personList">List People</g:link>

That would result in:


<a href="/showPeople">List People</a>

Parameters may be specified using the params attribute.


<g:link mapping="accountDetails" params="[acctNumber:'8675309']"> Show Account </g:link>

That would result in:


<a href="/details/8675309">Show Account</a>

Alternatively you may reference a named mapping using the link namespace.
<link:personList>List People</link:personList>

That would result in:

251

<a href="/showPeople">List People</a>

The link namespace approach allows parameters to be specified as attributes.


<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>

That would result in:


<a href="/details/8675309">Show Account</a>

To specify attributes that should be applied to the generated href, specify a Map value to the attrs attribute. Th applied directly to the href, not passed through to be used as request parameters.
<link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309"> Show Account </link:accountDetails>

That would result in:


<a href="/details/8675309" class="fancy">Show Account</a>

7.4.10 Customizing URL Formats

The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessi addNumbers in a controller named MathHelperController would be something like /mathHelper/a allows for the customization of this pattern and provides an implementation which replaces the camel cas hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated of "hyphenated" to the grails.web.url.converter property in grails-app/conf/Config.groovy
// grails-app/conf/Config.groovy grails.web.url.converter = 'hyphenated'

Arbitrary strategies may be plugged in by providing a class which implements the UrlConverter interface and a that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NA bean in the context with that name, it will be used as the default converter and there is no need to ass grails.web.url.converter config property.

252

// src/groovy/com/myapplication/MyUrlConverterImpl.groovy package com.myapplication class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) { // return some representation of a property or class name that should be used i } }

// grails-app/conf/spring/resources.groovy beans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }

7.5 Web Flow


Overview

Grails supports the creation of web flows built on the Spring Web Flow project. A web flow is a conversatio requests and retains state for the scope of the flow. A web flow also has a defined start and end state.

Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then r execution key that Grails passes around as a request parameter. This makes flows far more scalable than ot application that use the HttpSession and its inherit memory and clustering concerns.

Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the n managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some m flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and has multi page work flows.

From Grails 1.2 onwards Webflow is no longer in Grails core, so you must install the Webflow pl use this feature: grails install-plugin webflow

Creating a Flow

To create a flow create a regular Grails controller and add an action that ends with the convention Flow. For exam
class BookController { def index() { redirect(action: "shoppingCart") } def shoppingCartFlow = { } }

253

Notice when redirecting or referring to the flow as an action we omit the Flow suffix. In other words the nam above flow is shoppingCart.

7.5.1 Start and End States

As mentioned before a flow has a defined start and end state. A start state is the state which is entered when a conversation (or flow). The start state of a Grails flow is the first method call that takes a block. For example:
class BookController { def shoppingCartFlow ={ showCart { on( "checkout").to "enterPersonalDetails" on( "continueShopping").to "displayCatalogue" } displayCatalogue { redirect(controller: "catalogue", action: "show") } displayInvoice() } }

Here the showCart node is the start state of the flow. Since the showCart state doesn't define an action or redire view state that, by convention, refers to the view grails-app/views/book/shoppingCart/showCart. Notice that unlike regular controller actions, the views are stored within a directory that matches the grails-app/views/book/shoppingCart.

The shoppingCart flow also has two possible end states. The first is displayCatalogue which performs a another controller and action, thus exiting the flow. The second is displayInvoice which is an end state as and will simply render a view called grails-app/views/book/shoppingCart/displayInvoice.g flow at the same time.

Once a flow has ended it can only be resumed from the start state, in this case showCart, and not from any other

7.5.2 Action States and View States


View states
A view state is a one that doesn't define an action or a redirect. So for example this is a view state:
enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }

It will look for a view called grails-app/views/book/shoppingCart/enterPersonalDetails. that the enterPersonalDetails state defines two events: submit and return. The view is responsibl events. Use the render method to change the view to be rendered:

254

enterPersonalDetails { render(view: "enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }

Now it will look for grails-app/views/book/shoppingCart/enterDetailsView.gsp. Start the a / to use a shared view:
enterPersonalDetails { render(view: "/shared/enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }

Now it will look for grails-app/views/shared/enterDetailsView.gsp

Action States

An action state is a state that executes code but does not render a view. The result of the action is used to dicta create an action state you define an action to to be executed. This is done by calling the action method and pass to be executed:
listBooks { action { [bookList: Book.list()] } on("success").to "showCatalogue" on(Exception).to "handleError" }

As you can see an action looks very similar to a controller action and in fact you can reuse controller actions if y successfully returns with no errors the success event will be triggered. In this case since we return a Map, wh "model" and is automatically placed in flow scope. In addition, in the above example we also use an exception handler to deal with errors on the line:
on(Exception).to "handleError"

This makes the flow transition to a state called handleError in the case of an exception. You can write more complex actions that interact with the flow request context:

255

processPurchaseOrder { action { def a = flow.address def p = flow.person def pd = flow.paymentDetails def cartItems = flow.cartItems flow.clear() def o = new Order(person: p, shippingAddress: a, paymentDetails: pd) o.invoiceNumber = new Random().nextInt(9999999) for (item in cartItems) { o.addToItems item } o.save() [order: o] } on("error").to "confirmPurchase" on(Exception).to "confirmPurchase" on("success").to "displayInvoice" }

Here is a more complex action that gathers all the information accumulated from the flow scope and creates an O returns the order as the model. The important thing to note here is the interaction with the request context and "flow

Transition Actions

Another form of action is what is known as a transition action. A transition action is executed directly prior to sta event has been triggered. A simple example of a transition action can be seen below:
enterPersonalDetails { on("submit") { log.trace "Going to enter shipping" }.to "enterShipping" on("return").to "showCart" }

Notice how we pass a block of the code to submit event that simply logs the transition. Transition states are binding and validation, which is covered in a later section.

7.5.3 Flow Execution Events

In order to transition execution of a flow from one state to the next you need some way of trigger an event that in should do next. Events can be triggered from either view states or action states.

Triggering Events from a View State

As discussed previously the start state of the flow in a previous code listing deals with two possible events. A ch continueShopping event:
def shoppingCartFlow = { showCart { on("checkout").to "enterPersonalDetails" on("continueShopping").to "displayCatalogue" } }

256

Since the showCart event is a view state it will render the view grails-app/book/shoppingCart/sho this view you need to have components that trigger flow execution. On a form this can be done use the submitButt
<g:form> <g:submitButton name="continueShopping" value="Continue Shopping" /> <g:submitButton name="checkout" value="Checkout" /> </g:form>

The form automatically submits back to the shoppingCart flow. The name attribute of each submitButton tag will be triggered. If you don't have a form you can also trigger an event with the link tag as follows:
<g:link event="checkout" />

Prior to 2.0.0, it was required to specify the controller and/or action in forms and links, which caused to change when entering a subflow state. When the controller and action are not specified, all u relative to the main flow execution url, which makes your flows reusable as subflows and prevents with the browser's back button.

Triggering Events from an Action

To trigger an event from an action you invoke a method. For example there is the built in error() and succ example below triggers the error() event on validation failure in a transition action:
enterPersonalDetails { on("submit") { def p = new Person(params) flow.person = p if (!p.validate()) return error() }.to "enterShipping" on("return").to "showCart" }

In this case because of the error the transition action will make the flow go back to the enterPersonalDetail With an action state you can also trigger events to redirect flow:
shippingNeeded { action { if (params.shippingRequired) yes() else no() } on("yes").to "enterShipping" on("no").to "enterPayment" }

7.5.4 Flow Scopes

257

Scope Basics

You'll notice from previous examples that we used a special object called flow to store objects within "flow scop five different scopes you can utilize: request - Stores an object for the scope of the current request flash - Stores the object for the current and next request only flow - Stores objects for the scope of the flow, removing them when the flow reaches an end state

conversation - Stores objects for the scope of the conversation including the root flow and nested subflo session - Stores objects in the user's session

Grails service classes can be automatically scoped to a web flow scope. See the documentation on S for more information.

Returning a model Map from an action will automatically result in the model being placed in flow scope. F transition action, you can place objects within flow scope as follows:
enterPersonalDetails { on("submit") { [person: new Person(params)] }.to "enterShipping" on("return").to "showCart" }

Be aware that a new request is always created for each state, so an object placed in request scope in an action sta not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another Flow: 1. Moves objects from flash scope to request scope upon transition between states;

2. Merges objects from the flow and conversation scopes into the view model before rendering (so you shou prefix when referencing these objects within a view, e.g. GSP pages).

Flow Scopes and Serialization

When placing objects in flash, flow or conversation scope they must implement java.io.Serializa will be thrown. This has an impact on domain classes in that domain classes are typically placed within a scop rendered in a view. For example consider the following domain class:
class Book { String title }

To place an instance of the Book class in a flow scope you will need to modify it as follows:

258

class Book implements Serializable { String title }

This also impacts associations and closures you declare within a domain class. For example consider this:
class Book implements Serializable { String title Author author }

Here if the Author association is not Serializable you will also get an error. This also impacts closures u such as onLoad, onSave and so on. The following domain class will cause an error if an instance is placed in a f
class Book implements Serializable { String title def onLoad = { println "I'm loading" } }

The reason is that the assigned block on the onLoad event cannot be serialized. To get around this you should transient:
class Book implements Serializable { String title transient onLoad = { println "I'm loading" } }

or as methods:
class Book implements Serializable { String title def onLoad() { println "I'm loading" } }

259

The flow scope contains a reference to the Hibernate session. As a result, any object loaded into the through a GORM query will also be in the flow and will need to implement Serializable.

If you don't want your domain class to be Serializable or stored in the flow, then you will need to ev entity manually before the end of the state:
flow.persistenceContext.evict(it)

7.5.5 Data Binding and Validation

In the section on start and end states, the start state in the first example triggered a transition to the enterPerso This state renders a view and waits for the user to enter the required information:
enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }

The view contains a form with two submit buttons that either trigger the submit event or the return event:
<g:form> <!-- Other fields --> <g:submitButton name="submit" value="Continue"></g:submitButton> <g:submitButton name="return" value="Back"></g:submitButton> </g:form>

However, what about the capturing the information submitted by the form? To capture the form info we can action:
enterPersonalDetails { on("submit") { flow.person = new Person(params) !flow.person.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }

Notice how we perform data binding from request parameters and place the Person instance within flow scop that we perform validation and invoke the error() method if validation fails. This signals to the flow that the and return to the enterPersonalDetails view so valid entries can be entered by the user, otherwise continue and go to the enterShipping state.

Like regular actions, flow actions also support the notion of Command Objects by defining the first argument of th

260

enterPersonalDetails { on("submit") { PersonDetailsCommand cmd -> flow.personDetails = cmd !flow.personDetails.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }

7.5.6 Subflows and Conversations


Calling subflows

Grails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this
def searchFlow = { displaySearchForm { on("submit").to "executeSearch" } executeSearch { action { [results:searchService.executeSearch(params.q)] } on("success").to "displayResults" on("error").to "displaySearchForm" } displayResults { on("searchDeeper").to "extendedSearch" on("searchAgain").to "displaySearchForm" } extendedSearch { // Extended search subflow subflow(controller: "searchExtensions", action: "extendedSearch") on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" } displayMoreResults() displayNoMoreResults() }

It references a subflow in the extendedSearch state. The controller parameter is optional if the subflow is controller as the calling flow.

Prior to 1.3.5, the previous subflow call would look like subflow SearchExtensionsController().extendedSearchFlow), with the requirement that th of the subflow state be the same as the called subflow (minus Flow). This way of calling a sub deprecated and only supported for backward compatibility. The subflow is another flow entirely:

261

def extendedSearchFlow = { startExtendedSearch { on("findMore").to "searchMore" on("searchAgain").to "noResults" } searchMore { action { def results = searchService.deepSearch(ctx.conversation.query) if (!results) return error() conversation.extendedResults = results } on("success").to "moreResults" on("error").to "noResults" } moreResults() noResults() }

Notice how it places the extendedResults in conversation scope. This scope differs to flow scope as it let spans the whole conversation, i.e. a flow execution including all subflows, not just the flow itself. Also notice tha moreResults or noResults of the subflow triggers the events in the main flow:
extendedSearch { // Extended search subflow subflow(controller: "searchExtensions", action: "extendedSearch") on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" }

Subflow input and output

Using conversation scope for passing input and output between flows can be compared with using global variable between methods. While this is OK in certain situations, it is usually better to use method arguments and retur speak, this means defining input and output arguments for flows. Consider following flow for searching a person with a certain expertise:

262

def searchFlow = { input { expertise(required: true) title( "Search person") } search { onEntry { [personInstanceList: Person.findAllByExpertise(flow.expertise)] } on( "select") { flow.person = Person.get(params.id) }.to( "selected") on( "cancel").to("cancel") } selected { output { person {flow.person} } } cancel() } }

This flow accepts two input parameters: a required expertise argument an optional title argument with a default value All input arguments are stored in flow scope and are, just like local variables, only visible within this flow.

A flow that contains required input will throw an exception when an execution is started without providing the inp is that these flows can only be started as subflows.

Notice how an end state can define one or more named output values. If the value is a closure, this closure will be of each flow execution. If the value is not a closure, the value will be a constant that is only calculated once at flow When a subflow is called, we can provide it a map with input values:
def newProjectWizardFlow = { ... managerSearch { subflow(controller: "person", action: "search", input: [expertise : "management", title: "Search project manager"]) on("selected") { flow.projectInstance.manager = currentEvent.attributes.person }.to "techleadSearch" }

techleadSearch { subflow(controller: "person", action: "search", input: [expertise : { flow.technology }, title: "Search technical lead" on("selected") { flow.projectInstance.techlead = currentEvent.attributes.person }.to "projectDetails" } ... }

263

Notice again the difference between constant values like expertise : "management" and dynamic values { flow.technology } The subflow output is available via currentEvent.attributes

7.6 Filters

Although Grails controllers support fine grained interceptors, these are only really useful when applied to a few co difficult to manage with larger applications. Filters on the other hand can be applied across a whole group of con or to a specific action. Filters are far easier to plugin and maintain completely separately to your main controlle for all sorts of cross cutting concerns such as security, logging, and so on.

7.6.1 Applying Filters

To create a filter create a class that ends with the convention Filters in the grails-app/conf directory. W a code block called filters that contains the filter definitions:
class ExampleFilters { def filters = { // your filters here } }

Each filter you define within the filters block has a name and a scope. The name is the method name and the s named arguments. For example to define a filter that applies to all controllers and all actions you can use wildcard
sampleFilter(controller:'*', action:'*') { // interceptor definitions }

The scope of the filter can be one of the following things: A controller and/or action name pairing with optional wildcards A URI, with Ant path matching syntax Filter rule attributes: controller - controller matching pattern, by default * is replaced with .* and a regex is compiled

controllerExclude - controller exclusion pattern, by default * is replaced with .* and a regex is compil action - action matching pattern, by default * is replaced with .* and a regex is compiled actionExclude - action exclusion pattern, by default * is replaced with .* and a regex is compiled regex (true/false) - use regex syntax (don't replace '*' with '.*') uri - a uri to match, expressed with as Ant style path (e.g. /book/**) uriExclude - a uri pattern to exclude, expressed with as Ant style path (e.g. /book/**) find (true/false) - rule matches with partial match (see java.util.regex.Matcher.find()) invert (true/false) - invert the rule (NOT rule) 264

Some examples of filters include: All controllers and actions

all(controller: '*', action: '*') { }

Only for the BookController

justBook(controller: 'book', action: '*') { }

All controllers except the BookController

notBook(controller: 'book', invert: true) { }

All actions containing 'save' in the action name

saveInActionName(action: '*save*', find: true) { }

All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'

actionBeginningWithBButNotBad(action: 'b*', actionExclude: 'bad*', find: true) { }

Applied to a URI space

someURIs(uri: '/book/**') { }

Applied to all URIs

allURIs(uri: '/**') { }

265

In addition, the order in which you define the filters within the filters code block dictates the order in which control the order of execution between Filters classes, you can use the dependsOn property discussed i section.

Note: When exclude patterns are used they take precedence over the matching patterns. For exam action is 'b*' and actionExclude is 'bad*' then actions like 'best' and 'bien' will have that filter appl actions like 'bad' and 'badlands' will not.

7.6.2 Filter Types


Within the body of the filter you can then define one or several of the following interceptor types for the filter:

before - Executed before the action. Return false to indicate that the response has been handled that tha the action should not execute

after - Executed after an action. Takes a first argument as the view model to allow modification of the m the view

afterView - Executed after view rendering. Takes an Exception as an argument which will be non- null i during processing. Note: this Closure is called before the layout is applied. For example to fulfill the common simplistic authentication use case you could define a filter as follows:
class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if (!session.user && !actionName.equals('login')) { redirect(action: 'login') return false } } } } }

Here the loginCheck filter uses a before interceptor to execute a block of code that checks if a user is in t redirects to the login action. Note how returning false ensure that the action itself is not executed. Here's a more involved example that demonstrates all three filter types:

266

import java.util.concurrent.atomic.AtomicLong class LoggingFilters {

private static final AtomicLong REQUEST_NUMBER_COUNTER = new AtomicLong() private static final String START_TIME_ATTRIBUTE = 'Controller__START_TIME__' private static final String REQUEST_NUMBER_ATTRIBUTE = 'Controller__REQUEST_NUMBER__ def filters = { logFilter(controller: '*', action: '*') { before = { if (!log.debugEnabled) return true long start = System.currentTimeMillis() long currentRequestNumber = REQUEST_NUMBER_COUNTER.incrementAndGet() request[START_TIME_ATTRIBUTE] = start request[REQUEST_NUMBER_ATTRIBUTE] = currentRequestNumber

log.debug "preHandle request #$currentRequestNumber : " + "'$request.servletPath'/'$request.forwardURI', " + "from $request.remoteHost ($request.remoteAddr) " + " at ${new Date()}, Ajax: $request.xhr, controller: $controllerName, " + "action: $actionName, params: ${new TreeMap(params)}" return true } after = { Map model -> if (!log.debugEnabled) return true long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE] def msg = "postHandle request #$requestNumber: end ${new Date()}, " + "controller total time ${end - start}ms" if (log.traceEnabled) { log.trace msg + "; model: $model" } else { log.debug msg } } afterView = { Exception e -> if (!log.debugEnabled) return true long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE] def msg = "afterCompletion request #$requestNumber: " + "end ${new Date()}, total time ${end - start}ms" if (e) { log.debug "$msg \n\texception: $e.message", e } else { log.debug msg } } } } }

In this logging example we just log various request information, but note that the model map in the after fil need to add or remove items from the model map you can do that in the after filter.

267

7.6.3 Variables and Scopes


Filters support all the common properties available to controllers and tag libraries, plus the application context: request - The HttpServletRequest object response - The HttpServletResponse object session - The HttpSession object servletContext - The ServletContext object flash - The flash object params - The request parameters object actionName - The action name that is being dispatched to controllerName - The controller name that is being dispatched to grailsApplication - The Grails application currently running applicationContext - The ApplicationContext object However, filters only support a subset of the methods available to controllers and tag libraries. These include: redirect - For redirects to other controllers and actions render - For rendering custom responses

7.6.4 Filter Dependencies

In a Filters class, you can specify any other Filters classes that should first be executed using the depend used when a Filters class depends on the behavior of another Filters class (e.g. setting up the environ request/session, etc.) and is defined as an array of Filters classes. Take the following example Filters classes:
class MyFilters { def dependsOn = [MyOtherFilters] def filters = { checkAwesome(uri: "/*") { before = { if (request.isAwesome) { // do something awesome } } } checkAwesome2(uri: "/*") { before = { if (request.isAwesome) { // do something else awesome } } } } }

268

class MyOtherFilters { def filters = { makeAwesome(uri: "/*") { before = { request.isAwesome = true } } doNothing(uri: "/*") { before = { // do nothing } } } }

MyFilters specifically dependsOn MyOtherFilters. This will cause all the filters in MyOtherFilters whose scop request to be executed before those in MyFilters. For a request of "/test", which will match the scope of every filte execution order would be as follows: MyOtherFilters - makeAwesome MyOtherFilters - doNothing MyFilters - checkAwesome MyFilters - checkAwesome2

The filters within the MyOtherFilters class are processed in order first, followed by the filters in the MyFilters c between Filters classes are enabled and the execution order of filters within each Filters class are preserve

If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of processing will continue. Information about any cyclical dependencies that are detected will be written to the lo root logging level is set to at least WARN or configure an appender for the Grails org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin) when debugg issues.

7.7 Ajax

Ajax is the driving force behind the shift to richer web applications. These types of applications in general are dynamic frameworks written in languages like Groovy and Ruby Grails provides support for building Ajax ap Ajax tag library. For a full list of these see the Tag Library Reference.

7.7.1 Ajax Support

By default Grails ships with the jQuery library, but through the Plugin system provides support for other framewo , Dojo:http://dojotoolkit.org/, Yahoo UI:http://developer.yahoo.com/yui/ and the Google Web Toolkit.

This section covers Grails' support for Ajax in general. To get started, add this line to the <head> tag of your pag
<g:javascript library="jquery" />

You can replace jQuery with any other library supplied by a plugin you have installed. This works because adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax librari limited to):

269

jQuery Prototype Dojo YUI MooTools

7.7.1.1 Remoting Linking

Remote content can be loaded in a number of ways, the most commons way is through the remoteLink tag. This ta of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The sim remote link is as follows:
<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>

The above link sends an asynchronous request to the delete action of the current controller with an id of 1.

7.7.1.2 Updating Content


This is great, but usually you provide feedback to the user about what happened:
def delete() { def b = Book.get(params.id) b.delete() render "Book ${b.id} was deleted" }

GSP code:
<div id="message"></div> <g:remoteLink action="delete" id="1" update="message"> Delete Book </g:remoteLink>

The above example will call the action and set the contents of the message div to the response in this c deleted". This is done by the update attribute on the tag, which can also take a Map to indicate what should b
<div id="message"></div> <div id="error"></div> <g:remoteLink update="[success: 'message', failure: 'error']" action= "delete" id="1"> Delete Book </g:remoteLink>

Here the error div will be updated if the request failed.

270

7.7.1.3 Remote Form Submission

An HTML form can also be submitted asynchronously in one of two ways. Firstly using the formRemote tag w attributes to those for the remoteLink tag:
<g:formRemote url="[controller: 'book', action: 'delete']" update= "[success: 'message', failure: 'error']"> <input type="hidden" name="id" value="1" /> <input type="submit" value="Delete Book!" /> </g:formRemote >

Or alternatively you can use the submitToRemote tag to create a submit button. This allows some buttons to subm not depending on the action:
<form action="delete"> <input type="hidden" name="id" value="1" /> <g:submitToRemote action="delete" update= "[success: 'message', failure: 'error']" /> </form>

7.7.1.4 Ajax Events

Specific JavaScript can be called if certain events occur, all the events start with the "on" prefix and let you give where appropriate, or take other action:
<g:remoteLink action="show" id="1" update="success" onLoading="showProgress()" onComplete= "hideProgress()">Show Book 1</g:remoteLink>

The above code will execute the "showProgress()" function which may show a progress bar or whatever is appr include: onSuccess - The JavaScript function to call if successful onFailure - The JavaScript function to call if the call failed

on_ERROR_CODE - The JavaScript function to call to handle specified error codes (eg on404="alert('not fou onUninitialized - The JavaScript function to call the a Ajax engine failed to initialise onLoading - The JavaScript function to call when the remote function is loading the response onLoaded - The JavaScript function to call when the remote function is completed loading the response

onComplete - The JavaScript function to call when the remote function is complete, including any updates If you need a reference to the XmlHttpRequest object you can use the implicit event parameter e to obtain it:

271

<g:javascript> function fireMe(e) { alert("XmlHttpRequest = " + e) } } </g:javascript> <g:remoteLink action="example" update="success" onSuccess= "fireMe(e)">Ajax Link</g:remoteLink>

7.7.2 Ajax with Prototype

Grails features an external plugin to add Prototype support to Grails. To install the plugin type the following comm your project in a terminal window:
grails install-plugin prototype

This will download the current supported version of the Prototype plugin and install it into your Grails project. W add the following reference to the top of your page:
<g:javascript library="prototype" />

If you require Scriptaculous too you can do the following instead:


<g:javascript library="scriptaculous" />

Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Prototype remoting.

7.7.3 Ajax with Dojo

Grails features an external plugin to add Dojo support to Grails. To install the plugin type the following comm your project in a terminal window:
grails install-plugin dojo

This will download the current supported version of Dojo and install it into your Grails project. With that d following reference to the top of your page:
<g:javascript library="dojo" />

Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Dojo remoting.

7.7.4 Ajax with GWT


272

Grails also features support for the Google Web Toolkit through a plugin. There is comprehensive documenta Grails wiki.

7.7.5 Ajax on the Server


There are a number of different ways to implement Ajax which are typically broken down into: Content Centric Ajax - Where you just use the HTML result of a remote call to update the page

Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatical Script Centric Ajax - Where the server sends down a stream of JavaScript to be evaluated on the fly Most of the examples in the Ajax section cover Content Centric Ajax where you are updating the page, but you Data Centric or Script Centric. This guide covers the different styles of Ajax.

Content Centric Ajax

Just to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by with the render method:
def showBook() { def b = Book.get(params.id) render(template: "bookTemplate", model: [book: b]) }

Calling this on the client involves using the remoteLink tag:


<g:remoteLink action="showBook" id="${book.id}" update= "book${book.id}">Update Book</g:remoteLink> <div id="book${book.id}"> <!--existing book mark-up --> </div>

Data Centric Ajax with JSON

Data Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a Grails you would typically use Grails' JSON marshalling capability:
import grails.converters.JSON def showBook() { def b = Book.get(params.id) render b as JSON }

And then on the client parse the incoming JSON request using an Ajax event handler:

273

<g:javascript> function updateBook(e) { var book = eval("("+e.responseText+")") // evaluate the JSON $("book" + book.id + "_title").innerHTML = book.title } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>

Data Centric Ajax with XML


On the server side using XML is equally simple:
import grails.converters.XML def showBook() { def b = Book.get(params.id) render b as XML }

However, since DOM is involved the client gets more complicated:


<g:javascript> function updateBook(e) { var xml = e.responseXML var id = xml.getElementsByTagName("book").getAttribute("id") $("book" + id + "_title") = xml.getElementsByTagName("title")[0].textContent } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>

Script Centric Ajax with JavaScript


Script centric Ajax involves actually sending JavaScript back that gets evaluated on the client. An example of this
def showBook() { def b = Book.get(params.id) response.contentType = "text/javascript" String title = b.title.encodeAsJavascript() render "$('book${b.id}_title')='${title}'" }

274

The important thing to remember is to set the contentType to text/javascript. If you use Prototype on t JavaScript will automatically be evaluated due to this contentType setting.

Obviously in this case it is critical that you have an agreed client-side API as you don't want changes on the clien This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature su Dynamic JavaScript Plugin that offers similar capabilities.

Responding to both Ajax and non-Ajax requests

It's straightforward to have the same Grails controller action handle both Ajax and non-Ajax requests. Grails method to HttpServletRequest which can be used to identify Ajax requests. For example you could ren using a template for Ajax requests or the full page for regular HTTP requests:
def listBooks() { def books = Book.list(params) if (request.xhr) { render template: "bookTable", model: [books: books] } else { render view: "list", model: [books: books] } }

7.8 Content Negotiation

Grails has built in support for Content negotiation using either the HTTP Accept header, an explicit format req extension of a mapped URI.

Configuring Mime Types

Before you can start dealing with content negotiation you need to tell Grails what content types you wish to supp comes configured with a number of different content types within grails-app/conf/Config.g grails.mime.types setting:
grails.mime.types = [ xml: ['text/xml', 'application/xml'], text: 'text-plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', all: '*/*', json: 'text/json', html: ['text/html','application/xhtml+xml'] ]

The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'ap types as simply 'xml'. You can add your own types by simply adding new entries into the map.

Content Negotiation using the Accept header

Every incoming HTTP request has a special Accept header that defines what media types (or mime types) a c older browsers this is typically:

275

*/*

Which simply means anything. However, on newer browser something all together more useful is sent such as (an Accept header):
text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5

Grails parses this incoming format and adds a property to the response object that outlines the preferred resp above example the following assertion would pass:
assert 'html' == response.format

Why? The text/html media type has the highest "quality" rating of 0.9, therefore is the highest priority. browser as mentioned previously the result is slightly different:
assert 'all' == response.format

In this case 'all' possible formats are accepted by the client. To deal with different kinds of requests from Contro withFormat method that acts as kind of a switch statement:
import grails.converters.XML class BookController { def list() { def books = Book.list() withFormat { html bookList: books js { render "alert('hello')" } xml { render books as XML } } } }

If the preferred format is html then Grails will execute the html() call only. This causes Grails to look for grails-app/views/books/list.html.gsp or grails-app/views/books/list.gsp. If the fo closure will be invoked and an XML response rendered.

How do we handle the "all" format? Simply order the content-types within your withFormat block so that wh executed comes first. So in the above example, "all" will trigger the html handler.

When using withFormat make sure it is the last call in your controller action as the return value withFormat method is used by the action to dictate what happens next.

276

Request format vs. Response format

As of Grails 2.0, there is a separate notion of the request format and the response format. The request form CONTENT_TYPE header and is typically used to detect if the incoming request can be parsed into XML or JSON format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response t The withFormat available on controllers deals specifically with the response format. If you wish to add logic that format then you can do so using a separate withFormat method available on the request:
request.withFormat { xml { // read XML } json { // read JSON } }

Content Negotiation with the format Request Parameter

If fiddling with request headers if not your favorite activity you can override the format used by specifying parameter:
/book/list?format=xml

You can also define this parameter in the URL Mappings definition:
"/book/list"(controller:"book", action:"list") { format = "xml" }

Content Negotiation with URI Extensions


Grails also supports content negotiation using URI extensions. For example given the following URI:
/book/list.xml

Grails will remove the extension and map it to /book/list instead whilst simultaneously setting the content fo this extension. This behaviour is enabled by default, so if you wish to turn it off, yo grails.mime.file.extensions property in grails-app/conf/Config.groovy to false:
grails.mime.file.extensions = false

Testing Content Negotiation


277

To test content negotiation in a unit or integration test (see the section on Testing) you can either manipulate headers:
void testJavascriptOutput() { def controller = new TestController() controller.request.addHeader "Accept", "text/javascript, text/html, application/xml, text/xml, */*" controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }

Or you can set the format parameter to achieve a similar effect:


void testJavascriptOutput() { def controller = new TestController() controller.params.format = 'js' controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }

278

8 Validation

Grails validation capability is built on Spring's Validator API and data binding capabilities. However Grails t provides a unified way to define validation "constraints" with its constraints mechanism.

Constraints in Grails are a way to declaratively specify validation rules. Most commonly they are applied to dom URL Mappings and Command Objects also support constraints.

8.1 Declaring Constraints


Within a domain class constraints are defined with the constraints property that is assigned a code block:
class User { String login String password String email Integer age static constraints = { } }

You then use method calls that match the property name for which the constraint applies in combination with specify constraints:
class User { ... static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }

In this example we've declared that the login property must be between 5 and 15 characters long, it cannot b unique. We've also applied other constraints to the password, email and age properties.

By default, all domain class properties are not nullable (i.e. they have an implicit nullable: f constraint).

A complete reference for the available constraints can be found in the Quick Reference section under the Constrain

Note that constraints are only evaluated once which may be relevant for a constraint that relies on a value java.util.Date.

279

class User { ... static constraints = { // this Date object is created when the constraints are evaluated, not // each time an instance of the User class is validated. birthDate max: new Date() } }

A word of warning - referencing domain class properties from constraints

It's very easy to attempt to reference instance variables from the static constraints block, but this isn't legal in Gro do so, you will get a MissingPropertyException for your trouble. For example, you may try
class Response { Survey survey Answer answer static constraints = { survey blank: false answer blank: false, inList: survey.answers } }

See how the inList constraint references the instance property survey? That won't work. Instead, use a custom
class Response { static constraints = { survey blank: false answer blank: false, validator: { val, obj -> val in obj.survey.answers } } }

In this example, the obj argument to the custom validator is the domain instance that is being validated, so we ca property and return a boolean to indicate whether the new value for the answer property, val, is valid.

8.2 Validating Constraints


Validation Basics
Call the validate method to validate a domain class instance:
def user = new User(params) if (user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }

280

The errors property on domain classes is an instance of the Spring Errors interface. The Errors interface navigate the validation errors and also retrieve the original values.

Validation Phases

Within Grails there are two phases of validation, the first one being data binding which occurs when you bind req an instance such as:
def user = new User(params)

At this point you may already have errors in the errors property due to type conversion (such as converting S can check these and obtain the original input value using the Errors API:
if (user.hasErrors()) { if (user.errors.hasFieldErrors("login")) { println user.errors.getFieldError("login").rejectedValue } }

The second phase of validation happens when you call validate or save. This is when Grails will validate the bou constraints you defined. For example, by default the save method calls validate before executing, allowing you
if (user.save()) { return user } else { user.errors.allErrors.each { println it } }

8.3 Sharing Constraints Between Classes

A common pattern in Grails is to use command objects for validating user-submitted data and then copy the prope object to the relevant domain classes. This often means that your command objects and domain classes share constraints. You could manually copy and paste the constraints between the two, but that's a very error-prone app use of Grails' global constraints and import mechanism.

Global Constraints

In addition to defining constraints in domain classes, command objects and other validateable classes, you can grails-app/conf/Config.groovy:
grails.gorm.default.constraints = { '*'(nullable: true, size: 1..20) myShared(nullable: false, blank: false) }

281

These constraints are not attached to any particular classes, but they can be easily referenced from any validateable
class User { ... static constraints = { login shared: "myShared" } }

Note the use of the shared argument, whose value is the name of one of the constr grails.gorm.default.constraints. Despite the name of the configuration setting, you can ref constraints from any validateable class, such as command objects.

The '*' constraint is a special case: it means that the associated constraints ('nullable' and 'size' in the above examp all properties in all validateable classes. These defaults can be overridden by the constraints declared in a validatea

Importing Constraints

Grails 2 introduced an alternative approach to sharing constraints that allows you to import a set of constraint another. Let's say you have a domain class like so:
class User String String String { firstName lastName passwordHash

static constraints = { firstName blank: false, nullable: false lastName blank: false, nullable: false passwordHash blank: false, nullable: false } }

You then want to create a command object, UserCommand, that shares some of the properties of the d corresponding constraints. You do this with the importFrom() method:
class UserCommand { String firstName String lastName String password String confirmPassword static constraints = { importFrom User password blank: false, nullable: false confirmPassword blank: false, nullable: false } }

282

This will import all the constraints from the User domain class and apply them to UserCommand. The im constraints in the source class (User) that don't have corresponding properties in the importing class (UserCom example, only the 'firstName' and 'lastName' constraints will be imported into UserCommand because those ar shared by the two classes.

If you want more control over which constraints are imported, use the include and exclude arguments. Both of simple or regular expression strings that are matched against the property names in the source constraints. So only wanted to import the 'lastName' constraint you would use:
static constraints = { importFrom User, include: ["lastName"] }

or if you wanted all constraints that ended with 'Name':


static constraints = { importFrom User, include: [/.*Name/] }

Of course, exclude does the reverse, specifying which constraints should not be imported.

8.4 Validation on the Client


Displaying Errors

Typically if you get a validation error you redirect back to the view for rendering. Once there you need some way Grails supports a rich set of tags for dealing with errors. To render the errors as a list you can use renderErrors:
<g:renderErrors bean="${user}" />

If you need more control you can use hasErrors and eachError:
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li>${err}</li> </g:eachError> </ul> </g:hasErrors>

Highlighting Errors

It is often useful to highlight using a red box or some indicator when a field has been incorrectly input. This can a hasErrors by invoking it as a method. For example:

283

<div class='value ${hasErrors(bean:user,field:'login','errors')}'> <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/> </div>

This code checks if the login field of the user bean has any errors and if so it adds an errors CSS class to th to use CSS rules to highlight the div.

Retrieving Input Values

Each error is actually an instance of the FieldError class in Spring, which retains the original input value within it. can use the error object to restore the value input by the user using the fieldValue tag:
<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>

This code will check for an existing FieldError in the User bean and if there is obtain the originally input field.

8.5 Validation and Internationalization

Another important thing to note about errors in Grails is that error messages are not hard coded anywhere. Th Spring resolves messages from message bundles using Grails' i18n support.

Constraints and Message Codes


The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:
package com.mycompany.myapp class User { ... static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }

If a constraint is violated Grails will by convention look for a message code of the form:
[Class Name].[Property Name].[Constraint Code]

In the case of the blank constraint this would be user.login.blank so you would need a message such as t grails-app/i18n/messages.properties file:
user.login.blank=Your login name must be specified!

284

The class name is looked for both with and without a package, with the packaged version taking preceden com.mycompany.myapp.User.login.blank will be used before user.login.blank. This allows for cases where your d codes clash with a plugin's. For a reference on what codes are for which constraints refer to the reference guide for each constraint.

Displaying Messages

The renderErrors tag will automatically look up messages for you using the message tag. If you need more control handle this yourself:
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li><g:message error="${err}" /></li> </g:eachError> </ul> </g:hasErrors>

In this example within the body of the eachError tag we use the message tag in combination with its error message for the given error.

8.6 Applying Validation to Other Classes

Domain classes and command objects support validation by default. Other classes may be made validateable b constraints property in the class (as described above) and then telling the framework about them. It application register the validateable classes with the framework. Simply defining the constraints property is n

The Validateable Annotation

Classes which define the static constraints property and are annotated with @Validateable can be made framework. Consider this example:
// src/groovy/com/mycompany/myapp/User.groovy package com.mycompany.myapp import grails.validation.Validateable @Validateable class User { ... static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }

Registering Validateable Classes

285

If a class is not marked with Validateable, it may still be made validateable by the steps required to do this are to define the static constraints property in described above) and then telling the framework about the class by assigni the grails.validateable.classes property in Config.groovy@:
grails.validateable.classes = [com.mycompany.myapp.User, com.mycompany.dto.Account]

286

9 The Service Layer

Grails defines the notion of a service layer. The Grails team discourages the embedding of core application logic it does not promote reuse and a clean separation of concerns.

Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible flow with redirects and so on.

Creating a Service
You can create a Grails service by running the create-service command from the root of your project in a terminal
grails create-service helloworld.simple

If no package is specified with the create-service script, Grails automatically uses the application n the package name.

The above example will create a service at the location grails-app/services/helloworld/SimpleSe service's name ends with the convention Service, other than that a service is a plain Groovy class:
package helloworld class SimpleService { }

9.1 Declarative Transactions


Default Declarative Transactions

Services are typically involved with coordinating logic between domain classes, and hence often involved with p large operations. Given the nature of services, they frequently require transactional behaviour. You can use progr with the withTransaction method, however this is repetitive and doesn't fully leverage the power of Spring's u abstraction.

Services enable transaction demarcation, which is a declarative way of defining which methods are to be ma services are transactional by default. To disable this set the transactional property to false:
class CountryService { static transactional = false }

You may also set this property to true to make it clear that the service is intentionally transactional.

287

Warning: dependency injection is the only way that declarative transactions work. You will no transactional service if you use the new operator such as new BookService()

The result is that all methods are wrapped in a transaction and automatic rollback occurs if a method throws a ru one that extends RuntimeException) or an Error. The propagation level of the transaction is PROPAGATION_REQUIRED.

Checked exceptions do not roll back transactions. Even though Groovy blurs the distinction b checked and unchecked exceptions, Spring isn't aware of this and its default behaviour is used, important to understand the distinction between checked and unchecked exceptions.

Custom Transaction Configuration

Grails also fully supports Spring's Transactional annotation for cases where you need more fine-grained con at a per-method level or need specify an alternative propagation level.

Annotating a service method with Transactional disables the default Grails transactional behav that service (in the same way that adding transactional=false does) so if you use any anno you must annotate all methods that require transactions. In this example listBooks uses a read-only transaction, updateBook uses a default read-write transaction, not transactional (probably not a good idea given its name).
import org.springframework.transaction.annotation.Transactional class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } @Transactional def updateBook() { // } def deleteBook() { // } }

You can also annotate the class to define the default transaction behavior for the whole service, and then per-method. For example, this service is equivalent to one that has no annotations (since the de transactional=true):

288

import org.springframework.transaction.annotation.Transactional @Transactional class BookService { def listBooks() { Book.list() } def updateBook() { // } def deleteBook() { // } }

This version defaults to all methods being read-write transactional (due to the class-level annotation), but the l overrides this to use a read-only transaction:
import org.springframework.transaction.annotation.Transactional @Transactional class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } def updateBook() { // } def deleteBook() { // } }

Although updateBook and deleteBook aren't annotated in this example, they inherit the configuration annotation. For more information refer to the section of the Spring user guide on Using @Transactional.

Unlike Spring you do not need any prior configuration to use Transactional; just specify the annotation as n detect them up automatically.

9.1.1 Transactions Rollback and the Session


Understanding Transactions and the Hibernate Session

When using transactions there are important considerations you must take into account with regards to how the u session is handled by Hibernate. When a transaction is rolled back the Hibernate session used by GORM is clea objects within the session become detached and accessing uninitialized lazy-loaded collection LazyInitializationExceptions. To understand why it is important that the Hibernate session is cleared. Consider the following example:

289

class Author { String name Integer age static hasMany = [books: Book] }

If you were to save two authors using consecutive transactions as follows:


Author.withTransaction { status -> new Author(name: "Stephen King", age: 40).save() status.setRollbackOnly() } Author.withTransaction { status -> new Author(name: "Stephen King", age: 40).save() }

Only the second author would be saved since the first transaction rolls back the author save() by clearing the the Hibernate session were not cleared then both author instances would be persisted and it would lead to very une It can, however, be frustrating to get LazyInitializationExceptions due to the session being cleared. For example, consider the following example:
class AuthorService { void updateAge(id, int age) { def author = Author.get(id) author.age = age if (author.isTooOld()) { throw new AuthorException("too old", author) } } }

class AuthorController { def authorService def updateAge() { try { authorService.updateAge(params.id, params. int("age")) } catch(e) { render "Author books ${e.author.books}" } } }

In the above example the transaction will be rolled back if the Author's age exceeds the maximum va isTooOld() method by throwing an AuthorException. The AuthorException references the author association is accessed a LazyInitializationException will be thrown because the underlying Hibern cleared.

To solve this problem you have a number of options. One is to ensure you query eagerly to get the data you will ne 290

class AuthorService { void updateAge(id, int age) { def author = Author.findById(id, [fetch:[books:"eager"]]) ...

In this example the books association will be queried when retrieving the Author.

This is the optimal solution as it requires fewer queries then the following suggested solutions. Another solution is to redirect the request after a transaction rollback:
class AuthorController { AuthorService authorService def updateAge() { try { authorService.updateAge(params.id, params. int("age")) } catch(e) { flash.message "Can't update age" redirect action: "show", id:params.id } } }

In this case a new request will deal with retrieving the Author again. And, finally a third solution is to retri Author again to make sure the session remains in the correct state:
class AuthorController { def authorService def updateAge() { try { authorService.updateAge(params.id, params. int("age")) } catch(e) { def author = Author.read(params.id) render "Author books ${author.books}" } } }

Validation Errors and Rollback


A common use case is to rollback a transaction if there are validation errors. For example consider this service:

291

import grails.validation.ValidationException class AuthorService { void updateAge(id, int age) { def author = Author.get(id) author.age = age if (!author.validate()) { throw new ValidationException("Author is not valid", author.errors) } } }

To re-render the same view that a transaction was rolled back in you can re-associate the errors with a refre rendering:
import grails.validation.ValidationException class AuthorController { def authorService def updateAge() { try { authorService.updateAge(params.id, params. int("age")) } catch (ValidationException e) { def author = Author.read(params.id) author.errors = e.errors render view: "edit", model: [author:author] } } }

9.2 Scoped Services

By default, access to service methods is not synchronised, so nothing prevents concurrent execution of those met the service is a singleton and may be used concurrently, you should be very careful about storing state in a serv (and better) road and never store state in a service. You can change this behaviour by placing a service in a particular scope. The supported scopes are: prototype - A new service is created every time it is injected into another class request - A new service will be created per request flash - A new service will be created for the current and next request only flow - In web flows the service will exist for the scope of the flow

conversation - In web flows the service will exist for the scope of the conversation. ie a root flow and its session - A service is created for the scope of a user session singleton (default) - Only one instance of the service ever exists

If your service is flash , flow or conversation scoped it java.io.Serializable and can only be used in the context of a Web Flow

must

implem

292

To enable one of the scopes, add a static scope property to your class whose value is one of the above, for example
static scope = "flow"

9.3 Dependency Injection and Services


Dependency Injection Basics

A key aspect of Grails services is the ability to use Spring Framework's dependency injection features. Grails s injection by convention". In other words, you can use the property name representation of the class name of a ser inject them into controllers, tag libraries, and so on.

As an example, given a service called BookService, if you define a property called bookService in a contro
class BookController { def bookService }

In this case, the Spring container will automatically inject an instance of that service based on its configured sc injection is done by name. You can also specify the type as follows:
class AuthorService { BookService bookService }

NOTE: Normally the property name is generated by lower casing the first letter of the type. For exam instance of the BookService class would map to a property named bookService.

To be consistent with standard JavaBean conventions, if the first 2 letters of the class name are uppe the property name is the same as the class name. For example, the property name o JDBCHelperService class would be JDBCHelperService, not jDBCHelperServic jdbcHelperService. See section 8.8 of the JavaBean specification for more information on de-capitalization rules.

Dependency Injection and Services

You can inject services in other services with the same technique. If you had an AuthorService that BookService, declaring the AuthorService as follows would allow that:
class AuthorService { def bookService }

293

Dependency Injection and Domain Classes / Tag Libraries

You can even inject services into domain classes and tag libraries, which can aid in the development of rich domai
class Book { def bookService def buyBook() { bookService.buyBook(this) } }

9.4 Using Services from Java

One of the powerful things about services is that since they encapsulate re-usable logic, you can use them from ot Java classes. There are a couple of ways you can reuse a service from Java. The simplest way is to move your s within the grails-app/services directory. The reason this is important is that it is not possible to import c the default package (the package used when no package declaration is present). So for example the BookServi used from Java as it stands:
class BookService { void buyBook(Book book) { // logic } }

However, this can be rectified by placing this class in a package, by moving the class into a sub grails-app/services/bookstore and then modifying the package declaration:
package bookstore class BookService { void buyBook(Book book) { // logic } }

An alternative to packages is to instead have an interface within a package that the service implements:
package bookstore interface BookStore { void buyBook(Book book) }

And then the service:

294

class BookService implements bookstore.BookStore { void buyBook(Book b) { // logic } }

This latter technique is arguably cleaner, as the Java side only has a reference to the interface and not to the (although it's always a good idea to use packages). Either way, the goal of this exercise to enable Java to statically interface) to use, at compile time. Now that this is done you can create a Java class within the src/java directory and add a setter that uses the the bean in Spring:
// src/java/bookstore/BookConsumer.java package bookstore; public class BookConsumer { private BookStore store; public void setBookStore(BookStore storeInstance) { this.store = storeInstance; } }

Once this is done you can configure the Java class as a Spring bean in grails-app/conf/spring/resour information see the section on Grails and Spring):
<bean id="bookConsumer" class="bookstore.BookConsumer"> <property name="bookStore" ref="bookService" /> </bean>

or in grails-app/conf/spring/resources.groovy:
import bookstore.BookConsumer beans = { bookConsumer(BookConsumer) { bookStore = ref("bookService") } }

295

10 Testing

Automated testing is a key part of Grails. Hence, Grails provides many ways to making testing easier from low high level functional tests. This section details the different capabilities that Grails offers for testing.

Grails 1.3.x and below used the grails.test.GrailsUnitTestCase class hierarchy for testi JUnit 3 style. Grails 2.0.x and above deprecates these test harnesses in favour of mixins that can be a to a range of different kinds of tests (JUnit 3, Junit 4, Spock etc.) without subclassing

The first thing to be aware of is that all of the create-* and generate-* commands create unit or i automatically. For example if you run the create-controller command as follows:
grails create-controller com.acme.app.simple

Grails will create a controller at grails-app/controllers/com/acme/app/SimpleController. unit test at test/unit/com/acme/app/SimpleControllerTests.groovy. What Grails won't do ho logic inside the test! That is left up to you.

The default class name suffix is Tests but as of Grails 1.2.2, the suffix of Test is also supported.

Running Tests
Tests are run with the test-app command:
grails test-app

The command will produce output such as:


------------------------------------------------------Running Unit Tests Running test FooTests...FAILURE Unit Tests Completed in 464ms ------------------------------------------------------Tests failed: 0 errors, 1 failures

whilst showing the reason for each test failure.

You can force a clean before running tests by passing -clean to the test-app command.

Grails writes both plain text and HTML test reports to the target/test-reports directory, along with the The HTML reports are generally the best ones to look at. 296

Using Grails' interactive mode confers some distinct advantages when executing tests. First, the tests will execu on the second and subsequent runs. Second, a shortcut is available to open the HTML reports in your browser:
open test-report

You can also run your unit tests from within most IDEs.

Targeting Tests

You can selectively target the test(s) to be run in different ways. To run all tests for a controller named Simpl would run:
grails test-app SimpleController

This will run any tests for the class named SimpleController. Wildcards can be used...
grails test-app *Controller

This will test all classes ending in Controller. Package names can optionally be specified...
grails test-app some.org.*Controller

or to run all tests in a package...


grails test-app some.org.*

or to run all tests in a package including subpackages...


grails test-app some.org.**.*

You can also target particular test methods...


grails test-app SimpleController.testLogin

This will run the testLogin test in the SimpleController tests. You can specify as many patterns in comb
grails test-app some.org.* SimpleController.testLogin BookController

297

Targeting Test Types and/or Phases

In addition to targeting certain tests, you can also target test types and/or phases by using the phase:type synta

Grails organises tests by phase and by type. A test phase relates to the state of the Grails application the tests, and the type relates to the testing mechanism.

Grails comes with support for 4 test phases (unit, integration, functional and other) an test types for the unit and integration phases. These test types have the same name as the phas Testing plugins may provide new test phases or new test types for existing phases. Refer to the documentation. To execute the JUnit integration tests you can run:
grails test-app integration:integration

Both phase and type are optional. Their absence acts as a wildcard. The following command will run all te phase:
grails test-app unit:

The Grails Spock Plugin is one plugin that adds new test types to Grails. It adds a spock test type to the unit, functional phases. To run all spock tests in all phases you would run the following:
grails test-app :spock

To run the all of the spock tests in the functional phase you would run...
grails test-app functional:spock

More than one pattern can be specified...


grails test-app unit:spock integration:spock

Targeting Tests in Types and/or Phases


Test and type/phase targetting can be applied at the same time:
grails test-app integration: unit: some.org.**.*

298

This would run all tests in the integration and unit phases that are in the package some.org or a subpack

10.1 Unit Testing

Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code with surrounding infrastructure. Unit tests are typically run without the presence of physical resources that involve socket connections or files. This is to ensure they run as quick as possible since quick feedback is important.

The Test Mixins

Since Grails 2.0, a collection of unit testing mixins is provided by Grails that lets you enhance the behavior of a ty or Spock test. The following sections cover the usage of these mixins.

The previous JUnit 3-style GrailsUnitTestCase class hierarchy is still present in Grails for bac compatibility, but is now deprecated. The previous documentation on the subject can be found in the 1.3.x documentation You won't normally have to import any of the testing classes because Grails does that for you. But if you fi example can't find the classes, here they all are: grails.test.mixin.TestFor grails.test.mixin.TestMixin grails.test.mixin.Mock grails.test.mixin.support.GrailsUnitTestMixin grails.test.mixin.domain.DomainClassUnitTestMixin grails.test.mixin.services.ServiceUnitTestMixin grails.test.mixin.web.ControllerUnitTestMixin grails.test.mixin.web.FiltersUnitTestMixin grails.test.mixin.web.GroovyPageUnitTestMixin grails.test.mixin.web.UrlMappingsUnitTestMixin grails.test.mixin.webflow/WebFlowUnitTestMixin Note that you're only ever likely to use the first two explicitly. The rest are there for reference.

Test Mixin Basics

Most testing can be achieved via the TestFor annotation in combination with the Mock annotation for mocki example, to test a controller and associated domains you would define the following:
@TestFor(BookController) @Mock([Book, Author, BookService])

299

The TestFor annotation defines the class under test and will automatically create a field for the type of class un in the above case a "controller" field will be present, however if TestFor was defined for a service a "service" f and so on.

The Mock annotation creates mock version of any collaborators. There is an in-memory implementation of GOR most interactions with the GORM API. For those interactions that are not automatically mocked you can use th defining mocks and stubs programmatically. For example:
void testSearch() { def control = mockFor(SearchService) control.demand.searchWeb { String q -> ['mock results'] } control.demand.static.logResults { List results -> } controller.searchService = control.createMock() controller.search() assert controller.response.text.contains "Found 1 results" }

10.1.1 Unit Testing Controllers


The Basics

You use the grails.test.mixin.TestFor annotation to unit test controllers. Using TestFor in this m grails.test.mixin.web.ControllerUnitTestMixin and its associated API. For example:
import grails.test.mixin.TestFor @TestFor(SimpleController) class SimpleControllerTests { void testSomething() { } }

Adding the TestFor annotation to a controller causes a new controller field to be automatically created fo test.

The TestFor annotation will also automatically annotate any public methods starting with "tes JUnit 4's @Test annotation. If any of your test method don't start with "test" just add this manually To test the simplest "Hello World"-style example you can do the following:
// Test class class SimpleController { def hello() { render "hello" } }

300

void testHello() { controller.hello() assert response.text == 'hello' }

The response object is an instance of GrailsMockHttpServletResponse (from org.codehaus.groovy.grails.plugins.testing) which extends Spring's MockHttpServletR has a number of useful methods for inspecting the state of the response. For example to test a redirect you can use the redirectedUrl property:
// Test class class SimpleController { def index() { redirect action: 'hello' } }

void testIndex() { controller.index() assert response.redirectedUrl == '/simple/hello' }

Many actions make use of the parameter data associated with the request. For example, the 'sort', 'max', and 'offset common. Providing these in the test is as simple as adding appropriate values to a special params variable:
void testList() { params.sort = "name" params.max = 20 params.offset = 0 controller.list() }

You can even control what type of request the controller action sees by setting the method property of the mock
void testSave() { request.method = "POST" controller.save() }

This is particularly important if your actions do different things depending on the type of the request. Finally, yo as AJAX like so:

301

void testGetPage() { request.method = "POST" request.makeAjaxRequest() controller.getPage() }

You only need to do this though if the code under test uses the xhr property on the request.

Testing View Rendering

To test view rendering you can inspect the state of the controller's modelAndView property org.springframework.web.servlet.ModelAndView) or you can use the view and model prope mixin:
// Test class class SimpleController { def home() { render view: "homePage", model: [title: "Hello World"] } }

void testIndex() { controller.home() assert view == "/simple/homePage" assert model.title == "Hello World" }

Note that the view string is the absolute view path, so it starts with a '/' and will include path elements, such as after the action's controller.

Testing Template Rendering

Unlike view rendering, template rendering will actually attempt to write the template directly to the response ra ModelAndView hence it requires a different approach to testing. Consider the following controller action:
class SimpleController { def display() { render template:"snippet" } }

In this example the controller will look for a template in grails-app/views/simple/_snippet.gsp. follows:

302

void testDisplay() { controller.display() assert response.text == 'contents of template' }

However, you may not want to render the real template, but just test that is was rendered. In this case you can p Pages:
void testDisplay() { views['/simple/_snippet.gsp'] = 'mock contents' controller.display() assert response.text == 'mock contents' }

Testing Actions Which Return A Map

When a controller action returns a java.util.Map that Map may be inspected directly to assert that it contains
class SimpleController { def showBookDetails() { [title: 'The Nature Of Necessity', author: 'Alvin Plantinga'] } }

import grails.test.mixin.* @TestFor(SimpleController) class SimpleControllerTests { void testShowBookDetails() { def model = controller.showBookDetails() assert model.author == 'Alvin Plantinga' } }

Testing XML and JSON Responses

XML and JSON response are also written directly to the response. Grails' mocking capabilities provide some con XML and JSON response. For example consider the following action:
def renderXml() { render(contentType:"text/xml") { book(title:"Great") } }

This can be tested using the xml property of the response:

303

void testRenderXml() { controller.renderXml() assert "<book title='Great'/>" == response.text assert "Great" == response.xml.@title.text() }

The xml property is a parsed result from Groovy's XmlSlurper class which is very convenient for parsing XML. Testing JSON responses is pretty similar, instead you use the json property:
// controller action def renderJson() { render(contentType:"text/json") { book = "Great" } }

// test void testRenderJson() { controller.renderJson() assert '{"book":"Great"}' == response.text assert "Great" == response.json.book }

The json property is an instance of org.codehaus.groovy.grails.web.json.JSONElement structure that is useful for parsing JSON responses.

Testing XML and JSON Requests

Grails provides various convenient ways to automatically parse incoming XML and JSON packets. For ex incoming JSON or XML requests using Grails' data binding:
def consumeBook() { def b = new Book(params['book']) render b.title }

To test this Grails provides an easy way to specify an XML or JSON packet via the xml or json properties. Fo action can be tested by specifying a String containing the XML:
void testConsumeBookXml() { request.xml = '<book><title>The Shining</title></book>' controller.consumeBook() assert response.text == 'The Shining' }

Or alternatively a domain instance can be specified and it will be auto-converted into the appropriate XML reques 304

void testConsumeBookXml() { request.xml = new Book(title:"The Shining") controller.consumeBook() assert response.text == 'The Shining' }

The same can be done for JSON requests:


void testConsumeBookJson() { request.json = new Book(title:"The Shining") controller.consumeBook() assert response.text == 'The Shining' }

If you prefer not to use Grails' data binding but instead manually parse the incoming XML or JSON that can be te consider the controller action below:
def consume() { request.withFormat { xml { render request.XML.@title } json { render request.JSON.title } } }

To test the XML request you can specify the XML as a string:
void testConsumeXml() { request.xml = '<book title="The Stand" />' controller.consume() assert response.text == 'The Stand' }

And, of course, the same can be done for JSON:


void testConsumeJson() { request.json = '{title:"The Stand"}' controller.consume() assert response.text == 'The Stand' }

Testing Spring Beans

305

When using TestFor only a subset of the Spring beans available to a running Grails application are available. additional beans available you can do so with the defineBeans method of GrailsUnitTestMixin:
class SimpleController { SimpleService simpleService def hello() { render simpleService.sayHello() } }

void testBeanWiring() { defineBeans { simpleService(SimpleService) } controller.hello() assert response.text == "Hello World" }

The controller is auto-wired by Spring just like in a running Grails application. Autowiring even occurs if you i instances of the controller:
void testAutowiringViaNew() { defineBeans { simpleService(SimpleService) } def controller1 = new SimpleController() def controller2 = new SimpleController() assert controller1.simpleService != null assert controller2.simpleService != null }

Testing Mime Type Handling

You can test mime type handling and the withFormat method quite simply by setting the response's format a
// controller action def sayHello() { def data = [Hello:"World"] withFormat { xml { render data as XML } html data } }

306

// test void testSayHello() { response.format = 'xml' controller.sayHello() String expected = '<?xml version="1.0" encoding="UTF-8"?>' + '<map><entry key= "Hello">World</entry></map>' assert expected == response.text }

Testing Duplicate Form Submissions

Testing duplicate form submissions is a little bit more involved. For example if you have an action that handles a f
def handleForm() { withForm { render "Good" }.invalidToken { render "Bad" } }

you want to verify the logic that is executed on a good form submission and the logic that is executed on a d Testing the bad submission is simple. Just invoke the controller:
void testDuplicateFormSubmission() { controller.handleForm() assert "Bad" == response.text }

Testing the successful submission requires providing an appropriate SynchronizerToken:


import org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerToken ... void testValidFormSubmission() { def token = SynchronizerToken.store(session) params[SynchronizerToken.KEY] = token.currentToken.toString() controller.handleForm() assert "Good" == response.text }

If you test both the valid and the invalid request in the same test be sure to reset the response between executions o
controller.handleForm() // first execution response.reset() controller.handleForm() // second execution

307

Testing File Upload

You use the GrailsMockMultipartFile class to test file uploads. For example consider the following contr
def uploadFile() { MultipartFile file = request.getFile("myFile") file.transferTo(new File("/local/disk/myFile")) }

To test this action you can register a GrailsMockMultipartFile with the request:
void testFileUpload() { final file = new GrailsMockMultipartFile("myFile", "foo".bytes) request.addFile(file) controller.uploadFile() assert file.targetFileLocation.path == "/local/disk/myFile" }

The GrailsMockMultipartFile constructor arguments are the name and contents of the file. It has a moc the transferTo method that simply records the targetFileLocation and doesn't write to disk.

Testing Command Objects

Special support exists for testing command object handling with the mockCommandObject method. For e following action:
def handleCommand(SimpleCommand simple) { if (simple.hasErrors()) { render "Bad" } else { render "Good" } }

To test this you mock the command object, populate it and then validate it as follows:
void testInvalidCommand() { def cmd = mockCommandObject(SimpleCommand) cmd.name = '' // doesn't allow blank names cmd.validate() controller.handleCommand(cmd) assert response.text == 'Bad' }

Testing Calling Tag Libraries

308

You can test calling tag libraries using ControllerUnitTestMixin, although the mechanism for testing from tag to tag. For example to test a call to the message tag, add a message to the messageSource. Co action:
def showMessage() { render g.message(code: "foo.bar") }

This can be tested as follows:


void testRenderBasicTemplateWithTags() { messageSource.addMessage("foo.bar", request.locale, "Hello World") controller.showMessage() assert response.text == "Hello World" }

10.1.2 Unit Testing Tag Libraries


The Basics

Tag libraries and GSP pages can be tested with the grails.test.mixin.web.GroovyPageUnitTestM the mixin declare which tag library is under test with the TestFor annotation:
@TestFor(SimpleTagLib) class SimpleTagLibTests { }

Note that if you are testing invocation of a custom tag from a controller you can combine the ControllerUn the GroovyPageUnitTestMixin using the Mock annotation:
@TestFor(SimpleController) @Mock(SimpleTagLib) class GroovyPageUnitTestMixinTests { }

Testing Custom Tags

The core Grails tags don't need to be enabled during testing, however custom tag libraries do. The GroovyPag class provides a mockTagLib() method that you can use to mock a custom tag library. For example consid library:

309

class SimpleTagLib { static namespace = 's' def hello = { attrs, body -> out << "Hello ${attrs.name ?: 'World'}" } def bye = { attrs, body -> out << "Bye ${attrs.author.name ?: 'World'}" } }

You can test this tag library by using TestFor and supplying the name of the tag library:
@TestFor(SimpleTagLib) class SimpleTagLibTests { void testHelloTag() { assert applyTemplate('<s:hello />') == 'Hello World' assert applyTemplate('<s:hello name="Fred" />') == 'Hello Fred' assert applyTemplate('<s:bye author="${author}" />', [author: new Author(name: 'Bye Fred' } }

Alternatively, you can use the TestMixin annotation and mock multiple tag libraries using the mockTagLib(
@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin) class MultipleTagLibraryTests { @Test void testMuliple() { mockTagLib(FirstTagLib) mockTagLib(SecondTagLib) } }

The GroovyPageUnitTestMixin provides convenience methods for asserting that the template output e expected value.
@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin) class MultipleTagLibraryTests { @Test void testMuliple() { mockTagLib(FirstTagLib) mockTagLib(SecondTagLib) assertOutputEquals ('Hello World', '<s:hello />') assertOutputMatches (/.*Fred.*/, '<s:hello name="Fred" />') } }

Testing View and Template Rendering

310

You can test rendering of views and templates in grails-app/views via the render(Map) m GroovyPageUnitTestMixin :
def result = render(template: "/simple/hello") assert result == "Hello World"

This will attempt to render a template found at the location grails-app/views/simple/_hello.g template depends on any custom tag libraries you need to call mockTagLib as described in the previous section.

10.1.3 Unit Testing Domains


Overview

The mocking support described here is best used when testing non-domain artifacts that use domain c to let you focus on testing the artifact without needing a database. But when testing persistence it's use integration tests which configure Hibernate and use a database.

Domain class interaction can be tested without involving a database connection using DomainClassUni implementation mimics the behavior of GORM against an in-memory ConcurrentHashMap implementatio limitations compared to a real GORM implementation. The following features of GORM for Hibernate can onl integration test: String-based HQL queries composite identifiers dirty checking methods any direct interaction with Hibernate

However a large, commonly-used portion of the GORM API can be mocked using DomainClassUnitTestMi Simple persistence methods like save(), delete() etc. Dynamic Finders Named Queries Query-by-example GORM Events

If something isn't supported then GrailsUnitTestMixin's mockFor method can come in handy to moc Alternatively you can write an integration test which bootstraps the complete Grails environment at a cost of test e

The Basics
DomainClassUnitTestMixin is typically used in combination with testing either a controller, service or domain is a mock collaborator defined by the Mock annotation:

311

import grails.test.mixin.* @TestFor(SimpleController) @Mock(Simple) class SimpleControllerTests { }

The example above tests the SimpleController class and mocks the behavior of the Simple domain class consider a typical scaffolded save controller action:
class BookController { def save() { def book = new Book(params) if (book.save(flush: true)) { flash.message = message( code: ' default.created.message', args: [message(code: 'book.label', default: 'Book'), book.id])}" redirect(action: " show", id: book.id) } else { render(view: " create", model: [bookInstance: book]) } } }

Tests for this action can be written as follows:


import grails.test.mixin.* @TestFor(BookController) @Mock(Book) class BookControllerTests { void testSaveInvalidBook() { controller.save() assert model.bookInstance != null assert view == '/book/create' } void testSaveValidBook() { params.title = "The Stand" params.pages = "500" controller.save() assert response.redirectedUrl == '/book/show/1' assert flash.message != null assert Book.count() == 1 } }

Mock annotation also supports a list of mock collaborators if you have more than one domain to mock:

312

@TestFor(BookController) @Mock([Book, Author]) class BookControllerTests { }

Alternatively you can also use the DomainClassUnitTestMixin directly with the TestMixin annotation:
import grails.test.mixin.domain.DomainClassUnitTestMixin @TestFor(BookController) @TestMixin(DomainClassUnitTestMixin) class BookControllerTests { }

And then call the mockDomain method to mock domains during your test:
void testSave() { mockDomain(Author) mockDomain(Book) }

The mockDomain method also includes an additional parameter that lets you pass a Map of Maps to configur useful for fixture-like data:
void testSave() { mockDomain(Book, [ [title: "The Stand", pages: 1000], [title: "The Shining", pages: 400], [title: "Along Came a Spider", pages: 300] ]) }

Testing Constraints

Your constraints contain logic and that logic is highly susceptible to bugs - the kind of bugs that can be t (particularly as by default save() doesn't throw an exception when it fails). If your answer is that it's too hard longer an excuse. Enter the mockForConstraintsTests() method.

This method is like a much reduced version of the mockDomain() method that simply adds a validate( domain class. All you have to do is mock the class, create an instance with populated data, and then call valida access the errors property to determine if validation failed. So if all we are doing is mocking the validate optional list of test instances? That is so that we can test the unique constraint as you will soon see. So, suppose we have a simple domain class:

313

class Book { String title String author static constraints = { title blank: false, unique: true author blank: false, minSize: 5 } }

Don't worry about whether the constraints are sensible (they're not!), they are for demonstration only. To test the do the following:
@TestFor(Book) class BookTests { void testConstraints() { def existingBook = new Book( title: "Misery", author: "Stephen King") mockForConstraintsTests(Book, [existingBook]) // validation should fail if both properties are null def book = new Book() assert !book.validate() assert "nullable" == book.errors["title"] assert "nullable" == book.errors["author"] // So let's demonstrate the unique and minSize constraints book = new Book(title: "Misery", author: "JK") assert !book.validate() assert "unique" == book.errors["title"] assert "minSize" == book.errors["author"] // Validation should pass! book = new Book(title: "The Shining", author: "Stephen King") assert book.validate() } }

You can probably look at that code and work out what's happening without any further explanation. The one thi the way the errors property is used. First, is a real Spring Errors instance, so you can access all the proper would normally expect. Second, this particular Errors object also has map/property access as shown. Simply sp field you are interested in and the map/property access will return the name of the constraint that was violate constraint name, not the message code (as you might expect).

That's it for testing constraints. One final thing we would like to say is that testing the constraints in this way catc typos in the "constraints" property name! It is currently one of the hardest bugs to track down normally, and ye constraints will highlight the problem straight away.

10.1.4 Unit Testing Filters

Unit testing filters is typically a matter of testing a controller where a filter is a mock collaborator. For example c filters class:

314

class CancellingFilters { def filters = { all(controller:"simple", action:"list") { before = { redirect(controller: "book") return false } } } }

This filter interceptors the list action of the simple controller and redirects to the book controller. To test t with a test that targets the SimpleController class and add the CancellingFilters as a mock collabora
@TestFor(SimpleController) @Mock(CancellingFilters) class SimpleControllerTests { }

You can then implement a test that uses the withFilters method to wrap the call to an action in filter executio
void testInvocationOfListActionIsFiltered() { withFilters(action:"list") { controller.list() } assert response.redirectedUrl == '/book' }

Note that the action parameter is required because it is unknown what the action to invoke is until the action is controller parameter is optional and taken from the controller under test. If it is another controller you are specify it:
withFilters(controller:"book",action:"list") { controller.list() }

10.1.5 Unit Testing URL Mappings


The Basics

Testing URL mappings can be done with the TestFor annotation testing a particular URL mappings class. Fo default URL mappings you can do the following:

315

import org.example.AuthorController import org.example.SimpleController @TestFor(UrlMappings) @Mock([AuthorController, SimpleController]) class UrlMappingsTests { }

As you can see, any controller that is the target of a URL mapping that you're testing must be added to the @Mock

Note that since the default UrlMappings class is in the default package your test must also be default package

With that done there are a number of useful methods that are defin grails.test.mixin.web.UrlMappingsUnitTestMixin for testing URL mappings. These include:

assertForwardUrlMapping - Asserts a URL mapping is forwarded for the given controller class (no need to be defined as a mock collaborate for this to work)

assertReverseUrlMapping - Asserts that the given URL is produced when reverse mapping a link to a action assertUrlMapping - Asserts a URL mapping is valid for the assertForwardUrlMapping and assertReverseUrlMapping assertions given URL.

This

Asserting Forward URL Mappings

You use assertForwardUrlMapping to assert that a given URL maps to a given controller. For example, c URL mappings:
static mappings = { "/action1"(controller: "simple", action: "action1") "/action2"(controller: "simple", action: "action2") }

The following test can be written to assert these URL mappings:


void testUrlMappings() { assertForwardUrlMapping("/action1", controller: 'simple', action: "action1") assertForwardUrlMapping("/action2", controller: 'simple', action: "action2") shouldFail { assertForwardUrlMapping("/action2", controller: 'simple', action: "action1") } }

316

Assert Reverse URL Mappings

You use assertReverseUrlMapping to check that correct links are produced for your URL mapping when u GSP views. An example test is largely identical to the previous listing except you use assertReverseUrlM assertForwardUrlMapping. Note that you can combine these 2 assertions with assertUrlMapping.

Simulating Controller Mapping

In addition to the assertions to check the validity of URL mappings you can also simulate mapping to a cont UrlMappings as a mock collaborator and the mapURI method. For example:
@TestFor(SimpleController) @Mock(UrlMappings) class SimpleControllerTests { void testControllerMapping() { SimpleController controller = mapURI('/simple/list') assert controller != null def model = controller.list() assert model != null } }

10.1.6 Mocking Collaborators

Beyond the specific targeted mocking APIs there is also an all-purpose mockFor() method that is availa TestFor annotation. The signature of mockFor is:
mockFor(class, loose = false)

This is general-purpose mocking that lets you set up either strict or loose demands on a class.

This method is surprisingly intuitive to use. By default it will create a strict mock control object (one for whic methods are called is important) that you can use to specify demands:
def strictControl = mockFor(MyService) strictControl.demand.someMethod(0..2) { String arg1, int arg2 -> } strictControl.demand.static.aStaticMethod {-> }

Notice that you can mock static as well as instance methods by using the "static" property. You then specify the n mock, with an optional range argument. This range determines how many times you expect the method to be call of invocations falls outside of that range (either too few or too many) then an assertion error will be thrown. If no default of "1..1" is assumed, i.e. that the method must be called exactly once.

The last part of a demand is a closure representing the implementation of the mock method. The closure argum number and types of the mocked method, but otherwise you are free to add whatever you want in the body.

317

Call mockControl.createMock() to get an actual mock instance of the class that you are mocking. You times to create as many mock instances as you need. And once you have executed the test method, call mockCo to check that the expected methods were called. Lastly, the call:
def looseControl = mockFor(MyService, true)

will create a mock control object that has only loose expectations, i.e. the order that methods are invoked does not

10.1.7 Mocking Codecs

The GrailsUnitTestMixin provides a mockCodec method for mocking custom codecs which may be inv is running.
mockCodec(MyCustomCodec)

Failing to mock a codec which is invoked while a unit test is running may result in a MissingMethodException.

10.2 Integration Testing

Integration tests differ from unit tests in that you have full access to the Grails environment within the test. Grai H2 database for integration tests and clears out all the data from the database between tests.

One thing to bear in mind is that logging is enabled for your application classes, but it is different from logging in something like this:
class MyServiceTests extends GroovyTestCase { void testSomething() { log.info "Starting tests" } }

the "starting tests" message is logged using a different system than the one used by the application. The log pro above is an instance of java.util.logging.Logger (inherited from the base class, not injected by Grails the same methods as the log property injected into your application artifacts. For example, it doesn't have de methods, and the equivalent of warn() is in fact warning().

Transactions

Integration tests run inside a database transaction by default, which is rolled back at the end of the each test. This m during a test is not persisted to the database. Add a transactional property to your test class to check transac

318

class MyServiceTests extends GroovyTestCase { static transactional = false void testMyTransactionalServiceMethod() { } }

Be sure to remove any persisted data from a non-transactional test, for example in the tearDown method, so the with standard transactional tests that expect a clean database.

Testing Controllers
To test controllers you first have to understand the Spring Mock Library.

Grails automatically configures each test with a MockHttpServletRequest, MockHttpServletResponse, and Mock can use in your tests. For example consider the following controller:
class FooController { def text() { render "bar" } def someRedirect() { redirect(action:"bar") } }

The tests for this would be:


class FooControllerTests extends GroovyTestCase { void testText() { def fc = new FooController() fc.text() assertEquals "bar", fc.response.contentAsString } void testSomeRedirect() { def fc = new FooController() fc.someRedirect() assertEquals "/foo/bar", fc.response.redirectedUrl } }

In the above case response is an instance of MockHttpServletResponse which we can use to obtain t with contentAsString (when writing to the response) or the redirected URL. These mocked versions of completely mutable (unlike the real versions) and hence you can set properties on the request such as the contex

Grails does not invoke interceptors or servlet filters when calling actions during integration testing. You should filters in isolation, using functional testing if necessary.

Testing Controllers with Services

If your controller references a service (or other Spring beans), you have to explicitly initialise the service from you 319

Given a controller using a service:


class FilmStarsController { def popularityService def update() { // do something with popularityService } }

The test for this would be:


class FilmStarsTests extends GroovyTestCase { def popularityService void testInjectedServiceInController () { def fsc = new FilmStarsController() fsc.popularityService = popularityService fsc.update() } }

Testing Controller Command Objects

With command objects you just supply parameters to the request and it will automatically do the command objec you call your action with no parameters: Given a controller using a command object:
class AuthenticationController { def signup(SignupForm form) { } }

You can then test it like this:


def controller = new AuthenticationController() controller.params.login = "marcpalmer" controller.params.password = "secret" controller.params.passwordConfirm = "secret" controller.signup()

Grails auto-magically sees your call to signup() as a call to the action and populates the command object from parameters. During controller testing, the params are mutable with a mocked request supplied by Grails.

Testing Controllers and the render Method

The render method lets you render a custom view at any point within the body of an action. For instance, consider

320

def save() { def book = Book(params) if (book.save()) { // handle } else { render(view:"create", model:[book:book]) } }

In the above example the result of the model of the action is not available as the return value, but instead modelAndView property of the controller. The modelAndView property is an instance of Spring MVC's Mod you can use it to the test the result of an action:
def bookController = new BookController() bookController.save() def model = bookController.modelAndView.model.book

Simulating Request Data

You can use the Spring MockHttpServletRequest to test an action that requires request data, for example a RE example consider this action which performs data binding from an incoming request:
def create() { [book: new Book(params.book)] }

To simulate the 'book' parameter as an XML request you could do something like the following:
void testCreateWithXML() { def controller = new BookController() controller.request.contentType = 'text/xml' controller.request.content = '''\ <?xml version= "1.0" encoding="ISO-8859-1"?> <book> <title>The Stand</title> </book> '''.stripIndent().getBytes() // note we need the bytes def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }

The same can be achieved with a JSON request:

321

void testCreateWithJSON() { def controller = new BookController() controller.request.contentType = "text/json" controller.request.content = '{ "id":1,"class":"Book","title":"The Stand"}'.getBytes() def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }

With JSON don't forget the class property to specify the name the target type to bind to. In XML implicit within the name of the <book> node, but this property is required as part of the JSON packe

For more information on the subject of REST web services see the section on REST.

Testing Web Flows

Testing Web Flows requires a special test harness called grails.test.WebFlowTestCase which subclasse AbstractFlowExecutionTests class.

Subclasses of WebFlowTestCase must be integration tests

For example given this simple flow:


class ExampleController { def exampleFlow() { start { on( "go") { flow.hello = "world" }.to "next" } next { on( "back").to "start" on( "go").to "subber" } subber { subflow(action: "sub") on( "end").to("end") } end() } def subFlow() { subSubflowState { subflow(controller: "other", action: "otherSub") on( "next").to("next") } } }

You need to tell the test harness what to use for the "flow definition". This is done via overriding the abstract get 322

import grails.test.WebFlowTestCase class ExampleFlowTests extends WebFlowTestCase { def getFlow() { new ExampleController().exampleFlow } }

You can specify the flow id by overriding the getFlowId method, otherwise the default is test:
import grails.test.WebFlowTestCase class ExampleFlowTests extends WebFlowTestCase { String getFlowId() { "example" } }

If the flow under test calls any subflows, these (or mocks) must be registered before the calling the flow:
protected void setUp() { super.setUp() registerFlow("other/otherSub") { // register a simplified mock start { on( "next").to("end") } end() } // register the original subflow registerFlow("example/sub", new ExampleController().subFlow) }

Then you kick off the flow with the startFlow method:
void testExampleFlow() { def viewSelection = startFlow() }

Use the signalEvent method to trigger an event:


void testExampleFlow() { signalEvent("go") assert "next" == flowExecution.activeSession.state.id assert "world" == flowScope.hello }

Here we have signaled to the flow to execute the event "go" which causes a transition to the "next" state. In the action placed a hello variable into the flow scope.

Testing Tag Libraries

323

Testing tag libraries is simple because when a tag is invoked as a method it returns its result as a st StreamCharBuffer but this class implements all of the methods of String). So for example if you have a ta
class FooTagLib { def bar = { attrs, body -> out << "<p>Hello World!</p>" } def bodyTag out out out } } = { attrs, body -> << "<${attrs.name}>" << body() << "</${attrs.name}>"

The tests would look like:


class FooTagLibTests extends GroovyTestCase { void testBarTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bar(null, null).toString() } void testBodyTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bodyTag(name: "p") { "Hello World!" }.toString() } }

Notice that for the second example, testBodyTag, we pass a block that returns the body of the tag. T representing the body as a String.

Testing Tag Libraries with GroovyPagesTestCase

In addition to doing simple testing of tag libraries like in the above examples, you ca grails.test.GroovyPagesTestCase class to test tag libraries with integration tests.

The GroovyPagesTestCase class is a subclass of the standard GroovyTestCase class and adds utility m output of GSP rendering.

GroovyPagesTestCase can only be used in an integration test.

For example, consider this date formatting tag library:


import java.text.SimpleDateFormat class FormatTagLib { def dateFormat = { attrs, body -> out << new SimpleDateFormat(attrs.format) << attrs.date } }

324

This can be easily tested as follows:


class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format= "dd-MM-yyyy" date="${myDate}" />' def testDate = // create the date assertOutputEquals('01-01-2008', template, [myDate:testDate]) } }

You can also obtain the result of a GSP using the applyTemplate method of the GroovyPagesTestCase c
class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format= "dd-MM-yyyy" date="${myDate}" />' def testDate = // create the date def result = applyTemplate(template, [myDate:testDate]) assertEquals '01-01-2008', result } }

Testing Domain Classes

Testing domain classes is typically a simple matter of using the GORM API, but there are a few things to be aw testing queries you often need to "flush" to ensure the correct state has been persisted to the database. For examp example:
void testQuery() { def books = [ new Book(title: "The Stand"), new Book(title: "The Shining")] books*.save() assertEquals 2, Book.list().size() }

This test will fail because calling save does not actually persist the Book instances when called. Calling sa Hibernate that at some point in the future these instances should be persisted. To commit changes immediately you
void testQuery() { def books = [ new Book(title: "The Stand"), new Book(title: "The Shining")] books*.save(flush: true) assertEquals 2, Book.list().size() }

325

In this case since we're passing the argument flush with a value of true the updates will be persisted immediat available to the query later on.

10.3 Functional Testing

Functional tests involve making HTTP requests against the running application and verifying the resultant behav ship with any support for writing functional tests directly, but there are several plugins available for this. Canoo Webtest - http://grails.org/plugin/webtest G-Func - http://grails.org/plugin/functional-test Geb - http://grails.org/plugin/geb Selenium-RC - http://grails.org/plugin/selenium-rc WebDriver - http://grails.org/plugin/webdriver Consult the documentation for each plugin for its capabilities.

Common Options
There are options that are common to all plugins that control how the Grails application is launched, if at all.
inline

The -inline option specifies that the grails application should be started inline (i.e. like run-app). This option is implicitly set unless the baseUrl or war options are set
war

The -war option specifies that the grails application should be packaged as a war and started. This is useful as it in a production-like state, but it has a longer startup time than the -inline option. It also runs the war in a forke you cannot access any internal application objects.
grails test-app functional: -war

Note that the same build/config options for the run-war command apply to functional testing against the WAR.
https

The -https option results in the application being able to receive https requests as well as http requests. It is com -inline and -war options.
grails test-app functional: -https

Note that this does not change the test base url to be https, it will still be http unless the -httpsBaseUrl option
httpsBaseUrl

The -httpsBaseUrl causes the implicit base url to be used for tests to be a https url. 326

grails test-app functional: -httpsBaseUrl

This option is ignored if the -baseUrl option is specified.


baseUrl

The baseUrl option allows the base url for tests to be specified.
grails test-app functional: -baseUrl=http://mycompany.com/grailsapp

This option will prevent the local grails application being started unless -inline or -war are given as well. To but still test against the local Grails application you must specify one of either the -inline or -war options.

327

11 Internationalization

Grails supports Internationalization (i18n) out of the box by leveraging the underlying Spring MVC international Grails you are able to customize the text that appears in a view based on the user's Locale. To quote the javadoc fo

A Locale object represents a specific geographical, political, or cultural region. An operation that requir perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For examp number is a locale-sensitive operation--the number should be formatted according to the customs/conventio native country, region, or culture.

A Locale is made up of a language code and a country code. For example "en_US" is the code for US english, w code for British English.

11.1 Understanding Message Bundles

Now that you have an idea of locales, to use them in Grails you create message bundle file containing the differe wish to render. Message bundles in Grails are located inside the grails-app/i18n directory and are simple Ja

Each bundle starts with the name messages by convention and ends with the locale. Grails ships with several m whole range of languages within the grails-app/i18n directory. For example: messages.properties messages_da.properties messages_de.properties messages_es.properties messages_fr.properties ...

By default Grails looks in messages.properties for messages unless the user has specified a locale. You message bundle by simply creating a new properties file that ends with the locale you are interes messages_en_GB.properties for British English.

11.2 Changing Locales

By default the user locale is detected from the incoming Accept-Language header. However, you can provid to switch locales by simply passing a parameter called lang to Grails as a request parameter:
/book/list?lang=es

Grails will automatically switch the user's locale and store it in a cookie so subsequent requests will have the new

11.3 Reading Messages


Reading Messages in the View
The most common place that you need messages is inside the view. Use the message tag for this: 328

<g:message code="my.localized.content" />

As long as you have a key in your messages.properties (with appropriate locale suffix) such as the one b look up the message:
my.localized.content=Hola, Me llamo John. Hoy es domingo.

Messages can also include arguments, for example:


<g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />

The message declaration specifies positional parameters which are dynamically specified:
my.localized.content=Hola, Me llamo {0}. Hoy es {1}.

Reading Messages in Controllers and Tag Libraries


It's simple to read messages in a controller since you can invoke tags as methods:
def show() { def msg = message(code: "my.localized.content", args: ['Juan', 'lunes']) }

The same technique can be used in tag libraries, but if your tag library uses a custom namespace then you must pre
def myTag = { attrs, body -> def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes']) }

11.4 Scaffolding and i18n

Grails scaffolding templates for controllers and views are fully i18n-aware. The GSPs use the message tag for la controller flash messages use i18n to resolve locale-specific messages.

329

12 Security

Grails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secur to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinnin Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can mistakes and make writing secure applications easier to write.

What Grails Automatically Does


Grails has a few built in safety mechanisms by default.

1. All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injecti 2. The default scaffolding templates HTML escape all data fields when displayed

3. Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping m code injection

4. Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript and URLs to pre here.

12.1 Securing Against Attacks


SQL injection

Hibernate, which is the technology underlying GORM domain classes, automatically escapes data when committi is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameter the following is vulnerable to HQL injection attacks:
def vulnerable() { def books = Book.find("from Book as b where b.title ='" + params.title + "'") }

or the analagous call using a GString:


def vulnerable() { def books = Book.find("from Book as b where b.title ='${params.title}'") }

Do not do this. Use named or positional parameters instead to pass in parameters:


def safe() { def books = Book.find("from Book as b where b.title = ?", [params.title]) }

or

330

def safe() { def books = Book.find("from Book as b where b.title = :title", [title: params.title]) }

Phishing

This really a public relations issue in terms of avoiding hijacking of your branding and a declared communica customers. Customers need to know how to identify valid emails.

XSS - cross-site scripting injection

It is important that your application verifies as much as possible that incoming requests were originated from you from another site. Ticketing and page flow systems can help this and Grails' support for Spring Web Flow include default.

It is also important to ensure that all data values rendered into views are escaped correctly. For example when re XHTML you must call encodeAsHTML on every object to ensure that people cannot maliciously inject JavaScrip data or tags viewed by others. Grails supplies several Dynamic Encoding Methods for this purpose and if your ou is not supported you can easily write your own codec.

You must also avoid the use of request parameters or data fields for determining the next URL to redirect the successURL parameter for example to determine where to redirect a user to after a successful login, attackers c procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowi then exploit the logged-in account on the site.

Cross-site request forgery

CSRF involves unauthorized commands being transmitted from a user that a website trusts. A typical examp website embedding a link to perform an action on your website if the user is still authenticated.

The best way to decrease risk against these types of attacks is to use the useToken attribute on your forms. Se Form Submissions for more information on how to use it. An additional measure would be to not use remember-m

HTML/URL injection

This is where bad data is supplied such that when it is later used to create a link in a page, clicking it will no behaviour, and may redirect to another site or alter request parameters.

HTML/URL injection is easily handled with the codecs supplied by Grails, and the tag libraries supplied encodeAsURL where appropriate. If you create your own tags that generate URLs you will need to be mindful of d

Denial of service

Load balancers and other appliances are more likely to be useful here, but there are also issues relating to e example where a link is created by an attacker to set the maximum value of a result set so that a query could exce of the server or slow the system down. The solution here is to always sanitize request parameters before pass finders or other GORM query methods:

331

def safeMax = Math.max(params.max?.toInteger(), 100) // limit to 100 results return Book.list(max:safeMax)

Guessable IDs

Many applications use the last part of the URL as an "id" of some object to retrieve from GORM or elsewhere. Esp GORM these are easily guessable as they are typically sequential integers.

Therefore you must assert that the requesting user is allowed to view the object with the requested id before retu the user. Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of You must assume that every unprotected URL is publicly accessible one way or another.

12.2 Encoding and Decoding Objects

Grails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.

Codec Classes

A Grails codec class is one that may contain an encode closure, a decode closure or both. When a Grails applicatio framework dynamically loads codecs from the grails-app/utils/ directory.

The framework looks under grails-app/utils/ for class names that end with the convention Codec. Fo standard codecs that ships with Grails is HTMLCodec. If a codec contains an encode closure Grails will create a dynamic encode method and add that method to the name representing the codec that defined the encode closure. For example, the HTMLCodec class defines an Grails attaches it with the name encodeAsHTML.

The HTMLCodec and URLCodec classes also define a decode closure, so Grails attaches those with the name decodeURL respectively. Dynamic codec methods may be invoked from anywhere in a Grails application. For case where a report contains a property called 'description' which may contain special characters that must be esc in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynam shown below:
${report.description.encodeAsHTML()}

Decoding is performed using value.decodeHTML() syntax.

Standard Codecs
HTMLCodec

This codec performs HTML escaping and unescaping, so that values can be rendered safely in an HTML page HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn' safely within an HTML page because the > will look like it closes a tag, which is especially bad if you rende attribute, such as the value attribute of an input field. 332

Example of usage:
<input name="comment.message" value="${comment.message.encodeAsHTML()}"/>

Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double on attribute values to avoid text with apostrophes affecting your page. URLCodec

URL encoding is required when creating URLs in links or form actions, or any time data is used to create a UR characters from getting into the URL and changing its meaning, for example "Apple & Blackberry" is not goi parameter in a GET request as the ampersand will break parameter parsing. Example of usage:
<a href="/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}"> Repeat last search </a>

Base64Codec Performs Base64 encode/decode functions. Example of usage:


Your registration code is: ${user.registrationCode.encodeAsBase64()}

JavaScriptCodec Escapes Strings so they can be used as valid JavaScript strings. For example:
Element.update('${elementId}', '${render(template: "/common/message").encodeAsJavaScript()}')

HexCodec Encodes byte arrays or lists of integers to lowercase hexadecimal strings, and can decode hexadecimal strings example:
Selected colour: #${[255,127,255].encodeAsHex()}

MD5Codec

Uses the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system enco hexadecimal string. Example of usage:

333

Your API Key: ${user.uniqueID.encodeAsMD5()}

MD5BytesCodec

Uses the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encod Example of usage:
byte[] passwordHash = params.password.encodeAsMD5Bytes()

SHA1Codec

Uses the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system enco hexadecimal string. Example of usage:
Your API Key: ${user.uniqueID.encodeAsSHA1()}

SHA1BytesCodec

Uses the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encod Example of usage:
byte[] passwordHash = params.password.encodeAsSHA1Bytes()

SHA256Codec Uses the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default sy lowercase hexadecimal string. Example of usage:
Your API Key: ${user.uniqueID.encodeAsSHA256()}

SHA256BytesCodec

Uses the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system array. Example of usage:
byte[] passwordHash = params.password.encodeAsSHA256Bytes()

Custom Codecs

334

Applications may define their own codecs and Grails will load them along with the standard codecs. A custom defined in the grails-app/utils/ directory and the class name must end with Codec. The codec may encode closure, a static decode closure or both. The closure must accept a single argument which will dynamic method was invoked on. For Example:
class PigLatinCodec { static encode = { str -> // convert the string to pig latin and return the result } }

With the above codec in place an application could do something like this:
${lastName.encodeAsPigLatin()}

12.3 Authentication

Grails has no default mechanism for authentication as it is possible to implement authentication in many differen easy to implement a simple authentication mechanism using either interceptors or filters. This is sufficient for sim highly preferable to use an established security framework, for example by using the Spring Security or the Shiro p

Filters let you apply authentication across all controllers or across a URI space. For example you can create a n class called grails-app/conf/SecurityFilters.groovy by running:
grails create-filters security

and implement your interception logic there:


class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if (!session.user && actionName != "login") { redirect(controller: "user", action: "login") return false } } } } }

Here the loginCheck filter intercepts execution before all actions except login are executed, and if there is then redirect to the login action. The login action itself is simple too:

335

def login() { if (request.get) { return // render the login view } def u = User.findByLogin(params.login) if (u) { if (u.password == params.password) { session.user = u redirect(action: "home") } else { render(view: "login", model: [message: "Password incorrect"]) } } else { render(view: "login", model: [message: "User not found"]) } }

12.4 Security Plugins

If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you s one of the available security plugins.

12.4.1 Spring Security

The Spring Security plugins are built on the Spring Security project which provides a flexible, extensible frame sorts of authentication and authorization schemes. The plugins are modular so you can install just the functiona your application. The Spring Security plugins are the official security plugins for Grails and are actively maintaine

There is a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic au secondary dependent plugins provide alternate functionality such as OpenID authentication, ACL support, sing CAS, LDAP authentication, Kerberos authentication, and a plugin providing user interface extensions and security See the Core plugin page for basic information and the user guide for detailed information.

12.4.2 Shiro

Shiro is a Java POJO-oriented security framework that provides a default domain model that models real permissions. With Shiro you extend a controller base class called called JsecAuthBase in each controller you w provide an accessControl block to setup the roles. An example below:
class ExampleController extends JsecAuthBase { static accessControl = { // All actions require the 'Observer' role. role(name: 'Observer') // The 'edit' action requires the 'Administrator' role. role(name: 'Administrator', action: 'edit') // Alternatively, several actions can be specified. role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) } }

For more information on the Shiro plugin refer to the documentation.

336

13 Plugins

Grails is first and foremost a web application framework, but it is also a platform. By exposing a number of ext you extend anything from the command line interface to the runtime configuration engine, Grails can be customis needs. To hook into this platform, all you need to do is create a plugin.

Extending the platform may sound complicated, but plugins can range from trivially simple to incredibly powerfu build a Grails application, you'll know how to create a plugin for sharing a data model or some static resources.

13.1 Creating and Installing Plugins


Creating Plugins
Creating a Grails plugin is a simple matter of running the command:
grails create-plugin [PLUGIN NAME]

This will create a plugin project for the name you specify. For example running grails create-plugin ex a new plugin project called example.

The structure of a Grails plugin is very nearly the same as a Grails application project's except that in the root o you will find a plugin Groovy file called the "plugin descriptor".

The only plugins included in a new plugin project are Tomcat and Release. Hibernate is not inclu default. Being a regular Grails project has a number of benefits in that you can immediately test your plugin by running:
grails run-app

Plugin projects don't provide an index.gsp by default since most plugins don't need it. So, if you try t the plugin running in a browser right after creating it, you will receive a page not found error. Y easily create a grails-app/views/index.gsp for your plugin if you'd like.

The plugin descriptor name ends with the convention GrailsPlugin and is found in the root of the plugin proje
class ExampleGrailsPlugin { def version = "0.1" }

All plugins must have this class in the root of their directory structure. The plugin class defines the version of metadata, and optionally various hooks into plugin extension points (covered shortly).

337

You can also provide additional information about your plugin using several special properties: title - short one-sentence description of your plugin version - The version of your plugin. Valid values include example "0.1", "0.2-SNAPSHOT", "1.1.4" etc.

grailsVersion - The version of version range of Grails that the plugin supports. eg. "1.2 > *" (indicating author - plugin author's name authorEmail - plugin author's contact e-mail description - full multi-line description of plugin's features documentation - URL of the plugin's documentation Here is an example from the Quartz Grails plugin:
class QuartzGrailsPlugin { def version = "0.1" def grailsVersion = "1.1 > *" def author = "Sergey Nebolsin" def authorEmail = "nebolsin@gmail.com" def title = "Quartz Plugin" def description = '''\ The Quartz plugin allows your Grails application to schedule jobs\ to be executed using a specified interval or cron expression. The\ underlying system uses the Quartz Enterprise Job Scheduler configured\ via Spring, but is made simpler by the coding by convention paradigm.\ ''' def documentation = "http://grails.org/plugin/quartz" }

Installing and Distributing Plugins


To distribute a plugin you navigate to its root directory in a console and run:
grails package-plugin

This will create a zip file of the plugin starting with grails- then the plugin name and version. For example wi created earlier this would be grails-example-0.1.zip. The package-plugin command will also gene file which contains machine-readable information about plugin's name, version, author, and so on. Once you have a plugin distribution file you can navigate to a Grails project and run:
grails install-plugin /path/to/grails-example-0.1.zip

If the plugin is hosted on an HTTP server you can install it with:


grails install-plugin http://myserver.com/plugins/grails-example-0.1.zip

338

Notes on excluded Artefacts

Although the create-plugin command creates certain files for you so that the plugin can be run as a Grails applic files are included when packaging a plugin. The following is a list of artefacts created, but not included by packag grails-app/conf/BootStrap.groovy

grails-app/conf/BuildConfig.groovy (although it is used to generate dependencies.groov grails-app/conf/Config.groovy grails-app/conf/DataSource.groovy (and any other *DataSource.groovy) grails-app/conf/UrlMappings.groovy grails-app/conf/spring/resources.groovy Everything within /web-app/WEB-INF Everything within /web-app/plugins/** Everything within /test/** SCM management files within **/.svn/** and **/CVS/**

If you need artefacts within WEB-INF it is recommended you use the _Install.groovy script (covered late when a plugin is installed, to provide such artefacts. In addition, although UrlMappings.groovy is exclude include a UrlMappings definition with a different name, such as MyPluginUrlMappings.groovy.

Specifying Plugin Locations

An application can load plugins from anywhere on the file system, even if they have not been installed. Specif (unpacked) plugin in the application's grails-app/conf/BuildConfig.groovy file:
// Useful to test plugins you are developing. grails.plugin.location.shiro = "/home/dilbert/dev/plugins/grails-shiro" // Useful for modular applications where all plugins and // applications are in the same directory. grails.plugin.location.'grails-ui' = "../grails-grails-ui"

This is particularly useful in two cases: You are developing a plugin and want to test it in a real application without packaging and installing it first.

You have split an application into a set of plugins and an application, all in the same "super-project" directory

Global plugins

Plugins can also be installed globally for all applications for a particular version of Grails using the -global flag
grails install-plugin webtest -global

339

The default location is $USER_HOME/.grails/<grailsVersion>/global-plugins but this can be cust grails.global.plugins.dir setting in BuildConfig.groovy.

13.2 Plugin Repositories


Distributing Plugins in the Grails Central Plugin Repository

The preferred way to distribute plugin is to publish to the official Grails Central Plugin Repository. This will mak to the list-plugins command:
grails list-plugins

which lists all plugins that are in the central repository. Your plugin will also be available to the plugin-info comm
grails plugin-info [plugin-name]

which prints extra information about it, such as its description, who wrote, etc.

If you have created a Grails plugin and want it to be hosted in the central repository, you'll find instr for getting an account on this wiki page.

When you have access to the Grails Plugin repository, install the Release Plugin and execute the publish-p release your plugin:
grails install-plugin release grails publish-plugin

This will automatically commit any remaining source code changes to your SCM provider and then publish the repository. If the command is successful, it will immediately be available on the plugin portal at http://grails.org/p You can find out more about the Release plugin and its other features in its user guide.

Configuring Additional Repositories

The process for configuring repositories in Grails differs between versions. For version of Grails 1.2 and earlie Grails 1.2 documentation on the subject. The following sections cover Grails 1.3 and above.

Grails 1.3 and above use Ivy under the hood to resolve plugin dependencies. The mechanism for defining addition is largely the same as defining repositories for JAR dependencies. For example you can define a remote Maven re Grails plugins using the following syntax in grails-app/conf/BuildConfig.groovy:

340

repositories { mavenRepo "http://repository.codehaus.org" // ...or with a name mavenRepo name: "myRepo", root: "http://myserver:8081/artifactory/plugins-snapshots-local" }

You can also define a SVN-based Grails repository (such as the one hosted at http://plugins.grails.org) usin method:
repositories { grailsRepo "http://myserver/mygrailsrepo" // ...or with a name grailsRepo "http://myserver/svn/grails-plugins", "mySvnRepo" }

There is a shortcut to setup the Grails central repository:


repositories { grailsCentral() }

The order in which plugins are resolved is based on the ordering of the repositories. So in this case the Grails cen searched last:
repositories { grailsRepo "http://myserver/mygrailsrepo" grailsCentral() }

All of the above examples use HTTP; however you can specify any Ivy resolver to resolve plugins with. Below is an SSH resolver:
def sshResolver = new SshResolver(user:"myuser", host:"myhost.com") sshResolver.addArtifactPattern( "/path/to/repo/grails-[artifact]/tags/" + "LATEST_RELEASE/grails-[artifact]-[revision].[ext]") sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy() sshResolver.changingPattern = ".*SNAPSHOT" sshResolver.setCheckmodified(true)

The above example defines an artifact pattern which tells Ivy how to resolve a plugin zip file. For a more detaile patterns see the relevant section in the Ivy user guide.

Publishing to Maven Compatible Repositories

341

In general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plu doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven re Maven compatible repositories are not tied to SVN as Grails repositories are.

You use the Maven publisher plugin to publish a plugin to a Maven repository. Please refer to the section of th user guide on the subject.

Publishing to Grails Compatible Repositories

Specify the grails.plugin.repos.distribution.myRepository setting within the grails-app/con file to publish a Grails plugin to a Grails-compatible repository:
grails.plugin.repos.distribution.myRepository = "https://svn.codehaus.org/grails/trunk/grails-test-plugin-repo"

You can also provide this settings in the $USER_HOME/.grails/settings.groovy file if you prefer to share the multiple projects.

Once this is done use the repository argument of the release-plugin command to specify the repository into:
grails release-plugin -repository = myRepository

13.3 Understanding a Plugin's Structure

As as mentioned previously, a plugin is basically a regular Grails application with a plugin descriptor. Howeve structure of a plugin differs slightly. For example, take a look at this plugin directory structure:
+ grails-app + controllers + domain + taglib etc. + lib + src + java + groovy + web-app + js + css

When a plugin is installed the contents of the grails-app directory will go into a d plugins/example-1.0/grails-app. They will not be copied into the main source tree. A plugin ne project's primary source tree.

Dealing with static resources is slightly different. When developing a plugin, just like an application, all static web-app directory. You can then link to static resources just like in an application. This example links to a JavaS
<g:resource dir="js" file="mycode.js" />

342

When you run the plugin in development mode the link to the resource will resolve to something like /js/my when the plugin is installed into an application the path will automatically change to /plugin/example-0.1/js/mycode.js and Grails will deal with making sure the resources are in the righ

There is a special pluginContextPath variable that can be used whilst both developing the plugin and w installed into the application to find out what the correct path to the plugin is.

At runtime the pluginContextPath variable will either evaluate to an empty string or /plugins/exa whether the plugin is running standalone or has been installed in an application

Java and Groovy code that the plugin provides within the lib and src/java and src/groovy directories will main project's web-app/WEB-INF/classes directory so that they are made available at runtime.

13.4 Providing Basic Artefacts


Adding a new Script
A plugin can add a new script simply by providing the relevant Gant script in its scripts directory:
+ MyPlugin.groovy + scripts <-- additional scripts here + grails-app + controllers + services + etc. + lib

Adding a new grails-app artifact (Controller, Tag Library, Service, etc.)

A plugin can add new artifacts by creating the relevant file within the grails-app tree. Note that the plugin is is installed and not copied into the main application tree.
+ ExamplePlugin.groovy + scripts + grails-app + controllers <-- additional controllers here + services <-- additional services here + etc. <-- additional XXX here + lib

Providing Views, Templates and View resolution

When a plugin provides a controller it may also provide default views to be rendered. This is an excellent wa application through plugins. Grails' view resolution mechanism will first look for the view in the application it i that fails will attempt to look for the view within the plugin. This means that you can override views provided by corresponding GSPs in the application's grails-app/views directory.

For example, consider a controller called BookController that's provided by an 'amazon' plugin. If the acti list, Grails will first look for a view called grails-app/views/book/list.gsp then if that fails it w view relative to the plugin.

However if the view uses templates that are also provided by the plugin then the following syntax may be necessar 343

<g:render template="fooTemplate" plugin="amazon"/>

Note the usage of the plugin attribute, which contains the name of the plugin where the template resides. If this Grails will look for the template relative to the application.

Excluded Artefacts
By default Grails excludes the following files during the packaging process: grails-app/conf/BootStrap.groovy

grails-app/conf/BuildConfig.groovy (although it is used to generate dependencies.groov grails-app/conf/Config.groovy grails-app/conf/DataSource.groovy (and any other *DataSource.groovy) grails-app/conf/UrlMappings.groovy grails-app/conf/spring/resources.groovy Everything within /web-app/WEB-INF Everything within /web-app/plugins/** Everything within /test/** SCM management files within **/.svn/** and **/CVS/**

If your plugin requires files under the web-app/WEB-INF directory it is recommended that you m scripts/_Install.groovy Gant script to install these artefacts into the target project's directory tree.

In addition, the default UrlMappings.groovy file is excluded to avoid naming conflicts, however yo UrlMappings definition under a different name which will be included. For example grails-app/conf/BlogUrlMappings.groovy is fine. The list of excludes is extensible with the pluginExcludes property:
// resources that are excluded from plugin packaging def pluginExcludes = [ "grails-app/views/error.gsp" ]

This is useful for example to include demo or test resources in the plugin repository, but not include them in the fi

13.5 Evaluating Conventions

Before looking at providing runtime configuration based on conventions you first need to understand ho conventions from a plugin. Every plugin has an implicit application variable which is an instance of t interface.

The GrailsApplication interface provides methods to evaluate the conventions within the project and intern to all artifact classes within your application. 344

Artifacts implement the GrailsClass interface, which represents a Grails resource such as a controller or a tag lib get all GrailsClass instances you can do:
for (grailsClass in application.allClasses) { println grailsClass.name }

GrailsApplication has a few "magic" properties to narrow the type of artefact you are interested in. Fo controllers you can use:
for (controllerClass in application.controllerClasses) { println controllerClass.name }

The dynamic method conventions are as follows:

*Classes - Retrieves all the classes for a particular artefact name. For example application.contro get*Class Retrieves a named class for a application.getControllerClass("PersonController") is*Class - Returns true if the given class is of application.isControllerClass(PersonController) particular the given artefact. artefact

type.

The GrailsClass interface has a number of useful methods that let you further evaluate and work with th include: getPropertyValue - Gets the initial value of the given property on the class hasProperty - Returns true if the class has the specified property newInstance - Creates a new instance of this class.

getName - Returns the logical name of the class in the application without the trailing convention part if app getShortName - Returns the short name of the class without package prefix

getFullName - Returns the full name of the class in the application with the trailing convention part and w getPropertyName - Returns the name of the class as a property name

getLogicalPropertyName - Returns the logical property name of the class in the application without th part if applicable

getNaturalName - Returns the name of the property in natural terms (eg. 'lastName' becomes 'Last Name getPackageName - Returns the package name For a full reference refer to the javadoc API.

13.6 Hooking into Build Events


Post-Install Configuration and Participating in Upgrades

345

Grails plugins can do post-install configuration and participate in application upgrade process (the upgrade comma using two specially named scripts under the scripts directory of the plugin - _Install.groovy and _Upgr

_Install.groovy is executed after the plugin has been installed and _Upgrade.groovy is executed upgrades the application (but not the plugin) with upgrade command.

These scripts are Gant scripts, so you can use the full power of Gant. An addition to the standard Gant varia pluginBasedir variable which points at the plugin installation basedir.

As an example this _Install.groovy script will create a new directory type under the grails-app d configuration template:
ant.mkdir(dir: "${basedir}/grails-app/jobs") ant.copy(file: "${pluginBasedir}/src/samples/SamplePluginConfig.groovy", todir: "${basedir}/grails-app/conf")

The pluginBasedir variable is not available in custom scripts, but you can use fooPluginDir, where foo plugin.

Scripting events

It is also possible to hook into command line scripting events. These are events triggered during execution of Gr scripts.

For example, you can hook into status update output (i.e. "Tests passed", "Server running") and the creation of file

A plugin just has to provide an _Events.groovy script to listen to the required events. Refer the documenta Events for further information.

13.7 Hooking into Runtime Configuration

Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration

Hooking into the Grails Spring configuration

First, you can hook in Grails runtime configuration by providing a property called doWithSpring which is assi For example the following snippet is from one of the core Grails plugins that provides i18n support:
import org.springframework.web.servlet.i18n.CookieLocaleResolver import org.springframework.web.servlet.i18n.LocaleChangeInterceptor import org.springframework.context.support.ReloadableResourceBundleMessageSource class I18nGrailsPlugin { def version = "0.1" def doWithSpring = { messageSource(ReloadableResourceBundleMessageSource) { basename = "WEB-INF/grails-app/i18n/messages" } localeChangeInterceptor(LocaleChangeInterceptor) { paramName = "lang" } localeResolver(CookieLocaleResolver) } }

346

This plugin configures the Grails messageSource bean and a couple of other beans to manage Locale resolu using the Spring Bean Builder syntax to do so.

Participating in web.xml Generation

Grails generates the WEB-INF/web.xml file at load time, and although plugins cannot change this file directly in the generation of the file. A plugin can provide a doWithWebDescriptor property that is assigned a bl passed the web.xml as an XmlSlurper GPathResult.
Add servlet and servlet-mapping

Consider this example from the ControllersPlugin:


def doWithWebDescriptor = { webXml -> def mappingElement = webXml.'servlet-mapping' def lastMapping = mappingElement[mappingElement.size() - 1] lastMapping + { 'servlet-mapping' { 'servlet-name'( "grails") 'url-pattern'( "*.dispatch") } } }

Here the plugin gets a reference to the last <servlet-mapping> element and appends Grails' servlet after ability to programmatically modify XML using closures and blocks.
Add filter and filter-mapping

Adding a filter with its mapping works a little differently. The location of the <filter> element doesn't mat important, so it's simplest to insert your custom filter definition immediately after the last <context-para important for mappings, but the usual approach is to add it immediately after the last <filter> element like so:
def doWithWebDescriptor = { webXml -> def contextParam = webXml.'context-param' contextParam[contextParam.size() - 1] + { 'filter' { 'filter-name'('springSecurityFilterChain') 'filter-class'(DelegatingFilterProxy.name) } } def filter = webXml.'filter' filter[filter.size() - 1] + { 'filter-mapping'{ 'filter-name'('springSecurityFilterChain') 'url-pattern'('/*') } } }

347

In some cases you need to ensure that your filter comes after one of the standard Grails filters, such as the Sprin filter or the SiteMesh filter. Fortunately you can insert filter mappings immediately after the standard ones (mor are in the template web.xml file) like so:
def doWithWebDescriptor = { webXml -> ... // Insert the Spring Security filter after the Spring // character encoding filter. def filter = webXml.'filter-mapping'.find { it.'filter-name'.text() == "charEncodingFilter" } filter + { 'filter-mapping'{ 'filter-name'('springSecurityFilterChain') 'url-pattern'('/*') } } }

Doing Post Initialisation Configuration

Sometimes it is useful to be able do some runtime configuration after the Spring ApplicationContext has been b can define a doWithApplicationContext closure property.
class SimplePlugin { def name = "simple" def version = "1.1" def doWithApplicationContext = { appCtx -> def sessionFactory = appCtx.sessionFactory // do something here with session factory } }

13.8 Adding Dynamic Methods at Runtime


The Basics

Grails plugins let you register dynamic methods with any Grails-managed or other class at runtime. This doWithDynamicMethods closure. For Grails-managed classes like controllers, tag libraries and so forth you can add methods, construc ExpandoMetaClass mechanism by accessing each controller's MetaClass:
class ExamplePlugin { def doWithDynamicMethods = { applicationContext -> for (controllerClass in application.controllerClasses) { controllerClass.metaClass.myNewMethod = {-> println "hello world" } } } }

348

In this case we use the implicit application object to get a reference to all of the controller classes' MetaClass ins method called myNewMethod to each controller. If you know beforehand the class you wish the add a metho reference its metaClass property. For example we can add a new method swapCase to java.lang.String:
class ExamplePlugin { def doWithDynamicMethods = { applicationContext -> String.metaClass.swapCase = {-> def sb = new StringBuilder() delegate.each { sb << ( Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() } assert "UpAndDown" == "uPaNDdOWN".swapCase() } }

Interacting with the ApplicationContext

The doWithDynamicMethods closure gets passed the Spring ApplicationContext instance. This is interact with objects within it. For example if you were implementing a method to interact with Hibernate SessionFactory instance in combination with a HibernateTemplate:
import org.springframework.orm.hibernate3.HibernateTemplate class ExampleHibernatePlugin { def doWithDynamicMethods = { applicationContext -> for (domainClass in application.domainClasses) { domainClass.metaClass.static.load = { Long id-> def sf = applicationContext.sessionFactory def template = new HibernateTemplate(sf) template.load(delegate, id) } } } }

Also because of the autowiring and dependency injection capability of the Spring container you can implement mo constructors that use the application context to wire dependencies into your object at runtime:
class MyConstructorPlugin { def doWithDynamicMethods = { applicationContext -> for (domainClass in application.domainClasses) { domainClass.metaClass.constructor = {-> return applicationContext.getBean(domainClass.name) } } } }

349

Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!

13.9 Participating in Auto Reload Events


Monitoring Resources for Changes

Often it is valuable to monitor resources for changes and perform some action when they occur. This is how advanced reloading of application state at runtime. For example, consider this simplified snippet from the Grails S
class ServicesGrailsPlugin { def watchedResources = "file:./grails-app/services/*Service.groovy" def onChange = { event -> if (event.source) { def serviceClass = application.addServiceClass(event.source) def serviceName = "${serviceClass.propertyName}" def beans = beans { "$serviceName"(serviceClass.getClazz()) { bean -> bean.autowire = true } } if (event.ctx) { event.ctx.registerBeanDefinition( serviceName, beans.getBeanDefinition(serviceName)) } } } }

First it defines watchedResources as either a String or a List of strings that contain either the referenc resources to watch. If the watched resources specify a Groovy file, when it is changed it will automatically be relo the onChange closure in the event object. The event object defines a number of useful properties: event.source - The source of the event, either the reloaded Class or a Spring Resource event.ctx - The Spring ApplicationContext instance event.plugin - The plugin object that manages the resource (usually this) event.application - The GrailsApplication instance event.manager - The GrailsPluginManager instance

These objects are available to help you apply the appropriate changes based on what changed. In the "Services" e service bean is re-registered with the ApplicationContext when one of the service classes changes.

Influencing Other Plugins


In addition to reacting to changes, sometimes a plugin needs to "influence" another.

Take for example the Services and Controllers plugins. When a service is reloaded, unless you reload the controlle occur when you try to auto-wire the reloaded service into an older controller Class.

350

To get around this, you can specify which plugins another plugin "influences". This means that when one plugi will reload itself and then reload its influenced plugins. For example consider this snippet from the ServicesGr
def influences = ['controllers']

Observing other plugins

If there is a particular plugin that you would like to observe for changes but not necessary watch the resources tha use the "observe" property:
def observe = ["controllers"]

In this case when a controller is changed you will also receive the event chained from the controllers plugin. It is also possible for a plugin to observe all loaded plugins by using a wildcard:
def observe = ["*"]

The Logging plugin does exactly this so that it can add the log property back to any artefact that changes wh running.

13.10 Understanding Plugin Load Order


Controlling Plugin Dependencies

Plugins often depend on the presence of other plugins and can adapt depending on the presence of others. This two properties. The first is called dependsOn. For example, take a look at this snippet from the Hibernate plugin
class HibernateGrailsPlugin { def version = "1.0" def dependsOn = [dataSource: "1.0", domainClass: "1.0", i18n: "1.0", core: "1.0"] }

The Hibernate plugin is dependent on the presence of four plugins: the dataSource, domainClass, i18n an

The dependencies will be loaded before the Hibernate plugin and if all dependencies do not load, then the plugin w

The dependsOn property also supports a mini expression language for specifying version ranges. A few examp be seen below:

351

def dependsOn = [foo: "* > 1.0"] def dependsOn = [foo: "1.0 > 1.1"] def dependsOn = [foo: "1.0 > *"]

When the wildcard * character is used it denotes "any" version. The expression syntax also excludes any suff -ALPHA etc. so for example the expression "1.0 > 1.1" would match any of the following versions: 1.1 1.0 1.0.1 1.0.3-SNAPSHOT 1.1-BETA2

Controlling Load Order

Using dependsOn establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give is possible though to have a weaker dependency using the loadAfter and loadBefore properties:
def loadAfter = ['controllers']

Here the plugin will be loaded after the controllers plugin if it exists, otherwise it will just be loaded. The plu the presence of the other plugin, for example the Hibernate plugin has this code in its doWithSpring closure:
if (manager?.hasGrailsPlugin("controllers")) { openSessionInViewInterceptor(OpenSessionInViewInterceptor) { flushMode = HibernateAccessor.FLUSH_MANUAL sessionFactory = sessionFactory } grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor }

Here the Hibernate plugin will only register an OpenSessionInViewInterceptor if the controlle loaded. The manager variable is an instance of the GrailsPluginManager interface and it provides methods t plugins. You can also use the loadBefore property to specify one or more plugins that your plugin should load before:
def loadBefore = ['rabbitmq']

Scopes and Environments

It's not only plugin load order that you can control. You can also specify which environments your plugin sho which scopes (stages of a build). Simply declare one or both of these properties in your plugin descriptor:

352

def environments = ['development', 'test', 'myCustomEnv'] def scopes = [excludes:'war']

In this example, the plugin will only load in the 'development' and 'test' environments. Nor will it be package because it's excluded from the 'war' phase. This allows development-only plugins to not be packaged for pro The full list of available scopes are defined by the enum BuildScope, but here's a summary: test - when running tests functional-test - when running functional tests run - for run-app and run-war war - when packaging the application as a WAR file all - plugin applies to all scopes (default) Both properties can be one of: a string - a sole inclusion a list - a list of environments or scopes to include a map - for full control, with 'includes' and/or 'excludes' keys that can have string or list values For example,
def environments = "test"

will only include the plugin in the test environment, whereas


def environments = ["development", "test"]

will include it in both the development and test environments. Finally,


def environments = [includes: ["development", "test"]]

will do the same thing.

13.11 The Artefact API

You should by now understand that Grails has the concept of artefacts: special types of classes that it knows differently from normal Groovy and Java classes, for example by enhancing them with extra properties and m artefacts include domain classes and controllers. What you may not be aware of is that Grails allows application a access to the underlying infrastructure for artefacts, which means you can find out what artefacts are available an yourself. You can even provide your own custom artefact types.

353

13.11.1 Asking About Available Artefacts

As a plugin developer, it can be important for you to find out about what domain classes, controllers, or other available in an application. For example, the Searchable plugin needs to know what domain classes exist so it can searchable properties and index the appropriate ones. So how does it do it? The answer lies with the gra object, and instance of GrailsApplication that's available automatically in controllers and GSPs and can be injected

The grailsApplication object has several important properties and methods for querying artefacts. Probab is the one that gives you all the classes of a particular artefact type:
for (cls in grailsApplication.<artefactType>Classes) { }

In this case, artefactType is the property name form of the artefact type. With core Grails you have: domain controller tagLib service codec bootstrap urlMappings So for example, if you want to iterate over all the domain classes, you use:
for (cls in grailsApplication.domainClasses) { }

and for URL mappings:


for (cls in grailsApplication.urlMappingsClasses) { }

You need to be aware that the objects returned by these properties are not instances of Class. Instead, they are ins that has some particularly useful properties and methods, including one for the underlying Class:

354

shortName - the class name of the artefact without the package (equivalent of Class.simpleName).

logicalPropertyName - the artefact name in property form without the 'type' suffix. So MyGreatCo 'myGreat'. isAbstract() - a boolean indicating whether the artefact class is abstract or not.

getPropertyValue(name) - returns the value of the given property, whether it's a static or an instance if the property is initialised on declaration, e.g. static transactional = true. The artefact API also allows you to fetch classes by name and check whether a class is an artefact: get<type>Class(String name) is<type>Class(Class clazz)

The first method will retrieve the GrailsClass instance for the given name, e.g. 'MyGreatController'. Th whether a class is a particular type of artefact. For example, you grailsApplication.isControllerClass(org.example.MyGreatController) to ch MyGreatController is in fact a controller.

13.11.2 Adding Your Own Artefact Types

Plugins can easily provide their own artefacts so that they can easily find out what implementations are avail reloading. All you need to do is create an ArtefactHandler implementation and register it in your main plugi
class MyGrailsPlugin { def artefacts = [ org.somewhere.MyArtefactHandler ] }

The artefacts list can contain either handler classes (as above) or instances of handlers.

So, what does an artefact handler look like? Well, put simply it is an implementation of the ArtefactHandler inte bit easier, there is a skeleton implementation that can readily be extended: ArtefactHandlerAdapter.

In addition to the handler itself, every new artefact needs a corresponding wrapper class that implements GrailsC implementations are available such as AbstractInjectableGrailsClass, which is particularly useful as it turns your bean that is auto-wired, just like controllers and services. The best way to understand how both the handler and wrapper classes work is to look at the Quartz plugin: GrailsJobClass DefaultGrailsJobClass JobArtefactHandler Another example is the Shiro plugin which adds a realm artefact.

13.12 Binary Plugins

Regular Grails plugins are packaged as zip files containing the full source of the plugin. This has some advantage open distribution system (anyone can see the source), in addition to avoiding problems with the source compa compilation. 355

As of Grails 2.0 you can pre-compile Grails plugins into regular JAR files known as "binary plugins". This has sev some disadvantages as discussed in the advantages of source plugins above) including: Binary plugins can be published as standard JAR files to a Maven repository Binary plugins can be declared like any other JAR dependency Commercial plugins are more viable since the source isn't published IDEs have a better understanding since binary plugins are regular JAR files containing classes

Packaging
To package a plugin in binary form you can use the package-plugin command and the --binary flag:
grails package-plugin --binary

Supported artefacts include: Grails artifact classes such as controllers, domain classes and so on I18n Message bundles GSP Views, layouts and templates You can also specify the packaging in the plugin descriptor:
def packaging = "binary"

in which case the packaging will default to binary.

Using Binary Plugins

The packaging process creates a JAR file in the target directory of the plugin, for example target/fooThere are two ways to incorporate a binary plugin into an application.

One is simply placing the plugin JAR file in your application's lib directory. The other is to publish the plugin Maven repository and declare it as a dependency in grails-app/conf/BuildConfig.groovy:
dependencies { compile "mycompany:myplugin:0.1" }

Since binary plugins are packaged as JAR files, they are declared as dependencies in the dependen block, not in the plugins block as you may be naturally inclined to do. The plugins block is u declaring traditional source plugins packaged as zip files

356

14 Web Services
14.1 REST

Web services are all about providing a web API onto your web application and are typically implemented in either

REST is not really a technology in itself, but more an architectural pattern. REST is very simple and just involves JSON as a communication medium, combined with URL patterns that are "representational" of the underlyin methods such as GET, PUT, POST and DELETE.

Each HTTP method maps to an action type. For example GET for retrieving data, PUT for creating data, POST fo In this sense REST fits quite well with CRUD.

URL patterns
The first step to implementing REST with Grails is to provide RESTful URL mappings:
static mappings = { "/product/$id?"(resource:"product") }

This maps the URI /product onto a ProductController. Each HTTP method such as GET, PUT, POST unique actions within the controller as outlined by the table below: Method Action GET PUT POST show update save

DELETE delete In addition, Grails provides automatic XML or JSON marshalling for you. You can alter how HTTP methods are handled by using URL Mappings to map to HTTP methods:
"/product/$id"(controller: "product") { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }

However, unlike the resource argument used previously, in this case Grails will not provide automatic XML unless you specify the parseRequest argument:
"/product/$id"(controller: "product", parseRequest: true) { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }

357

HTTP Methods

In the previous section you saw how you can easily define URL mappings that map specific HTTP methods on actions. Writing a REST client that then sends a specific HTTP method is then easy (example in Groovy's HTTPB
import groovyx.net.http.* import static groovyx.net.http.ContentType.JSON def http = new HTTPBuilder("http://localhost:8080/amazon") http.request(Method.GET, JSON) { url.path = '/book/list' response.success = { resp, json -> for (book in json.books) { println book.title } } }

Issuing a request with a method other than GET or POST from a regular browser is not possible without some he defining a form you can specify an alternative method such as DELETE:
<g:form controller="book" method="DELETE"> .. </g:form>

Grails will send a hidden parameter called _method, which will be used as the request's HTTP method. An changing the method for non-browser clients is to use the X-HTTP-Method-Override to specify the alternativ

XML Marshalling - Reading


The controller can use Grails' XML marshalling support to implement the GET method:
import grails.converters.XML class ProductController { def show() { if (params.id && Product.exists(params.id)) { def p = Product.findByName(params.id) render p as XML } else { def all = Product.list() render all as XML } } .. }

If there is an id we search for the Product by name and return it, otherwise we return all Products. Th /products we get all products, otherwise if we go to /product/MacBook we only get a MacBook.

XML Marshalling - Updating

358

To support updates such as PUT and POST you can use the params object which Grails enhances with the ability XML packet. Given an incoming XML packet of:
<?xml version="1.0" encoding="ISO-8859-1"?> <product> <name>MacBook</name> <vendor id="12"> <name>Apple</name> </vender> </product>

you can read this XML packet using the same techniques described in the Data Binding section, using the params
def save() { def p = new Product(params.product) if (p.save()) { render p as XML } else { render p.errors } }

In this example by indexing into the params object using the product key we can automatically create and bin Product constructor. An interesting aspect of the line:
def p = new Product(params.product)

is that it requires no code changes to deal with a form submission that submits form data, or an XML request, or a

If you require different responses to different clients (REST, HTML etc.) you can use content negotat

The Product object is then saved and rendered as XML, otherwise an error message is produced using Grails' v in the form:
<error> <message>The property 'title' of class 'Person' must be specified</message> </error>

REST with JAX-RS

There also is a JAX-RS Plugin which can be used to build web services based on the Java API for RESTful We JAX-RS).

14.2 SOAP

359

There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract there is a Spring WS plugin, whilst if you want to generate a SOAP API from Grails services there are severa including: CXF plugin which uses the CXF SOAP stack Axis2 plugin which uses Axis2 Metro plugin which uses the Metro framework (and can also be used for Contract First)

Most of the SOAP integrations integrate with Grails services via the exposes static property. This example is plugin:
class BookService { static expose = ['cxf'] Book[] getBooks() { Book.list() as Book[] } }

The WSDL can then be accessed at the location: http://127.0.0.1:8080/your_grails_app/servic For more information on the CXF plugin refer to the documentation on the wiki.

14.3 RSS and Atom

No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the r capability. There is however a Feeds plugin available for Grails that provides a RSS and Atom builder using library. An example of its usage can be seen below:
def feed() { render(feedType: "rss", feedVersion: "2.0") { title = "My test feed" link = "http://your.test.server/yourController/feed" for (article in Article.list()) { entry(article.title) { link = "http://your.test.server/article/${article.id}" article.content // return the content } } } }

360

15 Grails and Spring

This section is for advanced users and those who are interested in how Grails integrates with and builds on the Sp also useful for plugin developers considering doing runtime configuration Grails.

15.1 The Underpinnings of Grails

Grails is actually a Spring MVC application in disguise. Spring MVC is the Spring framework's built-in M framework. Although Spring MVC suffers from some of the same difficulties as frameworks like Struts in terms o superbly designed and architected and was, for Grails, the perfect framework to build another framework on top of Grails leverages Spring MVC in the following areas:

Basic controller logic - Grails subclasses Spring's DispatcherServlet and uses it to delegate to Grails controlle

Data Binding and Validation - Grails' validation and data binding capabilities are built on those provided by S

Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring Applica Transactions - Grails uses Spring's transaction management in GORM In other words Grails has Spring embedded running all the way through it.

The Grails ApplicationContext

Spring developers are often keen to understand how the Grails ApplicationContext instance is constructed as follows.

Grails constructs a parent ApplicationContext from the web-app/WEB-INF/applicationCont ApplicationContext configures the GrailsApplication instance and the GrailsPluginManager.

Using this ApplicationContext as a parent Grails' analyses the conventions with the GrailsApplic constructs a child ApplicationContext that is used as the root ApplicationContext of the web ap

Configured Spring Beans

Most of Grails' configuration happens at runtime. Each plugin may configure Spring beans that are ApplicationContext. For a reference as to which beans are configured, refer to the reference guide which Grails plugins and which beans they configure.

15.2 Configuring Additional Beans


Using the Spring Bean DSL

You can easily register new (or override existing) beans by configurin grails-app/conf/spring/resources.groovy which uses the Grails Spring DSL. Beans are defi property (a Closure):
beans = { // beans here }

361

As a simple example you can configure a bean with the following syntax:
import my.company.MyBeanImpl beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } }

Once configured, the bean can be auto-wired into Grails artifacts and other classes that support dependency in BootStrap.groovy and integration tests) by declaring a public field whose name is your bean's name (in this
class ExampleController { def myBean }

Using the DSL has the advantage that you can mix bean declarations and logic, for example based on the environm
import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImpl beans = { switch(Environment.current) { case Environment.PRODUCTION: myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } break case Environment.DEVELOPMENT: myBean(MockImpl) { someProperty = 42 otherProperty = "blue" } break } }

The GrailsApplication object can be accessed with the application variable and can be used configuration (amongst other things):

362

import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImpl beans = { if (application.config.my.company.mockService) { myBean(MockImpl) { someProperty = 42 otherProperty = "blue" } } else { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } } }

If you define a bean in resources.groovy with the same name as one previously registered by or an installed plugin, your bean will replace the previous registration. This is a convenient w customize behavior without resorting to editing plugin code or other approaches that would maintainability.

Using XML

Beans can also be configured using a grails-app/conf/spring/resources.xml. In earlier versions o automatically generated for you by the run-app script, but the DSL in resources.groovy is the preferre isn't automatically generated now. But it is still supported - you just need to create it yourself. This file is typical Spring XML file and the Spring documentation has an excellent reference on how to configure The myBean bean that we configured using the DSL would be configured with this syntax in the XML file:
<bean id="myBean" class="my.company.MyBeanImpl"> <property name="someProperty" value="42" /> <property name="otherProperty" value="blue" /> </bean>

Like the other bean it can be auto-wired into any class that supports dependency injection:
class ExampleController { def myBean }

Referencing Existing Beans

Beans declared in resources.groovy or resources.xml can reference other beans by convention. For e BookService class its Spring bean name would be bookService, so your bean would reference it like this in

363

beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" bookService = ref("bookService") } }

or like this in XML:


<bean id="myBean" class="my.company.MyBeanImpl"> <property name="someProperty" value="42" /> <property name="otherProperty" value="blue" /> <property name="bookService" ref="bookService" /> </bean>

The bean needs a public setter for the bean reference (and also the two simple properties), which in Groovy would
package my.company class MyBeanImpl { Integer someProperty String otherProperty BookService bookService // or just "def bookService" }

or in Java like this:


package my.company; class MyBeanImpl { private BookService bookService; private Integer someProperty; private String otherProperty; public void setBookService(BookService theBookService) { this.bookService = theBookService; } public void setSomeProperty(Integer someProperty) { this.someProperty = someProperty; } public void setOtherProperty(String otherProperty) { this.otherProperty = otherProperty; } }

Using ref (in XML or the DSL) is very powerful since it configures a runtime reference, so the referenced bean yet. As long as it's in place when the final application context configuration occurs, everything will be resolved co For a full reference of the available beans see the plugin reference in the reference guide.

15.3 Runtime Spring with the Beans DSL

This Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at it 364

In addition, Spring's regular way of configuration (via XML and annotations) is static and difficult to modify and other than programmatic XML creation which is both error prone and verbose. Grails' BeanBuilder changes possible to programmatically wire together components at runtime, allowing you to adapt the logic based on environment variables.

This enables the code to adapt to its environment and avoids unnecessary duplication of code (having different S development and production environments)

The BeanBuilder class

Grails provides a grails.spring.BeanBuilder class that uses dynamic Groovy to construct bean definitions. The basi
import import import import org.apache.commons.dbcp.BasicDataSource org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean org.springframework.context.ApplicationContext grails.spring.BeanBuilder

def bb = new BeanBuilder() bb.beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = ref('dataSource') hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } } ApplicationContext appContext = bb.createApplicationContext()

Within plugins and the grails-app/conf/spring/resources.groovy file you don't need to create a new in of BeanBuilder. Instead the DSL is implicitly available inside the doWithSpring and beans respectively. This example shows how you would configure Hibernate with a data source with the BeanBuilder class.

Each method call (in this case dataSource and sessionFactory calls) maps to the name of the bean argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you the bean using standard Groovy syntax.

Bean references are resolved automatically using the name of the bean. This can be seen in the example abo sessionFactory bean resolves the dataSource reference.

Certain special properties related to bean management can also be set by the builder, as seen in the following code

365

sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> // Autowiring behaviour. The other option is 'byType'. [autowire] bean.autowire = 'byName' // Sets the initialisation method to 'init'. [init-method] bean.initMethod = 'init' // Sets the destruction method to 'destroy'. [destroy-method] bean.destroyMethod = 'destroy' // Sets the scope of the bean. [scope] bean.scope = 'request' dataSource = ref('dataSource') hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] }

The strings in square brackets are the names of the equivalent bean attributes in Spring's XML definition.

Using BeanBuilder with Spring MVC

Include the grails-spring-<version>.jar file in your classpath to use BeanBuilder in a regular Spri Then add the following <context-param> values to your /WEB-INF/web.xml file:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.groovy</param-value> </context-param> <context-param> <param-name>contextClass</param-name> <param-value> org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext </param-value> </context-param>

Then create a /WEB-INF/applicationContext.groovy file that does the rest:


import org.apache.commons.dbcp.BasicDataSource beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } }

Loading Bean Definitions from the File System

You can use the BeanBuilder class to load external Groovy scripts that define beans using the same path ma here. For example:
def bb = new BeanBuilder() bb.loadBeans("classpath:*SpringBeans.groovy") def applicationContext = bb.createApplicationContext()

366

Here the BeanBuilder loads all Groovy files on the classpath ending with SpringBeans.groovy and p definitions. An example script can be seen below:
import org.apache.commons.dbcp.BasicDataSource import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } }

Adding Variables to the Binding (Context)


If you're loading beans from a script you can set the binding to use by creating a Groovy Binding:
def binding = new Binding() binding.maxSize = 10000 binding.productGroup = 'finance' def bb = new BeanBuilder() bb.binding = binding bb.loadBeans("classpath:*SpringBeans.groovy") def ctx = bb.createApplicationContext()

Then you can access the maxSize and productGroup properties in your DSL files.

15.4 The BeanBuilder DSL Explained


Using Constructor Arguments

Constructor arguments can be defined using parameters to each bean-defining method. Put them after the first argu
bb.beans { exampleBean(MyExampleBean, "firstArgument", 2) { someProperty = [1, 2, 3] } }

This configuration corresponds to a MyExampleBean with a constructor that looks like this:
MyExampleBean(String foo, int bar) { }

367

Configuring the BeanDefinition (Using factory methods)

The first argument to the closure is a reference to the bean configuration instance, which you can use to configure invoke any method on the AbstractBeanDefinition class:
bb.beans { exampleBean(MyExampleBean) { bean -> bean.factoryMethod = "getInstance" bean.singleton = false someProperty = [1, 2, 3] } }

As an alternative you can also use the return value of the bean defining method to configure the bean:
bb.beans { def example = exampleBean(MyExampleBean) { someProperty = [1, 2, 3] } example.factoryMethod = "getInstance" }

Using Factory beans

Spring defines the concept of factory beans and often a bean is created not directly from a new instance of a C these factories. In this case the bean has no Class argument and instead you must pass the name of the factory bean method:
bb.beans { myFactory(ExampleFactoryBean) { someProperty = [1, 2, 3] } myBean(myFactory) { name = "blah" } }

Another common approach is provide the name of the factory method to call on the factory bean. This can be named parameter syntax:
bb.beans { myFactory(ExampleFactoryBean) { someProperty = [1, 2, 3] } myBean(myFactory: "getInstance") { name = "blah" } }

368

Here the getInstance method on the ExampleFactoryBean bean will be called to create the myBean bea

Creating Bean References at Runtime

Sometimes you don't know the name of the bean to be created until runtime. In this case you can use a string inte bean defining method dynamically:
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1, 2, 3] } }

In this case the beanName variable defined earlier is used when invoking a bean defining method. The exam value but would work just as well with a name that is generated programmatically based on configuration, system

Furthermore, because sometimes bean names are not known until runtime you may need to reference them b together other beans, in this case using the ref method:
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1, 2, 3] } anotherBean(AnotherBean) { example = ref("${beanName}Bean") } }

Here the example property of AnotherBean is set using a runtime reference to the exampleBean. The ref used to refer to beans from a parent ApplicationContext that is provided in the constructor of the BeanBui
ApplicationContext parent = ...// der bb = new BeanBuilder(parent) bb.beans { anotherBean(AnotherBean) { example = ref("${beanName}Bean", true) } }

Here the second parameter true specifies that the reference will look for the bean in the parent context.

Using Anonymous (Inner) Beans


You can use anonymous inner beans by setting a property of the bean to a block that takes an argument that is the

369

bb.beans { marge(Person) { name = "Marge" husband = { Person p -> name = "Homer" age = 45 props = [overweight: true, height: "1.8m"] } children = [bart, lisa] } bart(Person) { name = "Bart" age = 11 } lisa(Person) { name = "Lisa" age = 9 } }

In the above example we set the marge bean's husband property to a block that creates an inner bean reference have a factory bean you can omit the type and just use the specified bean definition instead to setup the factory:
bb.beans { personFactory(PersonFactory) marge(Person) { name = "Marge" husband = { bean -> bean.factoryBean = "personFactory" bean.factoryMethod = "newInstance" name = "Homer" age = 45 props = [overweight: true, height: "1.8m"] } children = [bart, lisa] } }

Abstract Beans and Parent Bean Definitions


To create an abstract bean definition define a bean without a Class parameter:
class HolyGrailQuest { def start() { println "lets begin" } }

370

class KnightOfTheRoundTable { String name String leader HolyGrailQuest quest KnightOfTheRoundTable(String name) { this.name = name } def embarkOnQuest() { quest.start() } }

import grails.spring.BeanBuilder def bb = new BeanBuilder() bb.beans { abstractBean { leader = "Lancelot" } }

Here we define an abstract bean that has a leader property with the value of "Lancelot". To use the abst parent of the child bean:
bb.beans { quest(HolyGrailQuest) knights(KnightOfTheRoundTable, "Camelot") { bean -> bean.parent = abstractBean quest = ref('quest') } }

When using a parent bean you must set the parent property of the bean before setting any other pro on the bean! If you want an abstract bean that has a Class specified you can do it this way:

371

import grails.spring.BeanBuilder def bb = new BeanBuilder() bb.beans { abstractBean(KnightOfTheRoundTable) { bean -> bean.'abstract' = true leader = "Lancelot" } quest(HolyGrailQuest) knights("Camelot") { bean -> bean.parent = abstractBean quest = quest } }

In this example we create an abstract bean of type KnightOfTheRoundTable and use the bean argument to s we define a knights bean that has no Class defined, but inherits the Class from the parent bean.

Using Spring Namespaces


Since Spring 2.0, users of Spring have had easier access to key features via XML namespaces. You can use a BeanBuilder by declaring it with this syntax:
xmlns context:"http://www.springframework.org/schema/context"

and then invoking a method that matches the names of the Spring namespace tag and its associated attributes:
context.'component-scan'('base-package': "my.company.domain")

You can do some useful things with Spring namespaces, such as looking up a JNDI resource:
xmlns jee:"http://www.springframework.org/schema/jee" jee.'jndi-lookup'(id: "dataSource", 'jndi-name': "java:comp/env/myDataSource")

This example will create a Spring bean with the identifier dataSource by performing a JNDI lookup on the giv Spring namespaces you also get full access to all of the powerful AOP support in Spring from BeanBuilder. For two classes:
class Person { int age String name void birthday() { ++age; } }

372

class BirthdayCardSender { List peopleSentCards = [] void onBirthday(Person person) { peopleSentCards << person } }

You can define an aspect that uses a pointcut to detect whenever the birthday() method is called:
xmlns aop:"http://www.springframework.org/schema/aop" fred(Person) { name = "Fred" age = 45 } birthdayCardSenderAspect(BirthdayCardSender) aop { config("proxy-target-class": true) { aspect(id: "sendBirthdayCard", ref: "birthdayCardSenderAspect") { after method: "onBirthday", pointcut: "execution(void ..Person.birthday()) and this(person)" } } }

15.5 Property Placeholder Configuration

Grails supports the notion of property placeholder configuration through an extended vers PropertyPlaceholderConfigurer, which is typically useful in combination with externalized configuration.

Settings defined in either ConfigSlurper scripts or Java properties files can be used as placeholder values for Sp grails-app/conf/spring/resources.xml and grails-app/conf/spring/resources.gr given the following entries in grails-app/conf/Config.groovy (or an externalized config):
database.driver="com.mysql.jdbc.Driver" database.dbname="mysql:mydb"

You can then specify placeholders in resources.xml as follows using the familiar ${..} syntax:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.driver}</value> </property> <property name="url"> <value>jdbc:${database.dbname}</value> </property> </bean>

To specify placeholders in resources.groovy you need to use single quotes:

373

dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) { driverClassName = '${database.driver}' url = 'jdbc:${database.dbname}' }

This sets the property value to a literal string which is later resolved against the config by Spring's PropertyPlaceh A better option for resources.groovy is to access properties through the grailsApplication variable:
dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) { driverClassName = grailsApplication.config.database.driver url = "jdbc:${grailsApplication.config.database.dbname}" }

Using this approach will keep the types as defined in your config.

15.6 Property Override Configuration

Grails supports setting of bean properties via configuration. This is often useful when used in combinatio configuration. You define a beans block with the names of beans and their values:
beans { bookService { webServiceURL = "http://www.amazon.com" } }

The general format is:


[bean name].[property name] = [value]

The same configuration in a Java properties file would be:


beans.bookService.webServiceURL=http://www.amazon.com

374

16 Grails and Hibernate

If GORM (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map using Hibernate, either with XML mapping files or JPA annotations. You will be able to map Grails domain class of legacy systems and have more flexibility in the creation of your database schema. Best of all, you will still be dynamic persistent and query methods provided by GORM!

16.1 Using Hibernate XML Mapping Files

Mapping your domain classes with XML is pretty straightforward. Simply create a hibernate.cfg.xml f grails-app/conf/hibernate directory, either manually or with the create-hibernate-cfg-xml comma following:
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Example mapping file inclusion --> <mapping resource="org.example.Book.hbm.xml"/> </session-factory> </hibernate-configuration>

The individual mapping files, like 'org.example.Book.hbm.xml' in the above example, als grails-app/conf/hibernate directory. To find out how to map domain classes with XML, check out the

If the default location of the hibernate.cfg.xml file doesn't suit you, you can change it by specifying an a grails-app/conf/DataSource.groovy:
hibernate { config.location = "file:/path/to/my/hibernate.cfg.xml" }

or even a list of locations:


hibernate { config.location = ["file:/path/to/one/hibernate.cfg.xml", "file:/path/to/two/hibernate.cfg.xml"] }

Grails also lets you write your domain model in Java or reuse an existing one that already has Hibernate mappin the mapping files into grails-app/conf/hibernate and either put the Java files in src/java or the cl lib directory if the domain model is packaged as a JAR. You still need the hibernate.cfg.xml though!

16.2 Mapping with Hibernate Annotations

To map a domain class with annotations, create a new class in src/java and use the annotations defined as par (for more info on this see the Hibernate Annotations Docs):

375

package com.books; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Book { private Long id; private String title; private String description; private Date date; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }

Then register the class with the Hibernate sessionFactory grails-app/conf/hibernate/hibernate.cfg.xml file as follows:

by

adding

relevant

<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping package="com.books" /> <mapping class="com.books.Book" /> </session-factory> </hibernate-configuration>

See the previous section for more information on the hibernate.cfg.xml file.

When Grails loads it will register the necessary dynamic methods with the class. To see what else you can do wit class see the section on Scaffolding.

16.3 Adding Constraints

You can still use GORM validation even if you use a Java domain model. Grails lets you define constraints throu the src/java directory. The script must be in a directory that matches the package of the corresponding doma must have a Constraints suffix. For example, if you had a domain class org.example.Book, then you wo src/java/org/example/BookConstraints.groovy.

376

Add a standard GORM constraints block to the script:


constraints = { title blank: false author blank: false }

Once this is in place you can validate instances of your domain class!

377

17 Scaffolding
Scaffolding lets you auto-generate a whole application for a given domain class including: The necessary views Controller actions for create/read/update/delete (CRUD) operations

Dynamic Scaffolding

The simplest way to get started with scaffolding is to enable it with the scaffold property. Set the scaff controller to true for the Book domain class:
class BookController { static scaffold = true }

This works because the BookController follows the same naming convention as the Book domain class. T domain class we could reference the class directly in the scaffold property:
class SomeController { static scaffold = Author }

With this configured, when you start your application the actions and views will be auto-generated at runtime. T are dynamically implemented by default by the runtime scaffolding mechanism: list show edit delete create save update

A CRUD interface will also be generated. To access this open http://localhost:8080/app/book in a br

If you prefer to keep your domain model in Java and mapped with Hibernate you can still use scaffolding, simp class and set its name as the scaffold argument. You can add new actions to a scaffolded controller, for example:

378

class BookController { static scaffold = Book def changeAuthor() { def b = Book.get(params.id) b.author = Author.get(params["author.id"]) b.save() // redirect to a scaffolded action redirect(action:show) } }

You can also override the scaffolded actions:


class BookController { static scaffold = Book // overrides scaffolded action to return both authors and books def list() { [bookInstanceList: Book.list(), bookInstanceTotal: Book.count(), authorInstanceList: Author.list()] } def show() { def book = Book.get(params.id) log.error(book) [bookInstance : book] } }

All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runti

By default, the size of text areas in scaffolded views is defined in the CSS, so adding 'rows' an attributes will have no effect.

Also, the standard scaffold views expect model variables of the form <propertyName>Instance for collections and <propertyName>Instance for single instances. It's tempting to use propert 'books' and 'book', but those won't work.

Customizing the Generated Views

The views adapt to Validation constraints. For example you can change the order that fields appear in the views s the constraints in the builder:
def constraints = { title() releaseDate() }

You can also get the generator to generate lists instead of text inputs if you use the inList constraint:

379

def constraints = { title() category(inList: ["Fiction", "Non-fiction", "Biography"]) releaseDate() }

Or if you use the range constraint on a number:


def constraints = { age(range:18..65) }

Restricting the size with a constraint also effects how many characters can be entered in the generated view:
def constraints = { name(size:0..30) }

Static Scaffolding
Grails also supports "static" scaffolding.

The above scaffolding features are useful but in real world situations it's likely that you will want to customize Grails lets you generate a controller and the views used to create the above interface from the command line. To type:
grails generate-controller Book

or to generate the views:


grails generate-views Book

or to generate everything:
grails generate-all Book

If you have a domain class in a package or are generating from a Hibernate mapped class remember to includ package name:
grails generate-all com.bookstore.Book

380

Customizing the Scaffolding templates


The templates used by Grails to generate the controller and views can be customized by installing the install-templates command.

381

18 Deployment
Grails applications can be deployed in a number of ways, each of which has its pros and cons.

"grails run-app"

You should be very familiar with this approach by now, since it is the most common method of running an a development phase. An embedded Tomcat server is launched that loads the web application from the develo allowing it to pick up an changes to application files.

This approach is not recommended at all for production deployment because the performance is poor. Chec changes places a sizable overhead on the server. Having said that, grails prod run-app removes the perlets you fine tune how frequently the regular check takes place.

Setting the system property "disable.auto.recompile" to true disables this regular check completely, "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you check. The default is currently 3.

"grails run-war"

This is very similar to the previous option, but Tomcat runs against the packaged WAR file rather than the d Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsew

WAR file

When it comes down to it, current java infrastructures almost mandate that web applications are deployed as WA far the most common approach to Grails application deployment in production. Creating a WAR file is as simple command:
grails war

There are also many ways in which you can customise the WAR file that is created. For example, you can s absolute or relative) to the command that instructs it where to place the file and what name to give it:
grails war /opt/java/tomcat-5.5.24/foobar.war

Alternatively, you can add a line to grails-app/conf/BuildConfig.groovy that changes the default loc
grails.project.war.file = "foobar-prod.war"

Any command line argument that you provide overrides this setting.

382

It is also possible to control what libraries are included in the WAR file, for example to avoid conflicts with directory. The default behavior is to include in the WAR file all libraries required by Grails, plus any libraries con directories, plus any libraries contained in the application's "lib" directory. As an alternative to the default behav specify the complete list of libraries to include in the WAR file by setting the property grails.war. BuildConfig.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is inclu pattern assigned to the latter property will be included in addition to grails.war.dependencies. Be careful with these properties: if any of the libraries Grails depends on are missing, the application will almost an example that includes a small subset of the standard Grails dependencies:
def deps = [ "hibernate3.jar", "groovy-all-*.jar", "standard-${servletVersion}.jar", "jstl-${servletVersion}.jar", "oscache-*.jar", "commons-logging-*.jar", "sitemesh-*.jar", "spring-*.jar", "log4j-*.jar", "ognl-*.jar", "commons-*.jar", "xstream-1.2.1.jar", "xpp3_min-1.1.3.4.O.jar" ] grails.war.dependencies = { fileset(dir: "libs") { for (pattern in deps) { include(name: pattern) } } }

This example only exists to demonstrate the syntax for the properties. If you attempt to use it as is in your application will probably not work. You can find a list of dependencies required by Grails in the "dependencie directory of the unpacked distribution. You can also find a list of the default dependencies included in WA "War.groovy" script - see the DEFAULT_DEPS and DEFAULT_J5_DEPS variables.

The remaining two configuration options available to you are grails.war.copyToWebApp and grails The first of these lets you customise what files are included in the WAR file from the "web-app" directory. The se extra processing you want before the WAR file is finally created.
// This closure is passed the command line arguments used to start the // war process. grails.war.copyToWebApp = { args -> fileset(dir:"web-app") { include(name: "js/**") include(name: "css/**") include(name: "WEB-INF/**") } } // This closure is passed the location of the staging directory that // is zipped up to make the WAR file, and the command line arguments. // Here we override the standard web.xml with our own. grails.war.resources = { stagingDir, args -> copy(file: "grails-app/conf/custom-web.xml", tofile: "${stagingDir}/WEB-INF/web.xml") }

383

Application servers

Ideally you should be able to simply drop a WAR file created by Grails into any application server and it should However, things are rarely ever this simple. The Grails website contains an up-to-date list of application servers tested with, along with any additional steps required to get a Grails WAR file working.

384

19 Contributing to Grails

Grails is an open source project with an active community and we rely heavily on that community to help make G there are various ways in which people can contribute to Grails. One of these is by writing useful plugins and m available. In this chapter, we'll look at some fo the other options.

19.1 Report Issues in JIRA

Grails uses JIRA to track issues in the core framework, its documentation, its website, and many of the public plu a bug or wish to see a particular feature added, this is the place to start. You'll need to create a (free) JIRA acco submit an issue or comment on an existing one.

When submitting issues, please provide as much information as possible and in the case of bugs, make sure you ex of Grails and various plugins you are using. Also, an issue is much more likely to be dealt with if you attach a application (which can be packaged up using the grails bug-report command).

Reviewing issues
There are quite a few old issues in JIRA, some of which may no longer be valid. The core team can't track down simple contribution that you can make is to verify one or two issues occasionally.

Which issues need verification? A shared JIRA filter will display all issues that haven't been resolved and have someone else in the last 6 months. Just pick one or two of them and check whether they are still relevant.

Once you've verified an issue, simply edit it and set the "Last Reviewed" field to today. If you think the issue can check the "Flagged" field and add a short comment explaining why. Once those changes are saved, the issue wi results of the above filter. If you've flagged it, the core team will review and close if it really is no longer relevant.

One last thing: you can easily set the above filter as a favourite on this JIRA screen so that it appears in the "Iss click on the star next to a filter to make it a favourite.

19.2 Build From Source and Run Tests

If you're interested in contributing fixes and features to the core framework, you will have to learn how to get source, build it and test it with your own applications. Before you start, make sure you have: A JDK (1.6 or above) A git client

Once you have all the pre-requisite packages installed, the next step is to download the Grails source code, whic in several repositories owned by the "grails" GitHub user. This is a simple case of cloning the repository you example, to getthe core framework run:
git clone http://github.com/grails/grails-core.git

This will create a "grails-core" directory in your current working directory containing all the project source files. T a Grails installation from the source.

Creating a Grails installation


385

If you look at the project structure, you'll see that it doesn't look much like a standard GRAILS_HOME installation to turn it into one. Just run this from the root directory of the project:
./gradlew install

This will fetch all the standard dependencies required by Grails and then build a GRAILS_HOME installation. Not the extensive collection of Grails test classes, which can take some time to complete.

Once the above command has finished, simply set the GRAILS_HOME environment variable to the checkout d "bin" directory to your path. When you next type run the grails command, you'll be using the version you just b

Running the test suite


All you have to do to run the full suite of tests is:
./gradlew test

These will take a while (15-30 mins), so consider running individual tests using the command line. For example MappingDslTests simply execute the following command:
./gradlew -Dtest.single=MappingDslTest :grails-test-suite-persistence:test

Note that you need to specify the sub-project that the test case resides in, because the top-level "test" target won't w

Developing in IntelliJ IDEA


You need to run the following gradle task:
./gradlew idea

Then open the project file which is generated in IDEA. Simple!

Developing in STS / Eclipse


You need to run the following gradle task:
./gradlew cleanEclipse eclipse

Before importing projects to STS do the following action: Edit grails-scripts/.classpath and remove the line "<classpathentry kind="src" path="../scripts"/>".

Use "Import->General->Existing Projects into Workspace" to import all projects to STS. There will be a few bui do the following: 386

Add the springloaded-core JAR file in $GRAILS_HOME/lib/com.springsource.springloaded/sprin grails-core's classpath. Remove "src/test/groovy" from grails-plugin-testing's source path GRECLIPSE-1067 Add the jsp-api JAR file in $GRAILS_HOME/lib/javax.servlet.jsp/jsp-api/jars to the classpath of grails-web

Fix the source path of grails-scripts. Add linked source folder linking to "../scripts". If you get build error "../gradlew cleanEclipse eclipse" in that directory and edit the .classpath file again (remove the line "<class path="../scripts"/>"). Remove possible empty "scripts" directory under grails-scripts if you are not able to add Do a clean build for the whole workspace.

To use Eclipse GIT scm team provider: Select all projects (except "Servers") in the navigation and right cli project (not "Share projects"). Choose "Git". Then check "Use or create repository in parent folder of project"

Get the recommended code style settings from the mailing list thread (final style not decided yet, currently the code style xml file to STS in Window->Preferences->Java->Code Style->Formatter->Import . Grails cod of tabs for indenting.

Debugging Grails or a Grails application


To enable debugging, run:
grails -debug <command>

and then connect to the JVM remotely via the IDE ("remote debugging") using the port 5005. Of course, if yo startGrails script to use a different port number, connect using that one.

In previous versions of Grails there was a grails-debug command. The command is still included distribution and is deprecated in favor of the -debug switch to the standard grails command.

If you need to debug stuff that happens during application startup, then you should modify the "grails-debug" s "suspend" option from 'n' to 'y'. You can read more about the JPDA connection settin http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#Invocation.

It's also possible to get Eclipse to wait for incoming debugger connections and "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005" you could "-Xrunjdwp:transport=dt_socket,server=n,address=8000" (which assumes the Eclipse default port for remote jav eclipse you create a new "Remote Java Application" launch configuration and change the connection type t Listen)" and click debug. This allows you to start a debugger session in eclipse and just leave it running and anything without having to keep remembering to relaunch a "Socket Attach" launch configuration. You might fi scripts, one called "grails-debug", and another called "grails-debug-attach"

19.3 Submit Patches to Grails Core

If you want to submit patches to the project, you simply need to fork the repository on GitHub rather than clone will commit your changes to your fork and send a pull request for a core team member to review.

Forking and Pull Requests


387

One of the benefits of GitHub is the way that you can easily contribute to a project by forking the repository and with your changes. What follows are some guidelines to help ensure that your pull requests are speedily dealt with and provide the They will also make your life easier!

Create a local branch for your changes

Your life will be greatly simplified if you create a local branch to make your changes on. For example, as soon as and clone the fork locally, execute
git checkout -b mine

This will create a new local branch called "mine" based off the "master" branch. Of course, you can name the bran - you don't have to use "mine".

Create JIRAs for non-trivial changes

For any non-trivial changes, raise a JIRA issue if one doesn't already exist. That helps us keep track of what chan version of Grails.

Include JIRA issue ID in commit messages

This may not seem particularly important, but having a JIRA issue ID in a commit message means that we can f why a change was made. Include the ID in any and all commits that relate to that issue. If a commit isn't related to no need to include an issue ID.

Make sure your fork is up to date

Since the core developers must merge your commits into the main repository, it makes life much easier if your fo date before you send a pull request.

Let's say you have the main repository set up as a remote called "upstream" and you want to submit a pull re changes are currently on the local "mine" branch but not on "master". The first step involves pulling any ch repository that have been added since you last fetched and merged:
git checkout master git pull upstream

This should complete without any problems or conflicts. Next, rebase your local branch against the now up-to-date
git checkout mine git rebase master

What this does is rearrange the commits such that all of your changes come after the most recent one in master cards to the top of a deck rather than shuffling them into the pack. You'll now be able to do a clean merge from your local branch to master:

388

git checkout master git merge mine

Finally, you must push your changes to your remote repository on GitHub, otherwise the core developers won't up:
git push

You're now ready to send the pull request from the GitHub user interface.

Say what your pull request is for

A pull request can contain any number of commits and it may be related to any number of issues. In the pull req specify the IDs of all issues that the request relates to. Also give a brief description of the work you have done, the data binder and added support for custom number editors (GRAILS-xxxx)".

19.4 Submit Patches to Grails Documentation

Contributing to the documentation is simpler for the core framework because there is a pu http://github.com/grails/grails-doc project that anyone can request commit access to. So, if you want to su documentation, simply request commit access to the following repository http://github.com/pledbrook/grails-doc message to 'pledbrook' and then commit your patches just as you would to any other GitHub repository.

Building the Guide


To build the documentation, simply type:
./gradlew docs

Be warned: this command can take a while to complete and you should probably increase your Gradle memory s GRADLE_OPTS environment variable a value like
export GRADLE_OPTS="-Xmx512m -XX:MaxPermSize=384m"

Fortunately, you can reduce the overall build time with a couple of useful options. The first allows you to speci Grails source to use:
./gradlew -Dgrails.home=/home/user/projects/grails-core docs

The Grails source is required because the guide links to its API documentation and the build needs to ensure it's g specify a grails.home property, then the build will fetch the Grails source - a download of 10s of megabytes. the Grails source which can take a while too. Additionally you can create a local.properties file with this variable set:

389

grails.home=/home/user/projects/grails-core

or
grails.home=../grails-core

The other useful option allows you to disable the generation of the API documentation, since you only need to do
./gradlew -Ddisable.groovydocs=true docs

Again, this can save a significant amount of time and memory.

The main English user guide is generated in the build/docs directory, with the guide sub-directory containin and the ref folder containing the reference material. To view the user guide, simply open build/docs/index

Publishing

The publishing system for the user guide is the same as the one for Grails projects. You write your chapters and wiki format which is then converted to HTML for the final guide. Each chapter is a top-level gdoc file in the sr directory. Sections and sub-sections then go into directories with the same name as the chapter gdoc but without th The structure of the user guide is defined in the src/<lang>/guide/toc.yml file, which is a YAML file. the (language-specific) section titles. If you add or remove a gdoc file, you must update the TOC as well!

The src/<lang>/ref directory contains the source for the reference sidebar. Each directory is the name of a appears in the docs. Hence the directories need different names for the different languages. Inside the director whose names match the names of the methods, commands, properties or whatever that the files describe.

Translations

This project can host multiple translations of the user guide, with src/en being the main one. To add another new language directory under src and copy into it all the files under src/en. The build will take care of the rest

Once you have a copy of the original guide, you can use the {hidden} macro to wrap the English text that you than remove it. This makes it easier to compare changes to the English guide against your translation. For example
{hidden} When you create a Grails application with the [create-app|commandLine] command, Grails doesn't automatically create an Ant build.xml file but you can generate one with the [integrate-with|commandLine] command: {hidden} Quando crias uma aplicao Grails com o comando [create-app|commandLine], Grails no cria automaticamente um ficheiro de construo Ant build.xml mas podes gerar um com o comando [integrate-with|commandLine]:

390

Because the English text remains in your gdoc files, diff will show differences on the English lines. You can th diff to see which bits of your translation need updating. On top of that, the {hidden} macro ensures that th displayed in the browser, although you can display it by adding this URL as a bookmark: javascript:t (requires you to build the user guide with Grails 2.0 M2 or later).

Even better, you can use the left_to_do.groovy script in the root of the project to see what still needs trans so:
./left_to_do.groovy es

This will then print out a recursive diff of the given translation against the reference English user guide. Any blocks that hasn't changed since being translated will not appear in the diff output. In other words, all you will see been translated yet and content that has changed since it was translated. Note that {code} blocks are ignored, include them inside {hidden} macros.

To provide translations for the headers, such as the user guide title and subtitle, just add language sp 'resources/doc.properties' file like so:
es.title=El Grails Framework es.subtitle=...

For each language translation, properties beginning <lang>. will override the standard ones. In the above examp will be El Grails Framework for the Spanish translation. Also, translators can be credited by adding a '<lang>.trans
fr.translators=Stphane Maldini

This should be a comma-separated list of names (or the native language equivalent) and it will be displayed as a "T in the user guide itself.

You can build specific translations very easily using the publishGuide_* and publishPdf_* tasks. For e the French HTML and PDF user guides, simply execute
./gradlew publishPdf_fr

Each translation is generated in its own directory, so for example the French guide will end up in build/doc view the translated guide by opening build/docs/<lang>/index.html.

All translations are created as part of the Hudson CI build for the grails-doc project, so you can easily see wh without having to build the docs yourself.

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. Sponsored by SpringSource

391

You might also like