Grails Users Guide
Grails Users Guide
Table of Contents
1 Introduction 1.1 What's new in Grails 2.0? 1.1.1 Development Environment Features 1.1.2 Core Features 1.1.3 Web Features 1.1.4 Persistence Features 1.1.5 Testing Features 2 Getting Started 2.1 Installation Requirements 2.2 Downloading and Installing 2.3 Upgrading from previous versions of Grails 2.4 Creating an Application 2.5 A Hello World Example 2.6 Using Interactive Mode 2.7 Getting Set Up in an IDE 2.8 Convention over Configuration 2.9 Running an Application 2.10 Testing an Application 2.11 Deploying an Application 2.12 Supported Java EE Containers 2.13 Generating an Application 2.14 Creating Artefacts 3 Configuration 3.1 Basic Configuration 3.1.1 Built in options 3.1.2 Logging
3.1.3 GORM 3.2 Environments 3.3 The DataSource 3.3.1 DataSources and Environments 3.3.2 JNDI DataSources 3.3.3 Automatic Database Migration 3.3.4 Transaction-aware DataSource Proxy 3.3.5 Database Console 3.3.6 Multiple Datasources 3.4 Externalized Configuration 3.5 Versioning 3.6 Project Documentation 3.7 Dependency Resolution 3.7.1 Configurations and Dependencies 3.7.2 Dependency Repositories 3.7.3 Debugging Resolution 3.7.4 Inherited Dependencies 3.7.5 Providing Default Dependencies 3.7.6 Snapshots and Other Changing Dependencies 3.7.7 Dependency Reports 3.7.8 Plugin JAR Dependencies 3.7.9 Maven Integration 3.7.10 Deploying to a Maven Repository 3.7.11 Plugin Dependencies 4 The Command Line 4.1 Interactive Mode 4.2 Creating Gant Scripts 4.3 Re-using Grails scripts 4.4 Hooking into Events 4.5 Customising the build 4.6 Ant and Maven 5 Object Relational Mapping (GORM) 5.1 Quick Start Guide 5.1.1 Basic CRUD 5.2 Domain Modelling in GORM 5.2.1 Association in GORM 5.2.1.1 Many-to-one and one-to-one 2
5.2.1.2 One-to-many 5.2.1.3 Many-to-many 5.2.1.4 Basic Collection Types 5.2.2 Composition in GORM 5.2.3 Inheritance in GORM 5.2.4 Sets, Lists and Maps 5.3 Persistence Basics 5.3.1 Saving and Updating 5.3.2 Deleting Objects 5.3.3 Understanding Cascading Updates and Deletes 5.3.4 Eager and Lazy Fetching 5.3.5 Pessimistic and Optimistic Locking 5.3.6 Modification Checking 5.4 Querying with GORM 5.4.1 Dynamic Finders 5.4.2 Where Queries 5.4.3 Criteria 5.4.4 Detached Criteria 5.4.5 Hibernate Query Language (HQL) 5.5 Advanced GORM Features 5.5.1 Events and Auto Timestamping 5.5.2 Custom ORM Mapping 5.5.2.1 Table and Column Names 5.5.2.2 Caching Strategy 5.5.2.3 Inheritance Strategies 5.5.2.4 Custom Database Identity 5.5.2.5 Composite Primary Keys 5.5.2.6 Database Indices 5.5.2.7 Optimistic Locking and Versioning 5.5.2.8 Eager and Lazy Fetching 5.5.2.9 Custom Cascade Behaviour 5.5.2.10 Custom Hibernate Types 5.5.2.11 Derived Properties 5.5.2.12 Custom Naming Strategy 5.5.3 Default Sort Order 5.6 Programmatic Transactions 5.7 GORM and Constraints 3
6 The Web Layer 6.1 Controllers 6.1.1 Understanding Controllers and Actions 6.1.2 Controllers and Scopes 6.1.3 Models and Views 6.1.4 Redirects and Chaining 6.1.5 Controller Interceptors 6.1.6 Data Binding 6.1.7 XML and JSON Responses 6.1.8 More on JSONBuilder 6.1.9 Uploading Files 6.1.10 Command Objects 6.1.11 Handling Duplicate Form Submissions 6.1.12 Simple Type Converters 6.1.13 Asynchronous Request Processing 6.2 Groovy Server Pages 6.2.1 GSP Basics 6.2.1.1 Variables and Scopes 6.2.1.2 Logic and Iteration 6.2.1.3 Page Directives 6.2.1.4 Expressions 6.2.2 GSP Tags 6.2.2.1 Variables and Scopes 6.2.2.2 Logic and Iteration 6.2.2.3 Search and Filtering 6.2.2.4 Links and Resources 6.2.2.5 Forms and Fields 6.2.2.6 Tags as Method Calls 6.2.3 Views and Templates 6.2.4 Layouts with Sitemesh 6.2.5 Static Resources 6.2.5.1 Including resources using the resource tags 6.2.5.2 Other resource tags 6.2.5.3 Declaring resources 6.2.5.4 Overriding plugin resources 6.2.5.5 Optimizing your resources 6.2.5.6 Debugging 4
6.2.5.7 Preventing processing of resources 6.2.5.8 Other Resources-aware plugins 6.2.6 Sitemesh Content Blocks 6.2.7 Making Changes to a Deployed Application 6.2.8 GSP Debugging 6.3 Tag Libraries 6.3.1 Variables and Scopes 6.3.2 Simple Tags 6.3.3 Logical Tags 6.3.4 Iterative Tags 6.3.5 Tag Namespaces 6.3.6 Using JSP Tag Libraries 6.3.7 Tag return value 6.4 URL Mappings 6.4.1 Mapping to Controllers and Actions 6.4.2 Embedded Variables 6.4.3 Mapping to Views 6.4.4 Mapping to Response Codes 6.4.5 Mapping to HTTP methods 6.4.6 Mapping Wildcards 6.4.7 Automatic Link Re-Writing 6.4.8 Applying Constraints 6.4.9 Named URL Mappings 6.4.10 Customizing URL Formats 6.5 Web Flow 6.5.1 Start and End States 6.5.2 Action States and View States 6.5.3 Flow Execution Events 6.5.4 Flow Scopes 6.5.5 Data Binding and Validation 6.5.6 Subflows and Conversations 6.6 Filters 6.6.1 Applying Filters 6.6.2 Filter Types 6.6.3 Variables and Scopes 6.6.4 Filter Dependencies 6.7 Ajax 5
6.7.1 Ajax Support 6.7.1.1 Remoting Linking 6.7.1.2 Updating Content 6.7.1.3 Remote Form Submission 6.7.1.4 Ajax Events 6.7.2 Ajax with Prototype 6.7.3 Ajax with Dojo 6.7.4 Ajax with GWT 6.7.5 Ajax on the Server 6.8 Content Negotiation 7 Validation 7.1 Declaring Constraints 7.2 Validating Constraints 7.3 Validation on the Client 7.4 Validation and Internationalization 7.5 Validation Non Domain and Command Object Classes 8 The Service Layer 8.1 Declarative Transactions 8.1.1 Transactions Rollback and the Session 8.2 Scoped Services 8.3 Dependency Injection and Services 8.4 Using Services from Java 9 Testing 9.1 Unit Testing 9.1.1 Unit Testing Controllers 9.1.2 Unit Testing Tag Libraries 9.1.3 Unit Testing Domains 9.1.4 Unit Testing Filters 9.1.5 Unit Testing URL Mappings 9.1.6 Mocking Collaborators 9.2 Integration Testing 9.3 Functional Testing 10 Internationalization 10.1 Understanding Message Bundles 10.2 Changing Locales 10.3 Reading Messages 10.4 Scaffolding and i18n 6
11 Security 11.1 Securing Against Attacks 11.2 Encoding and Decoding Objects 11.3 Authentication 11.4 Security Plugins 11.4.1 Spring Security 11.4.2 Shiro 12 Plugins 12.1 Creating and Installing Plugins 12.2 Plugin Repositories 12.3 Understanding a Plugin's Structure 12.4 Providing Basic Artefacts 12.5 Evaluating Conventions 12.6 Hooking into Build Events 12.7 Hooking into Runtime Configuration 12.8 Adding Dynamic Methods at Runtime 12.9 Participating in Auto Reload Events 12.10 Understanding Plugin Load Order 12.11 The Artefact API 12.11.1 Asking About Available Artefacts 12.11.2 Adding Your Own Artefact Types 12.12 Binary Plugins 13 Web Services 13.1 REST 13.2 SOAP 13.3 RSS and Atom 14 Grails and Spring 14.1 The Underpinnings of Grails 14.2 Configuring Additional Beans 14.3 Runtime Spring with the Beans DSL 14.4 The BeanBuilder DSL Explained 14.5 Property Placeholder Configuration 14.6 Property Override Configuration 15 Grails and Hibernate 15.1 Using Hibernate XML Mapping Files 15.2 Mapping with Hibernate Annotations 15.3 Adding Constraints 7
16 Scaffolding 17 Deployment 18 Contributing to Grails 18.1 Report Issues in JIRA 18.2 Build From Source and Run Tests 18.3 Submit Patches to Grails Core 18.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 web frameworks in the 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 thinking about web applications. Grails builds on these concepts and dramatically reduces the complexity of building web applications on the Java platform. What makes it different, however, is that it does so by building on already established Java technologies like Spring and Hibernate. Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and 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 Specific Languages (DSLs) This documentation will take you through getting started with Grails and building web applications with the Grails framework.
In general Grails makes its best effort to display update information on a single line and only present the information that is crucial. This means that while in previous versions of Grails the war command produced many lines of output, in Grails 2.0 only 1 line of output is produced:
10
In addition simply typing 'grails' at the command line activates the new interactive mode which features TAB completion, command history and keeps the JVM running to ensure commands execute much quicker than otherwise
11
For more information on the new features of the console refer to the section of the user guide that covers the console and interactive mode.
Reloading Agent
Grails 2.0 reloading mechanism no longer uses class loaders, but instead uses a JVM agent to reload changes to class files. This results in greatly improved reliability when reloading changes and also ensures that the class files stored in disk remain consistent with the class files loaded in memory, which reduces the need to run the clean command.
12
In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails application and plugin documentation:
See the section on the documentation engine for more usage info.
13
In addition stack trace filtering has been further enhanced to display only relevant trace information:
Line | Method ->> 9 | getValue in - - - - - - - - - - - - | 7 | getBookValue in | 886 | runTask . . in | 908 | run in ^ 662 | run . . . . in
14
You can change the ivy cache directory for all projects via settings.groovy
15
grails.dependency.cache.dir = "${userHome}/.ivy2/cache"
It is now possible to completely disable resolution from inherited repositories (repositories defined by other plugins):
grails.project.dependency.resolution = { repositories { inherits false // Whether to inherit repository definitions from plugins } }
Groovy 1.8
Grails 2.0 comes with Groovy 1.8 which includes many new features and enhancements
16
You can define an action that declares arguments for each input and automatically converts the parameters to the appropriate type:
def save(String name, int age) { // remaining }
17
A general purpose LinkGenerator class is now available that is usable anywhere within a Grails application and not just within the context of a controller. For example if you need to generate links in a service or an asynchronous background job outside the scope of a request:
LinkGenerator grailsLinkGenerator def generateLink() { grailsLinkGenerator.link(controller:"book", action:"list") }
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 requests a particular filter should be applied.
filter1(actionExclude: 'log*') { before = { // } } filter2(controllerExclude: 'auth') { before = { // } } filter3(uriExclude: '/secure*') { before = { // } }
18
Performance Improvements
Performance of GSP page rendering has once again been improved by optimizing the GSP compiler to inline method calls where 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 compatibility a Prototype plugin is available. Refer to the documentation on the Prototype plugin for installation instructions.
19
The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named addNumbers in a controller named MathHelperController would be something like /mathHelper/addNumbers. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated URLs assign a value 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 adding an instance of that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NAME. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the 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 in URLs } }
Grails 2.0 features support for DetachedCriteria which are criteria queries that are not associated with any session or connection and 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 has been introduced to 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.
Abstract Inheritance
GORM now supports abstract inheritance trees which means you can define queries and associations linking to abstract classes:
21
abstract class Media { String title } class Book extends Media { } class Album extends Media { } class Account { static hasMany = [purchasedMedia:Media] } .. def allMedia = Media.list()
If multiple datasources are specified for a domain then you can use the name of a particular datasource as a namespace in front of any 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 your database, rollback changes and diff your domain model with the current state of the database.
Hibernate 3.6
Grails 2.0 is now built on Hibernate 3.6 22
Bag Collections
You can now use Hibernate Bags for mapped collections to avoid the memory and performance issues of loading large collections to enforce Set uniqueness or List order. For more information see the section on Sets, Lists and Maps in the user guide.
23
The documentation on testing has also been re-written around this new framework.
24
2 Getting Started
2.1 Installation Requirements
Before installing Grails you will as a minimum need a Java Development Kit (JDK) installed version 1.6 or above and environment variable called JAVA_HOME pointing to the location of this installation. On some platforms (for example OS X) the Java installation is automatically detected. However in many cases you will want to manually configure the location of Java. For example:
export JAVA_HOME=/Library/Java/Home export PATH="$PATH:$JAVA_HOME/bin"
Note that although JDK 1.6 is required to use Grails at development time it is possible to deploy Grails to JDK 1.5 VMs by setting the grails.project.source.level and grails.project.target.level settings to "1.5" in grails-app/conf/BuildConfig.groovy:
grails.project.source.level = 1.5 grails.project.target.level = 1.5
In addition, Grails supports Servlet versions 2.5 and above. If you wish to use newer features of the Servlet API (such as 3.0) you should configure the grails.servlet.version in BuildConfig.groovy appropriately:
grails.servlet.version = "3.0"
On Windows this is done by modifying the Path environment variable under My Computer/Advanced/Environment Variables 25
If Grails is working correctly you should now be able to type grails -version in the terminal window and see output similar to this:
Public methods in controllers will now be treated as actions. If you don't want this, make them protected or private. The new unit testing framework won't work with the old GrailsUnitTestCase class hierarchy. Your old tests will continue 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(), etc. you might want to use alternative mechanisms for output. Domain properties of type java.net.URL may no longer work with your existing data. The serialisation mechanism for them 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 setting (see below) but 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. If you have code that implements any of those APIs, you will need to update it. Problems will typically manifest as compilation errors. The following deprecated classes have been removed: grails.web.JsonBuilder and grails.web.OpenRicoBuilder.
27
Spring 3.1 adds a new bean with the name 'environment'. It's of type Environment (in package org.springframework.core.env) and it will automatically be autowired into properties with the same name. This seems to cause particular problems with domain classes that have an environment property. In this case, adding the method:
void setEnvironment(org.springframework.core.env.Environment env) {}
28
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 properties. HSQLDB's default BLOB size is large and so you typically don't need to specify a maximum size. But H2 defaults to a maximum size of 255 bytes! If you store images in the database, the saves are likely to fail because of this. The easy fix is to add a maxSize constraint to the byte[] 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 BINARY(2097152) by Hibernate.
29
In Grails 1.3.x you would get a BOOK table and the properties from the Sellable class would be stored within the BOOK table. However, in Grails 2.x you will get a SELLABLE table and the default table-per-hierarchy inheritance rules apply with all properties of 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/groovy directory it will no longer be regarded as persistent. 2. Use the database migration plugin to apply the appropriate changes to the database (typically renaming the table to the root abstract class of the inheritance tree).
To resolve this issue, simply install the Prototype plugin in your application. You can also remove the prototype files from your web-app/js/prototype directory if you want.
In this case in Grails 1.3.x and below the response.committed property would return true and the if block will execute. In Grails 2.0 this is no longer the case and you should instead use the new isRedirected() method of the request object:
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 configuration option if it's set. Previous versions of Grails included default values for all the environments, but when upgrading to Grails 2.0 those values more often than not break redirection. So, we recommend you remove the development and test settings for grails.serverURL or replace them with something appropriate for your application.
31
Content Negotiation
As of Grails 2.0 the withFormat method of controllers no longer takes into account the request content type (dictated by the CONTENT_TYPE header), but instead deals exclusively with the response content type (dictated by the ACCEPT header or file extension). This means that if your application has code that relies on reading XML from the request using withFormat this will no 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 } } }
32
1. Remove extends *UnitTestCase and add a @TestFor annotation to the class if you're testing a core artifact (controller, tag lib, domain class, etc.) or @TestMixin(GrailsUnitTestMixin) for non-core artifacts and non-artifact classes. 2. Add @Mock annotation for domain classes that must be mocked and use new MyDomain().save() in place of mockDomain(). 3. Replace references to mockRequest, mockResponse and mockParams with request, response and params. 4. Remove references to renderArgs and use the view and model properties for view rendering, or response.text for all others. 5. Replace references to redirectArgs with response.redirectedUrl. The latter takes into account the URL mappings as is a string URL rather than a map of redirect() arguments. 6. The mockCommandObject() method is no longer needed as Grails automatically detects whether an action requires a command object or not. There are other differences, but these are the main ones. We recommend that you read the chapter on testing thoroughly to understand 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 line, but your IDE may 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.
33
event "StatusUpdate", ["Some message"] event "StatusFinal", ["Some message"] event "StatusError", ["Some message"]
For more control you can use the grailsConsole script variable, which gives you access to an instance of GrailsConsole. In particular, you can log information messages with log() or info(), errors and warnings with error() and warning(), and request user input with userInput().
If you do this, be aware that you may run into problems running Grails 2 and earlier versions of Grails side-by-side. These problems can be avoided by excluding "xml-apis" and "commons-digester" from the inherited global dependencies in Grails 1.3 and earlier projects.
34
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 the above to:
35
In these cases you should check for the java.lang.CharSequence interface, which both String and StreamCharBuffer 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 of Grails. However, if your application depends on the older semantics you can still use the deprecated implementation by setting the following property to 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 objects are persisted. If one of your constraints (such as a custom validator) executes a query then this can cause an additional flush, resulting in a StackOverflowError. For example:
static constraints = { author validator: { a -> assert a != Book.findByTitle("My Book").author } }
36
The above code can lead to a StackOverflowError in Grails 1.2. The solution is to run the query in a new Hibernate session (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 } } }
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 stick to the Grails 1.0.x stream until you are able to upgrade your JDK.
Configuration Changes
1) The setting grails.testing.reports.destDir grails.project.test.reports.dir for consistency. has been renamed to
2) The following settings have been moved from grails-app/conf/Config.groovy to 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 3) The grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baseline (see above). 4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to grails-app/conf/Config.groovy:
grails.views.enable.jsessionid=true
37
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 default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in 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 importing scripts from GRAILS_HOME:
Ant.property(environment:"env") grailsHome = Ant.antProject.properties."env.GRAILS_HOME" includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")
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 work:
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 }
2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything; however you should drop column on the inverse side as it contains duplicate data.
REST Support
Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the parseRequest argument inside a URL mapping:
"/book"(controller:"book",parseRequest:true)
Alternatively, you can use the new resource argument, which enables parsing by default:
"/book"(resource:"book")
This will create a new directory inside the current one that contains the project. Navigate to this directory in your console:
39
cd helloworld
$ cd helloworld $ grails
What we want is a simple page that just prints the message "Hello World!" to the browser. In Grails, whenever you want a new page you just create a new controller action for it. Since we don't yet have a controller, let's create one now with the create-controller command:
Don't forget that in the interactive console, we have auto-completion on command names. So you can type "cre" and then press <tab> to get a list of all create-* commands. Type a few more letters of the command name and then <tab> again to finish. The above command will create a new controller in the grails-app/controllers/helloworld directory called HelloController.groovy. Why the extra helloworld directory? Because in Java land, it's strongly recommended that all classes are placed into packages, so Grails defaults to the application name if you don't provide one. The reference page for 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:
40
The action is simply a method. In this particular case, it calls a special method provided by Grails to render the page. Job done. To see your application in action, you just need to start up a server with another command called run-app:
grails> run-app
This will start an embedded server on port 8080 that hosts your application. You should now be able to access your application at the 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 another server is running on that port. You can easily work around this by running your server on a different port using -Dserver.port=9090 run-app. '9090' is just an example: you can pretty much choose anything within the range 1024 to 49151. The result will look something like this:
This is the Grails intro page which is rendered by the grails-app/view/index.gsp file. It detects the presence of your controllers and provides links to them. You can click on the "HelloController" link to see our custom page containing the text "Hello World!". Voila! You have your first working Grails application.
41
One final thing: a controller can contain many actions, each of which corresponds to a different page (ignoring AJAX at this point). Each page is accessible via a unique URL that is composed from the controller name and the action name: /<appname>/<controller>/<action>. This means you can access the Hello World page via /helloworld/hello/index, where 'hello' is the controller name (remove the 'Controller' suffix from the class name and lower-case the first letter) and 'index' is the action name. But you can also access the page via the same URL without the action name: this is because 'index' is the default action . See the end of the controllers and actions section of the user guide to find out more on default actions.
For more information on the capabilities of interactive mode refer to the section on Interactive Mode in the user guide.
42
Eclipse
We recommend that users of Eclipse looking to develop Grails application take a look at SpringSource Tool Suite, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands. See the STS Integration page for an overview.
NetBeans
NetBeans provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the ability to run Grails applications in the IDE, code completion and integration with the Glassfish server. For an overview of features see the NetBeans 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 Mac has an excellent 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 command from the root of your project:
mate .
43
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.
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
44
More information on the run-app command can be found in the reference guide.
This will produce a WAR file under the target directory which can then be deployed as per your container's instructions. Unlike most scripts which default to the development environment unless overridden, the war command runs in the production 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-reloading at 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 sufficient memory allocation. A good set of VM flags would be:
-server -Xmx512M -XX:MaxPermSize=256m
45
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 issues can be found on the Grails wiki.
46
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.
47
3 Configuration
It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one-off, it is best to get it out the way. With Grails' default settings you can actually develop an application without doing any configuration whatsoever. Grails ships with an embedded servlet container and in-memory H2 database, so there isn't even a database to set up. However, typically you should configure a more robust database at some point and that is described in the following section.
Then later in your application you can access these settings in one of two ways. The most common is from the GrailsApplication object, 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}" } }
The other way involves getting a reference to the ConfigurationHolder class that holds a reference to the configuration object:
import org.codehaus.groovy.grails.commons.* def config = ConfigurationHolder.config assert "world" == config.foo.bar.hello
ConfigurationHolder and ApplicationHolder are deprecated and will be removed in a future version of Grails, so it is highly preferable to access the GrailsApplication and config from the grailsApplication variable.
48
Description Location of the home directory for the account that is running the Grails application. The application name as it appears in application.properties. The application version as it appears in application.properties.
grailsApplication The GrailsApplication instance. So if you want to include the application name and version in a mail footer for example, you could do it like this:
mail.footer = "Sent from ${appName} ${appVersion}"
War generation
grails.project.war.file - Sets the name and location of the WAR file generated by the war command grails.war.dependencies - A closure containing Ant builder syntax or a list of JAR filenames. Lets you customise what libaries are included in the WAR file. grails.war.copyToWebApp - A closure containing Ant builder syntax that is legal inside an Ant copy, for example "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 other other work before building the final WAR file For more information on using these options, see the section on deployment 49
3.1.2 Logging
The Basics
Grails uses its common configuration mechanism to provide the settings for the underlying Log4j log system, so all you have to do is 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:
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.groovy.grails.web.pages', only messages logged at 'error' level and above will be shown. Loggers with names starting with 'org.apache.catalina' logger only show 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) will log a message at the 'error' level. Likewise, log.debug(msg) will log it at 'debug'. Each of the above levels apart from 'off' and 'all' have a 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 determine whether the message gets written out. For example, if you have an 'org.example.domain' logger configured like so:
warn 'org.example.domain'
50
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 only be used in the configuration; you can't log messages at these levels. So if you configure a logger with a level of 'off', then no messages will be written 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 they? Are they shared? 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 Log). These loggers are cached and uniquely identified by name, so if two separate classes use loggers with the same name, those loggers are actually the same instance. 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 type is the type of the artifact, for example 'controller' or 'service, and className is the fully qualified name of the artifact. For example, if you have this 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 isn't an artifact. You can also pass a name to the getLog() method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.
Configuring loggers
You have already seen how to configure loggers in Grails: 51
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 messages sent to them at a level of 'warn' or lower. But is there a logger with this name in the application? No. So why have a configuration for it? Because the above rule applies to any logger whose name begins with 'org.codehaus.groovy.grails.servlet.' as well. For example, the rule applies to both the org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet class and the 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 otherwise be. The most common things that you will want to capture log output from are your controllers, services, and other artifacts. Use the convention mentioned earlier to do that: grails.app.<artifactType>.<className> . In particular the class name must be fully qualifed, i.e. with the package if there is one:
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 useful loggers from Grails internals that you can use, especially when tracking down problems with your application:
52
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 don't have an explicit configuration? Are they simply ignored? The answer lies with the root logger.
The above example configures the root logger to log messages at 'info' level and above to the default console appender. You can also 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 custom 'file' appender. For power users there is an alternative syntax for configuring the root logger: the root org.apache.log4j.Logger instance is passed as an argument to the log4j closure. This lets you work with the logger directly: 53
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 messages to the console. But 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 but not the console? 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. That's the job of the appender, of which there are various types. For example, there is the default one that writes messages to the console, another that writes 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:
As you can see, a single logger may have several appenders attached to it. In a standard Grails configuration, the console appender named 'stdout' is attached to all loggers through the default root logger configuration. But that's the only one. Adding more appenders can be done within an 'appenders' block:
log4j = { appenders { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } }
54
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 the previous example 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 multiple instances of 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 not available in the 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") } }
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 key to one of the log 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 well as any appenders configured for the root logger. To add more than one appender to the logger, then add them to the same level declaration:
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 (myFileAppender) by using a list. 55
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 the last level declared 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. That may be fine in a file, but it makes working at the console difficult. So we configure the console appender to only write out messages at 'info' level or 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 argument is available for all 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 available including: 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:
56
Environment-specific configuration
Since the logging configuration is inside Config.groovy, you can put it inside an environment-specific block. However, there is a problem with this approach: you have to provide the full logging configuration each time you define the log4j setting. In other 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 configuration:
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 definition inside an environment block.
Full stacktraces
When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.
57
When this happens, the full trace is always logged to the StackTrace logger, which by default writes its output to a file called stacktrace.log. As with other loggers though, you can change its behaviour in the configuration. For example if you prefer full 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 written to. An alternative 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:
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 output in the console. Finally, you can completely disable stacktrace filtering by setting the grails.full.stacktrace VM property to true:
grails -Dgrails.full.stacktrace=true run-app
Request parameter logging may be turned off altogether by setting the grails.exceptionresolver.logRequestParameters config property to false. The default value is true when the application is running in DEVELOPMENT mode and false for all other modes.
58
grails.exceptionresolver.logRequestParameters=false
Logger inheritance
Earlier, we mentioned that all loggers inherit from the root logger and that loggers are hierarchical based on '.'-separated terms. What this means is that unless you override a parent setting, a logger retains the level and the appenders configured for that parent. So with 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. What if you only want to log to 'stdout' for a particular logger? Change the 'additivity' for a logger in that case. Additivity simply determines whether a logger inherits the configuration from its parent. If additivity is false, then its not inherited. The default for all loggers is true, i.e. they inherit the configuration. So how do you change this setting? Here's an example:
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 additivity, you must configure the loggers for a named appender. The following syntax will not work:
info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]
59
Stacktraces in general and those generated when using Groovy in particular are quite verbose and contain many stack frames that aren't interesting when diagnosing problems. So Grails uses a implementation of the org.codehaus.groovy.grails.exceptions.StackTraceFilterer interface to filter out irrelevant stack frames. To customize the approach used for filtering, implement that interface in a class in src/groovy or src/java and register it in 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. To customize this, implement the org.codehaus.groovy.grails.exceptions.StackTracePrinter interface in a class in src/groovy or 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 needed. The default implementation is org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter and it's registered as a Spring bean. To use your own implementation, either implement the org.codehaus.groovy.grails.exceptions.StackTraceFilterer directly or subclass ErrorsViewStackTracePrinter and register it in grails-app/conf/spring/resources.groovy as:
import com.yourcompany.yourapp.MyErrorsViewStackTracePrinter beans = { errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter, ref('grailsResourceLocator')) }
60
If you do this, you will get unfiltered, standard Java stacktraces in your log files and you won't be able to use the logging configuration DSL that's just been described. Instead, you will have to use the standard configuration mechanism for the library you choose.
3.1.3 GORM
Grails provides the following GORM configuration options: grails.gorm.failOnError - If set to true, causes the save() method on domain classes to throw a grails.validation.ValidationException if validation fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain 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
grails.gorm.autoFlush = If set to true, causes the merge, save and delete methods to flush the session, replacing the need to explicitly flush using save(flush: true).
3.2 Environments
Per Environment Configuration
Grails supports the concept of per environment configuration. The Config.groovy, DataSource.groovy, and BootStrap.groovy files in the grails-app/conf directory can use per-environment configuration using the syntax provided by ConfigSlurper. As an example consider the following default DataSource definition provided by Grails:
61
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 specifies per environment settings for the dbCreate and url properties of the DataSource.
In addition, there are 3 preset environments known to Grails: dev, prod, and test for development, production and test. 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:
grails -Dgrails.env=UAT run-app
62
import grails.util.Environment ... switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }
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 file located at grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the following settings: 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', 'update' or 'validate' 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 database. See the org.hibernate.dialect package for available dialects. readOnly - If true makes the DataSource read-only, which results in the connection pool calling setReadOnly(true) on each Connection properties - Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation. A typical configuration for MySQL may be something like:
64
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 of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:
dataSource { boolean pooled = true // type declaration results in ignored local variable }
More on dbCreate
Hibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through the dbCreate property, which can take these values:
65
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 or data. Note that this can't properly handle many schema changes like column renames (you're left with the old column containing the existing data). validate - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings. any other value - does nothing You can also remove the dbCreate setting completely, which is recommended once your schema is relatively stable and definitely when your application and database are deployed in production. Database changes are then managed through proper migrations, either with SQL scripts or a migration tool like Liquibase (the Database Migration plugin uses Liquibase and is tightly integrated with Grails and GORM).
66
The format on the JNDI name may vary from container to container, but the way you define the DataSource in Grails remains the same.
67
Grails supports Rails-style migrations via the Database Migration plugin which can be installed by running
The plugin uses Liquibase and and provides access to all of its functionality, and also has support for GORM (for example generating a change set by comparing your domain classes to a database).
68
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 framework.
Configuration
By default the console is configured for an H2 database which will work with the default settings if you haven't configured an external database - you just need to change the JDBC URL to jdbc:h2:mem:devDB. If you've configured an external database (e.g. MySQL, Oracle, etc.) then you can use the Saved Settings dropdown to choose a settings template and fill in the url and username/password information from your DataSource.groovy.
69
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 DataSources, add another dataSource block (at the top level, in an environment block, or both, just like the standard DataSource definition) with a custom name, separated by an underscore. For example, this configuration adds a second DataSource, using MySQL in the development environment and Oracle in production:
70
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.
A domain class can also use two or more DataSources. Use the datasources property with a list of names to configure more than one, for example:
71
If a domain class uses the default DataSource and one or more others, use the special name 'DEFAULT' to indicate the default 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' } }
The first DataSource specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. But you can call GORM methods on the 'auditing' DataSource with the DataSource name, for example:
72
As you can see, you add the DataSource to the method call in both the static case and the instance case.
Services
Like Domain classes, by default Services use the default DataSource and PlatformTransactionManager. To configure a 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 whose DataSource is the same as the Service. Note that the datasource specified in a service has no bearing on which datasources are used for domain classes; that's determined by 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, and WahooService uses dataSource1, a service method that saves a new Foo and a new Bar will only be transactional for Foo since they share the datasource. The transaction won't affect the Bar instance. If you want both to be transactional you'd need to use two services and XA datasources for two-phase commit, e.g. with the Atomikos plugin.
73
In the above example we're loading configuration files (both Java Properties files and ConfigSlurper configurations) from different 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 application. A typical use 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 hence obtainable from there. Values that have the same name as previously defined values will overwrite the existing values, and the pointed to configuration 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 property will override any values defined in your application Config.groovy file which may not be what you want. You may want to have a set of default values be be loaded that can be overridden in either your application's Config.groovy file or in a named config location. For this you can use the grails.config.defaults.locations property. This property supports the same values as the grails.config.locations property (i.e. paths to config scripts, property files or classes), but the config described by grails.config.defaults.locations will be loaded before all other values and can therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration that you can choose to include in your application config.
Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring
3.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 create an application with the create-app command. The version is stored in the application meta data file application.properties in the root of the project. 74
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 version to the end of the created WAR file.
You can retrieve the the version of Grails that is running with:
def grailsVersion = grailsApplication.metadata['app.grails.version']
75
Note that you can have all your gdoc files in the top-level directory if you want, but you can also put sub-sections in sub-directories 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 guide is going to be. To do that, you add a src/docs/guide/toc.yml file that contains the structure and titles for each section. This file is in YAML format and basically represents the structure of the user guide in tree form. For example, the above files could be represented as:
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 filename (minus the .gdoc extension) followed by a colon. The next line should contain title: plus the title of the section as seen by the end user. Every sub-section then has its own line after the title. Leaf nodes, i.e. those without any sub-sections, declare their title on the same line as the 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 guide. You should also make sure that all section names, i.e. the gdoc filenames, should be unique since they are used for creating internal links and for the HTML filenames. Don't worry though, the documentation engine will warn you of duplicate section names.
76
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 name is used. 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.io.File) grails.doc.images - The location of a directory containing image files for use in the style templates and within the documentation 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.css and then put a custom.css file in the corresponding directory. Grails will automatically include this CSS file in the guide.
Generating Documentation
Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the 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 documentation.
Documentation Syntax
As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.
Basic Formatting
Monospace: monospace
@monospace@
77
Italic: italic
_italic_
Bold: bold
*bold*
Image:
!http://grails.org/images/new/grailslogo_topNav.png!
This will link to an image stored locally within your project. There is currently no default location for doc images, but you can specify 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 defined using confluence or 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 want to link to:
[Intro|guide:introduction]
78
The section name comes from the corresponding gdoc filename. The documentation engine will warn you if any links to sections in 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 the right. 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 APIs to the engine you 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 API docs.
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
79
The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:
<hello>world</hello>
There are also a couple of macros for displaying notes and warnings: Note: This is a note!
80
Warning:
This is a warning!
81
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.
82
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'] )
83
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' ])
As you can see, you can either exclude dependencies by their artifact ID (also known as a module name) or any combination of group and artifact IDs (if you use the Map notation). You may also come across exclude as well, but that can only accept a single string or Map:
runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { exclude "xml-apis" }
If the dependency configuration is not explicitly set, the configuration named "default" will be used (which is also the correct value for dependencies coming from Maven style repositories).
84
The settings.groovy option applies to all projects, so it's the preferred approach.
In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the ebr() method:
repositories { ebr() }
85
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 provide appropriate (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 example!). In this case you can use the offline flag to execute Grails commands and Grails will not connect to any remote repositories:
grails --offline run-app
Note that this command will fail if you do not have the necessary dependencies in your local Ivy cache You can also globally configure offline mode by setting grails.offline.mode to true in ~/.grails/settings.groovy 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' }
Custom Resolvers
If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver: 86
/* * 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
It's also possible to pull dependencies from a repository using SSH. Ivy comes with a dedicated resolver that you can configure and 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 the path in the Grails 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 applications. An alternative on Unix is to create an alias for grails -classpath ... so that you don't have to type the extra arguments each time.
Authentication
If your repository requires authentication you can configure this using a credentials block: 87
This can be placed in your USER_HOME/.grails/settings.groovy file using the grails.project.ivy.authentication setting:
grails.project.ivy.authentication = { credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" } }
A common issue is that the checksums for a dependency don't match the associated JAR file, and so Ivy rejects the dependency. This helps ensure that the dependencies are valid. But for a variety of reasons some dependencies simply don't have valid checksums in the 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 }
88
Inside the BuildConfig.groovy file. To exclude specific inherited dependencies you use the excludes method:
inherits("global") { excludes "oscache", "ehcache" }
defaultDependenciesProvided must come before inherits, otherwise the Grails dependencies will be included in the war.
{info} Be sure to read the next section on Dependency Resolution Caching in addition to this one as it affects changing dependencies. {info} All dependencies (jars and plugins) with a version number ending in -SNAPSHOT are implicitly considered to be changing by Grails. 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 for newer versions of a dependency once it finds a remote repository that has the dependency. Consider the following setup:
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 that the local Grails dependency and the local Maven cache do not contain the dependency but the remote repository does, when we perform dependency 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 will happen: 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 cache so will not be updated (i.e. downloaded) Later on, a new version of mylib 1.0-SNAPSHOT is published changing the version on the server. The next time we perform 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 will be updated (i.e. downloaded to the cache) So far everything is working well.
90
Now we want to test some local changes to the mylib library. To do this we build it locally and install it to the local Maven cache (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 updated (i.e. downloaded to 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 next time we perform 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 so will not be updated (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 continue to keep using the version from the local maven repository. The rule to remember is this: when resolving a dependency, Grails will stop searching as soon as it finds a repository that has the dependency at the specified version number. It will not continue searching all repositories trying to find a more recently modified instance. To remedy this situation (i.e. build against the newer version of mylib 1.0-SNAPSHOT in the remote repository), you can either: 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 finished building against a locally built SNAPSHOT always try to clear it from the local maven repository.
This changing dependency behaviour is an unmodifiable characteristic of the underlying dependency management system that Grails uses, Apache Ivy. It is currently not possible to have Ivy search all repositories to look for newer versions (in terms of modification date) of the same dependency (i.e. the same combination of group, name and version).
91
By default this will generate reports in the target/dependency-report directory. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:
grails dependency-report runtime
In this case the Spock dependency will be available only to the plugin and not resolved as an application dependency. Alternatively, if 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 because it's consistent with the Map argument.
92
In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the excludes method, effectively excluding the javassist library as a dependency.
The line pom true tells Grails to parse Maven's pom.xml and load dependencies from there.
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 installed.
maven-deploy
The maven-deploy command will deploy a Grails project or plugin into a remote Maven repository:
93
grails maven-deploy
It is assumed that you have specified the necessary <distributionManagement> configuration within a pom.xml or that you 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 specified by this 'id' within your grails-app/conf/BuildConfig.groovy file or in your $USER_HOME/.grails/settings.groovy file:
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 Ant Maven tasks. For example the following XML:
<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>
By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however to specify a different protocol you can do:
grails maven-deploy --repository=myRepo --protocol=webdav
For applications this plugin will use the Grails application name and version provided by Grails when generating the pom.xml file. To 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 GrailsPlugin.groovy descriptor:
String groupId = 'myOrg' String version = '0.1'
The 'artifactId' is taken from the plugin name. For example if you have a plugin called FeedsGrailsPlugin the artifactId will be "feeds". If your plugin does not specify a groupId then this defaults to "org.grails.plugins".
95
If you don't specify a group id the default plugin group id of org.grails.plugins is used. You can specify to use the latest version of a particular plugin by using "latest.integration" as the version number:
plugins { runtime ':hibernate:latest.integration' }
The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based 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' }
Plugin Exclusions
You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:
plugins { runtime(':weceem:0.8') { excludes "searchable" } }
Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" plugin. By using the excludes method you can tell Grails not to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:
96
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 resolved:
plugins { runtime(':weceem:0.8') { transitive = false } runtime ':searchable:0.5.4' // specifies a fixed searchable version }
97
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, Grails will quit with an 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:
98
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 for more information about individual commands It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with run-app where you may for example want to set a higher maximum heap size. The Grails command will use any JVM options provided in the general 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 running the script. But when you run a script as part of an automated process, for example a continuous integration build server, there's no way to "answer" the questions. So you can pass the --non-interactive switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin. For example:
grails war --non-interactive
99
If you need to open a file whilst within interactive mode you can use the open command which will TAB complete file paths:
100
Even better, the open command understands the logical aliases 'test-report' and 'dep-report', which will open the most recent test and dependency reports respectively. In other words, to open the test report in a browser simply execute open test-report. You can even open multiple files at once: open test-report test/unit/MyTests.groovy will open the HTML test report in your 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 with a !:
101
Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.
Will create a script called scripts/CompileSources.groovy. A Gant script itself is similar to a regular Groovy script except 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.AntBuilder) that allows access to the Apache Ant API. 102
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.
This lets you call the default target directly from other scripts if you wish. Also, although we have put the call to setDefaultTarget() at the end of the script in this example, it can go anywhere as long as it comes after the target it refers to ("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 advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section.
103
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() } }
Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant documentation.
104
Description You really should include this! Fortunately, it is included automatically by all other Grails scripts except _GrailsProxy, so you usually don't have to include it explicitly. Include this to fire events. Adds an event(String eventName, List args) method. Again, included by almost all other Grails scripts. Configures compilation, test, and runtime classpaths. If you want to use or play with them, include this script. 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 access through your proxy.
Provides a parseArguments target that does what it says on the tin: parses the _GrailsArgParsing arguments provided by the user when they run your script. Adds them to the argsMap property. _GrailsTest _GrailsRun 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 normally (runApp/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 what kind of targets are 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 of determining that a script is internal , or in other words that it has not corresponding "command". So you can't run "grails _grails-settings" for example. That is also why they don't have a default target. Internal scripts are all about code sharing and reuse. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. For example if you have a script that runs some functional tests, you can 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(...) }
105
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 arguments direct to the closures.
You can see here the three handlers eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events: 106
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
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 completing a target, even if the target does not exit the scripting environment Called when a create-xxxx script has completed and created an artefact Called whenever a project source filed is created, not including files constantly managed by Grails Called when the scripting environment is about to exit cleanly Called after a plugin has been installed Called when compilation starts, passing the kind of compile - source or tests Called when compilation is finished, passing the kind of compile - source or tests Called when documentation generation is about to start javadoc or groovydoc Called when documentation generation has ended - javadoc or groovydoc Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name. Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated)
StatusFinal
message
PluginInstalled pluginName CompileStart CompileEnd DocStart DocEnd kind kind kind kind
SetClasspath
rootLoader
PackagingEnd
none
The defaults
The core of the Grails build configuration is the grails.util.BuildSettings class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings. Here is a selection of the configuration options and their default values: 108
Default value $USER_HOME/.grails/<grailsVersion> <grailsWorkDir>/projects/<baseDirName> <projectWorkDir>/classes <projectWorkDir>/test-classes <projectWorkDir>/test/reports <projectWorkDir>/resources <projectWorkDir>/plugins <grailsWorkDir>/global-plugins
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 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.
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 do: an instance of BuildSettings is available to your scripts as the grailsSettings script variable. You can also access it from your code by using the grails.util.BuildSettingsHolder class, but this isn't recommended.
109
Note that the default values take account of the property values they depend on, so setting the project working directory like this would 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 wins because it takes 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 contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.
Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be grails.compiler.dependencies processed by an AntBuilder so the syntax is the Groovy form of the corresponding XML elements in an Ant build file, e.g. fileset(dir: "$basedir/lib", include: "**/*.class). grails.testing.patterns A list of Ant path patterns that let you control which files are included in the tests. The patterns should 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 anything you like but setting this option. For example, another common suffix is "Test". A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war". A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory. A closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app". A closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR. The location to generate Grails' web.xml to
grails.testing.nameSuffix
grails.project.war.file grails.war.dependencies
grails.war.copyToWebApp
grails.war.resources
grails.project.web.xml
110
Ant Integration
When you create a Grails application with the create-app command, Grails doesn't automatically create an Ant build.xml file but you can generate one with the integrate-with command:
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 automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it 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 that's available, not just 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"/>
This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available:
111
Attribute home
Description
Required
The location of the Grails installation directory to Yes, unless classpath is use for the build. specified. Classpath to load Grails from. Must include the Yes, unless home is set or "grails-bootstrap" artifact and should include you use a classpath "grails-scripts". element. The name of the Grails script to run, e.g. Yes. "TestApp". The arguments to pass to the script, e.g. "-unit No. Defaults to "". -xml". The Grails environment to run the script in. No. Defaults to the script default.
classpathref
Advanced setting: adds the application's runtime No. Defaults to true. classpath to the 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 includes everything in @compileClasspath. testClasspath - Classpath used to compile and run the tests. Typically includes everything in runtimeClasspath. How you populate these paths is up to you. If you use the home attribute and put your own dependencies in the lib directory, then 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 new apps.
Maven Integration
Grails provides integration with Maven 2 with a Maven plugin. The current Maven plugin is based on but supersedes the version created by Octo, who did a great job with the original.
Preparation
In order to use the new plugin, all you need is Maven 2 installed and set up. This is because you no longer need to install Grails 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 will not work with earlier versions.
112
The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance: export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"
Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to. But first, to set target JDK to Java 6, do that now. 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>
113
then run
mvn compile
and the hibernate and tomcat plugins will be installed. Now you have a Grails application all ready to go. The plugin integrates into the standard build cycle, so you can use the standard Maven phases to build and package your app: mvn clean , mvn compile , mvn test , mvn package , mvn install . You can also use some of the Grails commands that have been wrapped as Maven goals:
114
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-plugin - Calls the install-plugin 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 grails:uninstall-plugin - Calls the uninstall-plugin command For a complete, up to date list, run mvn grails:help
When this command has finished, you can immediately start using the standard phases, such as mvn package. Note that you have to specify a group ID when creating the POM. You may also want to set target JDK to Java 6; see above.
115
The standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional 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" block:
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>1.3.2</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>
This also demonstrates the grails:exec goal, which can be used to run any Grails command. Simply pass the name of the command as the command system property, and optionally specify the arguments with the args property:
mvn grails:exec -Dcommand=create-webtest -Dargs=Book
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 variable, and launch Maven with the default "mvn" command:
116
Raising issues
If you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of GRAILS-3547.
117
If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name. This will create a class at the location grails-app/domain/helloworld/Person.groovy such as the one below:
package helloworld class Person { }
If you have the dbCreate property set to "update", "create" or "create-drop" on your DataSource, Grails will automatically generate/modify the database tables for you. You can customize the class by adding properties:
118
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, GORM, etc.
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. You can also load an 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 persisted. Note that if you 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:
119
def p = Person.load(1)
This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or throws an exception if no record is found for the specified id.
Update
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()
This class will map automatically to a table in the database called book (the same name as the class). This behaviour is customizable through the ORM Domain Specific Language Now that you have a domain class you can define its properties as Java types. For example:
120
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 lower case separated by underscores. For example releaseDate maps onto a column release_date. The SQL types are auto-detected from the Java types, but can be customized with Constraints or the ORM DSL.
class Nose { }
In this case we have a unidirectional many-to-one relationship from Face to Nose. To make this relationship bidirectional define the other side as follows:
Example B
121
In this case we use the belongsTo setting to say that Nose "belongs to" Face. The result of this is that we can create a Face, attach a Nose instance to it and when we save or delete the Face instance, GORM will save or delete the Nose. In other words, saves and 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 a transient Face:
new Nose(face:new Face()).save() // will cause an error
To make the relationship a true one-to-one, use the hasOne property on the owning side, e.g. Face:
Example C
Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships. 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 } }
122
5.2.1.2 One-to-many
A one-to-many relationship is when one class, example Author, has many instances of a another class, example Book. With Grails you define such a relationship with the hasMany setting:
class Author { static hasMany = [books: Book] String name }
In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
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 hasMany setting. This can be 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 initialized 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 specified:
123
If you have two properties of the same type on the many side of a one-to-many you have to use mappedBy to specify which the collection is mapped:
class Airport { static hasMany = [flights: Flight] static mappedBy = [flights: "departureAirport"] }
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"] }
5.2.1.3 Many-to-many
Grails supports many-to-many relationships by defining a hasMany on both sides of the relationship and having a belongsTo on the owned side of the relationship:
124
Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case Author, takes 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!
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 responsibility for managing the relationship.
Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself
125
GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using 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 | ---------------------------------------------
126
If you define the Address class in a separate Groovy file in the grails-app/domain directory you will also get an address table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the Address class below the Person class in the grails-app/domain/Person.groovy file
In the above example we have a parent Content class and then various child classes with more specific behaviour.
Considerations
At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called class so the parent class (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 inheritance mapping. An 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 of outer join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.
Polymorphic Queries
127
The upshot of inheritance is that you get the ability to polymorphically query. For example using the list method on the Content 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
The books property that GORM injects is a java.util.Set. Sets guarantee uniquenes but not order, which may not be what you 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.lang.Comparable in your Book class:
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 by their release date.
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 you can define your collection type as a List:
128
In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:
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 of the elements in the 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 throw an exception (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 Bag type to represent mapped collections. The only change required for this is to define the collection type as a Collection:
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 Bag don't trigger a load of all existing instances from the database, so this approach will perform better and require less memory than using a Set or a List.
Maps of Objects
If you want a simple map of string/value pairs GORM can map this with the following: 129
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 strings.
In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an Author with a large number of associated Book instances if you 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()
130
You could also model the collection as a Hibernate Bag as described above.
Transactional Write-Behind
A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call save or delete it does not necessarily perform any SQL operations at that point. Hibernate batches up SQL statements and executes them as late as possible, often at the end of the request when flushing and closing the session. This is typically done for you automatically by Grails, which manages your Hibernate session. Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush is required, or when a flush is triggered programmatically. One common case where Hibernate will flush cached updates is when performing queries since the cached information might be included in the query results. But as long as you're doing non-conflicting saves, updates, and deletes, they'll be batched until the session is flushed. This can be a significant performance boost for applications that do a lot of database writes. Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a transaction, flushing will execute SQL updates but the database will save the changes in its transaction queue and only finalize the updates when the transaction commits.
This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. But there are occasions when you want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so 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 with the database. This also lets you catch any exceptions, which is typically useful in highly concurrent scenarios involving optimistic locking:
131
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 validation fails the domain instance will not be persisted to the database. By default, save() will simply return null in this case, but if you would prefer it to 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 on configuration. Just remember that when you are saving domain instances that have been bound with data provided by the user, the likelihood of validation 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!
As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-place you can use the flush argument:
def p = Person.get(1) p.delete(flush: true)
Using the flush argument lets you catch any errors that occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a DataIntegrityViolationException that is thrown when you violate the database constraints:
132
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 avoided through boolean 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"])
If I now create an Airport and add some Flights to it I can save the Airport and have the updates cascaded down to each flight, 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 understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read part 2 of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.
Bidirectional one-to-many with belongsTo
In the case of a bidirectional one-to-many where the many side defines a belongsTo then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.
Unidirectional one-to-many
class B {
In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".
Bidirectional one-to-many, no belongsTo
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 cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.
Unidirectional one-to-one with belongsTo
class A {
In the case of a unidirectional one-to-one association that defines a belongsTo then the cascade strategy is set to "ALL" for the 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.
class Flight { String number Location destination static belongsTo = [airport: Airport] }
135
GORM will execute a single SQL query to fetch the Airport instance, another to get its flights, and then 1 extra query for each iteration over the flights association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).
In this case the flights association will be loaded at the same time as its Airport instance, although a second query will be executed to fetch the collection. You can also use fetch: 'join' instead of lazy: false , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the 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 for one-to-manys. Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the section on the ORM DSL.
136
In this case, due to the batchSize argument, when you iterate over the flights association, Hibernate will fetch results in batches of 10. For example if you had an Airport that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the Airport and then 30 queries to fetch each flight. With batch fetching you get 1 query to fetch the Airport and 3 queries to fetch each Flight in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:
class Flight { static mapping = { batchSize 10 } }
Check out part 3 of the GORM Gotchas series for more in-depth coverage of this tricky topic.
When you perform updates Hibernate will automatically check the version property against the version column in the database and if 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 performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:
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 the data or go back to the user and ask them to resolve the conflict. Alternatively, if it becomes a problem you can resort to pessimistic locking. 137
Pessimistic Locking
Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has 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()
Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated 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 finder:
def airport = Airport.findByName("Heathrow", [lock: true])
Or using criteria:
def airport = Airport.createCriteria().get { eq('name', 'Heathrow') lock true }
138
Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using get Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).
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 persistent properties and associations. You can also check if individual fields have been modified:
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 will not be null:
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:
139
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 } }
Listing instances
Use the list method to obtain all instances of a given class:
def books = Book.list()
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 argument is either asc for ascending or desc for descending.
140
You can also obtain a list of instances for a set of identifiers using getAll:
def books = Book.getAll(23, 93, 81)
The Book class has properties such as title, releaseDate and author. These can be used by the findBy and findAllBy 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 combines one or more properties. The basic form is:
141
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 equivalent to a SQL like expression. The possible comparators include: 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 demonstrated in the following example:
def now = new Date() def lastWeek = now - 7 def book = Book.findByReleaseDateBetween(lastWeek, now) books = Book.findAllByReleaseDateIsNull() books = Book.findAllByReleaseDateIsNotNull()
142
In this case we're using And in the middle of the query to make sure both conditions are satisfied, but you could equally use Or:
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 combine And and Or 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:
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 Author.
Basic Querying
The where method accepts a closure that looks very similar to Groovy's regular collection methods. The closure should define the logical criteria in regular Groovy syntax, for example:
def query = Person.where { firstName == "Bart" } Person bart = query.find()
143
The returned object is a DetachedCriteria instance, which means it is not associated with any particular database connection or 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 a where-style query immediately there are variations of the findAll and find methods to accomplish this:
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 operators to methods: 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")
144
The Groovy regex matching operators map onto like and ilike queries unless the expression on the right hand side is a Pattern 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 }
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 original query:
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 explicitly cast to a DetachedCriteria instance. In other words the following will produce an error:
def callable = { lastName == "Simpson" } def query = Person.where(callable)
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 targeted at the Person class.
The following table described how each comparison operator maps onto each criteria property comparison method:
146
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 association name:
def query = Person.where { pets { name == "Jack" || name == "Joe" } }
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:
147
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 average age the following 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 criteria:
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 following query will find all people younger than people with the surname "Simpson":
Person.where { age < property(age).of { lastName == "Simpson" } }
148
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 cannot, for 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 }
149
Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed. To batch delete records you can use the deleteAll method:
def query = Person.where { lastName == 'Simpson' } int total = query.deleteAll()
5.4.3 Criteria
Criteria is an advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better approach 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 API. The nodes on this 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: 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.
Querying Associations
Associations can be queried by having a node that matches the property name. For example say the Account class had many Transaction objects:
class Account { static hasMany = [transactions: Transaction] }
We can query this association by using the property name transaction as a builder node:
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 days. You can also nest such association queries within logical blocks:
151
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 in the last 10 days.
When multiple fields are specified in the projection, a List of values will be returned. A single value will be returned otherwise.
Note that the parameter there is SQL. The first_name attribute referenced in the example refers to the persistence model, not the object model like in HQL queries. The Person property named firstName is mapped to the first_name column in the database and you must refer to that in the sqlRestriction string. Also note that the SQL used here is not necessarily portable across databases.
152
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 / ScrollableResults pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet. Contrary to JDBC, columns of results are numbered from zero.
Notice the usage of the join method: it tells the criteria API to use a JOIN to fetch the named associations with the Task instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode: 153
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 results - even with the maxResults option.
fetchMode and join are general settings of the query and can only be specified at the top-level, i.e. you 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 will automatically be 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 set.
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:
c.list { }
154
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 queries one row. This 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 listDistinct the result set, this allows listing only distinct entities and is equivalent to DISTINCT_ROOT_ENTITY of the CriteriaSpecification class. count Returns the number of matching rows.
Once you have obtained a reference to a detached criteria instance you can execute where queries or criteria queries to build up the 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 new query. In other 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' }
155
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")
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 treated like a list:
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 Groovy collection iteration methods. 156
You can also execute dynamic finders on DetachedCriteria just like on domain classes. For example:
def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def bart = criteria.findByFirstName("Bart")
Notice that in this case the subquery class is the same as the original criteria query class (ie. Person) and hence the query can be 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 your subquery returns multiple results then there are different criteria methods that need to be used to compare the result. For example to find all the people 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" }
157
The following table summarizes criteria methods for operating on subqueries that return multiple results: 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
Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed within the DetachedCriteria instance.
158
def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = ?", [author])
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.
159
def results = Book.findAll("from Book as b where " + "b.title like 'Lord of the%' " + "order by b.title asc", [max: 10, offset: 20])
Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired 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() } }
160
Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like save() and delete() won't result in objects being saved unless you run your operations with a new Session. Fortunately the withNewSession method lets you share the same transactional JDBC connection even though you're using a different underlying Session.
161
Validation may run more often than you think. It is triggered by the validate() and save() methods as you'd expect, but it is also typically triggered just before the view is rendered as well. So when writing beforeValidate() implementations, make sure that they can handle being called multiple times with the same property values. GORM supports an overloaded version of beforeValidate which accepts a List parameter which may include the names of the properties which are about to be validated. This version of beforeValidate will be called when the validate method has been 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 that the validate method is being invoked with no arguments, not a List that includes all of the property names.
Either or both versions of beforeValidate may be defined in a domain class. GORM will prefer the List version if a List is passed to validate but will fall back on the no-arg version if the List version does not exist. Likewise, GORM will prefer the no-arg version if no arguments are passed to validate but will fall back on the List version if the no-arg version does not exist. In that case, null is passed to beforeValidate.
162
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.
163
@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, PostInsertEvent etc.) that provide further information specific to the event. A cancel() method is also provided on the event which allows you to veto an insert, update or delete operation. Once you have created your event listener you need to register it with the ApplicationContext. This can be done in BootStrap.groovy:
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 more detailed Hibernate 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.groovy or in the doWithSpring closure in a plugin descriptor by registering a Spring bean named hibernateEventListeners. This bean has 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 can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid Map keys and corresponding interfaces are listed here:
164
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
165
For example, you could register a class AuditEventListener which implements PostInsertEventListener , PostUpdateEventListener , and PostDeleteEventListener using the following in an application:
beans = { 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 keep track of updates to objects. However, this is actually not necessary. By defining a lastUpdated and dateCreated property these will be 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 domain instances will fail validation - probably not what you want. Leave constraints off these properties unless you have disabled automatic timestamping.
166
Grails domain classes can be mapped onto many legacy schemas with an Object Relational Mapping DSL (domain specific language). The following sections takes you through what is possible with the ORM DSL.
None of this is necessary if you are happy to stick to the conventions defined by GORM for table names, column names and so on. You only needs this functionality if you need to tailor the way GORM maps onto legacy schemas or configures caching Custom mappings are defined using a a static mapping block defined within your domain class:
class Person { static mapping = { } }
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 name you can do:
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 name corresponds to a domain class persistent field, the parameter values (in this case just "column") are used to configure the mapping for that property. 167
Column type
GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifing user types that implement the Hibernate org.hibernate.usertype.UserType interface, which allows complete customization of how a type is persisted. 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 you could use:
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 (for example TEXT or 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 of a many-to-one or one-to-one association this is exactly the same as any regular column. For example consider the following:
class Person { String firstName Address address static mapping = { table 'people' firstName column: 'First_Name' address column: 'Person_Address_Id' } }
168
By default the address association would map to a foreign key column called address_id. By using the above mapping we have 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 the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional associations the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between Person and 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 use the joinTable 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 association:
class Group { static hasMany = [people: Person] }
169
In this case Grails will create a join table called group_person containing foreign keys called person_id and group_id referencing the person and group tables. To change the column names you can specify a column within the mappings for each 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' } }
You can customize any of these settings, for example to use a distributed caching mechanism. 170
For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate 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 further:
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 (associations) of objects. For example:
class Person { String firstName static hasMany = [addresses: Address] static mapping = { table 'people' version false addresses column: 'Address', cache: true } }
171
This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:
cache: 'read-write' // or 'read-only' or 'transactional'
Caching Queries
You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the cache argument:
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 discussed in 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 cache may be used. 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 very unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate. transactional - The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class in the grails-app/conf/DataSource.groovy file's hibernate config.
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 for all child classes.
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 documentation Although you don't typically specify the id field (Grails adds it for you) you can still configure its mapping like the other properties. For example to customise the column for the id property you can do:
class Person { static mapping = { table 'people' version false id column: 'person_id' } }
173
The above will create a composite id of the firstName and lastName properties of the Person class. To retrieve an instance by id 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 override the equals and hashCode methods, using the properties in the composite key for the calculations. The example above uses a HashCodeBuilder for convenience but it's fine to implement it yourself. Another important consideration when using composite primary keys is associations. If for example you have a many-to-one association where the foreign keys are stored in the associated table then 2 columns will be present in the associated table. For example consider the following domain class:
class Address { Person person }
In this case the address table will have an additional two columns called person_first_name and person_last_name. If you wish the change the mapping of these columns then you can do so using the following technique: 174
class Address { Person person static mapping = { person { column: "FirstName" column: "LastName" } } }
Note that you cannot have any spaces in the value of the index attribute; in this example index:'Name_Idx, Address_Index' will cause an error.
If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing data (due to data overriding) unless you use pessimistic locking
175
There's a slight risk that two updates occurring at nearly the same time on a fast server can end up with the same timestamp value but this risk is very low. One benefit of using a Timestamp instead of a Long is that you combine the optimistic locking and last-updated semantics into a single column.
176
The first option, lazy: false , ensures that when a Person instance is loaded, its addresses collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded with a JOIN rather than another SELECT. Typically you want to reduce the number of queries, so fetch: 'join' is the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would 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, consider this mapping for 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 that Pet plus the four next ones. You can get the same behaviour with eager loading by combining batchSize with the lazy: false option. You can find out more about these options in the Hibernate user guide and this primer on fetching strategies. Note that ORM DSL does not currently support the "subselect" fetching strategy.
177
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 Address is loaded.
and assume that we have a single Person instance with a Dog as the pet. The following code will work as you would expect:
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.get(person.petId) instanceof Dog
178
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.list()[0] instanceof Dog
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 session makes. When you load the Person instance, Hibernate creates a proxy for its pet relation and attaches it to the session. Once that happens, whenever you retrieve that Pet instance with a query, a get(), or the pet relation within the same session , Hibernate gives you the proxy. Fortunately for us, GORM automatically unwraps the proxy when you use get() and findBy*(), or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned with a query that returns a list, such as list() and findAllBy*(). However, if Hibernate hasn't attached the proxy to the 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 ClassCastException because the 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 can access any Dog 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 will know why such an error occurs and be able to work around it.
179
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 is removed from an 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 better 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 its value:
class Person { String firstName static hasMany = [addresses: Address] static mapping = { addresses cascade: "all-delete-orphan" } }
180
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 to the corresponding UserType implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column 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 such cases you explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails 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 pleased to know that you 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 joinTable. One thing to bear in mind with custom types is that they define the SQL types for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, override the column's SQL type using the sqlType attribute:
181
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 "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work.
If the tax property is derived based on the value of price and taxRate properties then is probably no need to persist the tax 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 persistence model not 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 generated to support that will look something like this:
182
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 could be achieved by adding a method like getTax() to the Product class that simply returns the product of the taxRate and price properties. With an approach like that you would give up the ability query the database based on the value of the tax property. Using a derived property allows exactly that. To retrieve all Product objects that have a tax value greater than 21.12 you could execute a query like this:
Product.findAllByTaxGreaterThan(21.12)
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 of SQL code, derived properties may not have GORM constraints applied to them. If constraints are specified for a derived property, they will be ignored.
183
By default Grails uses Hibernate's ImprovedNamingStrategy to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-instance basis in the mapping closure but if there's a consistent pattern you can specify a different NamingStrategy class to use. Configure the class name to be used in grails-app/conf/DataSource.groovy in the hibernate section, e.g.
dataSource { pooled = true dbCreate = "create-drop" } hibernate { cache.use_second_level_cache = true naming_strategy = com.myco.myproj.CustomNamingStrategy }
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) } }
However, you can also declare the default sort order for a collection in the mapping:
class Airport { static mapping = { sort "name" } }
184
The above means that all collections of Airports will by default be sorted by the airport name. If you also want to change the sort order , use this syntax:
class Airport { static mapping = { sort name: "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 relationships because they involve a join table. See this issue for more details. Consider using a SortedSet or queries with sort parameters to fetch the data you need.
185
In this example we rollback the transaction if the destination account is not active. Also, if an unchecked Exception or Error (but not a checked Exception, even though Groovy doesn't require that you catch checked exceptions) is thrown during the process the 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 the entire transaction. 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 block.
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. If that were the case, we would likely define the column as follows if we were creating the table with an SQL script. Column Data Type
description TEXT Chances are we would also want to have some application-based validation to make sure we don't exceed that 1000 character limit before we persist any records. In Grails, we achieve this validation with constraints. We would add the following constraint declaration 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 schema to be generated as shown above. Below is a description of the other constraints that influence schema generation. 186
187
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
188
the
location
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 and you 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:
189
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.
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 the grails-app/controllers/ directory, methods inherited from that class are not converted to controller actions. If the intent is to expose those inherited methods as controller actions the methods may be overridden in the subclass and the subclass method may invoke the method in the super class.
190
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:
Accessing Scopes
Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even on classes provided 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 } }
191
This is one of the ways that Grails unifies access to the different scopes.
When the list action is requested, the message value will be in scope and can be used to display an information message. It will be 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, but can be any object type.
Scoped Controllers
By default, a new controller instance is created for each request. In fact, because the controller is prototype scoped, it is thread-safe 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 Closure properties) 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 above, for example
static scope = "singleton"
You can define the default strategy under in grails.controllers.defaultScope key, for example:
grails.controllers.defaultScope = "singleton"
Config.groovy
with
the
192
Use scoped controllers wisely. For instance, we don't recommend having any properties in a singleton-scoped controller since they will be shared for all requests. Setting a default scope other than prototype may also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope is prototype.
The above does not reflect what you should use with the scaffolding views - see the scaffolding section for more details. If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write code like this:
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 controller is created for each request. Otherwise code such as the above would not be thread-safe, and all users would 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:
193
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.
In this case Grails will attempt to render a view at the location grails-app/views/book/display.gsp. Notice that Grails automatically qualifies the view location with the book directory of the grails-app/views directory. This is convenient, but to 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) }
render
view
at
the
location
194
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 instead.
Rendering a Response
Sometimes it's easier (for example with Ajax applications) to render snippets of text or code to the response directly from the 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) } }
// 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 careful of naming clashes between HTML elements and Grails tags, for example:
195
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). To correctly output a <form> element, use the following:
def login() { // body { h1 'Hello' builder.form { } } // }
Internally the redirect method uses the HttpServletResponse object's sendRedirect method. The redirect method expects one of: Another closure within the same controller class:
196
// 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')
Or a full URL:
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 parameter is specified with the same name as a request parameter, the request parameter is overridden and the controller parameter is used. Since the params object is a Map, you can use it to pass the current request parameters from one action to the next:
redirect(action: "next", params: params)
which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".
Chaining
197
Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the first 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]) } }
The model can be accessed in subsequent controller actions in the chain using the chainModel map. This dynamic property only 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"])
If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic of each controller
Before Interception
198
The beforeInterceptor intercepts processing before the action is executed. If it returns false then the intercepted action will 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 does not interfere with 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 the outside world. The beforeInterceptor then defines an interceptor that is used on all actions except the login action and it executes the auth method. The auth method is referenced using Groovy's method pointer syntax. Within the method it detects whether there is a user in the session, and if not it redirects to the login action and returns false, causing the intercepted action to not be processed.
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. An after interceptor may also modify the Spring MVC ModelAndView object prior to rendering. In this case, the above example becomes:
def afterInterceptor = { model, modelAndView -> println "Current view is ${modelAndView.viewName}" if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview" println "View is now ${modelAndView.viewName}" }
199
This allows the view to be changed based on the model returned by the current action. Note that the modelAndView may be null if 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 executing the interceptor (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 follows:
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']]
The data binding happens within the code new Book(params). By passing the params object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:
/book/save?title=The%20Stand&author=Stephen%20King
200
Then the title and author request parameters would automatically be set on the domain class. You can use the properties property to perform data binding onto an existing instance:
def save() { def b = Book.get(params.id) b.properties = params b.save() }
Grails will automatically detect the .id suffix on the request parameter and look up the Author instance for the given id when doing 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
This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically use the 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 technique won't work. Instead you use the subscript operator: 201
<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 do the update in. This is because a Set has no concept of order, so although we're referring to books0 and books1 it is not guaranteed that the order of the 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 refer to. This is also 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 size of association:
<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 elements in the middle:
<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 additional instances if 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 with a single-ended 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}" />
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': '']"/>
202
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 map key:
<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".
You'll notice the difference with the above request is that each parameter has a prefix such as author. or book. which is used to isolate which parameters belong to which type. Grails' params object is like a multi-dimensional hash and you can index into it to 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 below this level to bind. We could do the same with an Author domain class:
def a = new Author(params.author)
203
For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument. The type conversion happens automatically. In a case like the example shown above, the params.accountType request parameter has to be converted to an int. If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the errors property of the defining controller.
/accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue
Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, controller.errors.hasErrors() will be true, controller.errors.errorCount will be equal to 1 and controller.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.RequestParameter annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:
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 accountType) { // } }
Here we have a domain class Book that uses the java.net.URL class to represent URLs. Given an incoming request such as:
/book/save?publisherURL=a-bad-url
204
it is not possible to bind the string a-bad-url to the publisherURL property as a type mismatch error occurs. You can check for 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 conversion errors you would want a message from the grails-app/i18n/messages.properties file to use for the error. You can use a generic error message handler such as:
typeMismatch.java.net.URL=The field {0} is not a valid URL
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. Alternatively there is also 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:
205
Note that if an empty List is provided as a value for the include parameter then all fields will be subject to binding if they are not explicitly excluded.
Be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:
206
This is because there is local variable books which Groovy attempts to invoke as a method.
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.
Now you can use the following highly readable syntax to automatically convert domain classes to XML:
207
An alternative to using the converters is to use the codecs feature of Grails. The codecs feature provides encodeAsXML and encodeAsJSON methods:
def xml = Book.list().encodeAsXML() render xml
Again as an alternative you can use the encodeAsJSON to achieve the same effect.
The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation specific to Grails.
209
210
The uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard <g:form> tag. There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance directly:
211
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 InputStream and so on with the MultipartFile interface.
If you create an image using the params object in the constructor as in the example below, Grails will automatically bind the file's 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 column size that can't handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for byte properties. It is also possible to set the contents of the file as a string by changing the type of the myFile property on the image to a String type:
class Image { String myFile }
As this example shows, you can define constraints in command objects just like in domain classes.
When using methods instead of Closures for actions, you can specify command objects in arguments:
class LoginController { def login(LoginCommand cmd) { if (cmd.hasErrors()) { redirect(action: 'loginForm') return } // work with the command object data } }
213
In this example the command object interacts with the loginService bean which is injected by name from the Spring ApplicationContext.
Then in your controller code you can use the withForm method to handle valid and invalid requests:
withForm { // good request }.invalidToken { // bad request }
If you only provide the withForm method and not the chained invalidToken method then by default Grails will store the invalid token in a flash.invalidToken variable and redirect the request back to the original page. This can then be checked in the view:
<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 if used in a cluster.
214
The above example uses the int method, and there are also methods for boolean, long, char, short and so on. Each of these methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the parameters. Each of the conversion methods allows a default value to be passed as an optional second argument. The default value will be returned 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.
With that done ensure you do a clean re-compile as some async features are enabled at compile time.
215
With a Servlet target version of 3.0 you can only deploy on Servlet 3.0 containers such as Tomcat 7 and above.
Asynchronous Rendering
You can render content (templates, binary data etc.) in an asynchronous manner by calling the startAsync method which returns an instance of the Servlet 3.0 AsyncContext. Once you have a reference to the AsyncContext you can use Grails' regular render 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.
A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.
216
Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document, the practice is strongly discouraged. Mixing mark-up and code is a bad thing and most GSP 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 the GSP view from a 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 be referenced within the GSP view using the name book:
${book.title}
You can also use the <%= %> syntax to output values:
<html> <body> <%="Hello GSP!" %> </body> </html>
GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:
217
<html> <body> <%-- This is my comment --%> <%="Hello GSP!" %> </body> </html>
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
218
6.2.1.4 Expressions
In GSP the <%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form ${expr}:
<html> <body> Hello ${params.name} </body> </html>
However, unlike JSP EL you can have any Groovy expression within the ${..} block. Variables within the ${..} block are not escaped by default, so any HTML in the variable's string is rendered directly to the page. To reduce the risk of Cross-site-scripting (XSS) attacks, you can enable automatic HTML escaping with the grails.views.default.codec setting in grails-app/conf/Config.groovy:
grails.views.default.codec='html'
Other possible values are 'none' (for no default encoding) and 'base64'.
219
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 starts with g: it is automatically assumed to be a GSP tag. An example GSP tag would look like:
<g:example />
Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:
<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:
<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.
220
Here we assign a variable called now to the result of a GSP expression (which simply constructs a new java.util.Date instance). 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" />
221
The expr attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:
<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>
The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The books variable is a collection of Book instances. Since each Book has a title, you can obtain a list of Book titles using the expression books.title. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!
GSP supports many different tags for working with HTML forms and fields, the most basic of which is the form tag. This is a controller/action aware version of the regular HTML form tag. The url attribute lets you specify which controller and action to map 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 that all of the usual HTML attributes apply.
Form Fields
In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including: 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 tags), localeSelect, currencySelect and timeZoneSelect (for selecting locales, currencies and time zones respectively).
Tags return their results as a String-like object (a StreamCharBuffer which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:
Static Resource: ${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 quickly and often has an 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" />" />
For tags that use a custom namespace, use that prefix for the method call. For example (from the FCK Editor plugin):
def editor = fckeditor.editor(name: "text", width: "100%", height: "400")
Template Basics
Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example, you might have a template that renders Books located at grails-app/views/book/_bookTemplate.gsp: 224
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 Book instances you can 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 and its views at 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 location, and then with the template attribute use an absolute location starting with / instead of a relative location. For example if you had a template called 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]" />
225
The render controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of 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 method.
The key elements are the layoutHead, layoutTitle and layoutBody tag invocations:
226
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 the target page.
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. If we were to use the 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>
You can create a layout called grails-app/views/layouts/customer.gsp which will be applied to all views that the BookController delegates to. The value of the "layout" property may contain a directory structure relative to the grails-app/views/layouts/ directory. For example:
227
with
the
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 all views that the BookController delegates to. Alternatively, you can create a layout called grails-app/views/layouts/book/list.gsp which will only be applied to the list action within the BookController. If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed. If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which is grails-app/views/layouts/application.gsp. The name of the application default layout may be changed by defining a property in grails-app/conf/Config.groovy as follows:
grails.sitemesh.default.layout = 'myLayoutName'
default
layout
will
be
Inline Layouts
Grails' also supports Sitemesh's concept of inline layouts with the applyLayout tag. This can be used to apply a layout to a template, URL or arbitrary section of content. This lets you even further modularize your view structure by "decorating" your template includes. Some examples of usage can be seen below:
228
<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 external content in the 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.
The plugin achieves this by introducing new artefacts and processing the resources using the server's local file system. It adds artefacts for declaring resources, for declaring "mappers" that can process resources, and a servlet filter to serve processed resources. What you get is an incredibly advanced resource system that enables you to easily create highly optimized web applications that run the same in development and in production. The Resources plugin documentation provides a more detailed overview of the concepts which will be beneficial when reading the following guide.
This will automatically include all resources needed for jQuery, including them at the correct locations in the page. By default 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 modules:
<html> <head> <r:require modules="jquery, main, blueprint, charting"/> <r:layoutResources/> </head> <body> <r:layoutResources/> </body> </html>
The above may result in many JavaScript and CSS files being included, in the correct order, with some JavaScript files loading at the 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 actually perform the render.
When you have declared the resource modules that your GSP page requires, the framework needs to render the links to those resources at the correct time. To achieve this correctly, you must include the r:layoutResources tag twice in your page, or more commonly, in your GSP layout:
<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 the page the resource should be included. The default disposition applied depends on the type of resource. All CSS must be rendered in <head> in HTML, so "head" is the default for all CSS, and will be rendered by the first r:layoutResources. Page load times are improved when JavaScript is loaded after the page content, so the default for JavaScript files is "defer", which means it is rendered when the second r:layoutResources is invoked. Note that both your GSP page and your Sitemesh layout (as well as any GSP template fragments) can call r:require to depend on resources. The only limitation is that you must call r:require before the r:layoutResources that should render it.
...in your GSP you can inject some JavaScript code into the head or deferred regions of the page like this:
231
<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 required libraries have loaded.
Note that Grails has a built-in g:img tag as a shortcut for rendering <img> tags that refer to a static resource. The Grails img tag is Resources-aware and will delegate to r:img if found. However it is recommended that you use r:img directly if using the Resources plugin. Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity. See r:resource documentation for full details.
232
This is equivalent to the Grails resource tag, returning a link to the processed static resource. Grails' own g:resource tag delegates to this implementation if found, but if your code requires the Resources plugin, you should use r:resource directly. 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 external file resource such as CSS, JS or a favicon. See r:resource documentation for full details.
This defines three resource modules; 'core', 'utils' and 'forms'. The resources in these modules will be automatically bundled out of the box according to the module name, resulting in fewer files. You can override this with bundle:'someOtherName' on each resource, or call defaultBundle on the module (see resources plugin documentation).
233
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 'core' and 'utils' as well 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 defer all the other JS files 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 to the r:external tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated link. There is no limit to the number of modules or xxxResources.groovy artefacts you can provide, and plugins can supply them to expose 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 closure to the grails.resources.modules Config variable. For full details of the resource DSL please see the resources plugin documentation.
234
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 separate bundles are 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 resource. For full details of the resource DSL please see the resources plugin documentation.
235
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.
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 default already compressed 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. At the time of writing none are publicly released but releases are imminent.
236
6.2.5.6 Debugging
When your resources are being moved around, renamed and otherwise mutated, it can be hard to debug client-side issues. Modern browsers, especially Safari, Chrome and Firefox have excellent tools that let you view all the resources requested by a page, including 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, indicating the original source file(s) that make up the response.
237
There is also an "includes" inverse. Note that settings these replaces the default includes/excludes for that mapper - it is not additive.
238
Although it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started, partition the page to be decorated using the <content> tag:
<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>
239
The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, you can make as many changes as you like but they won't be reflected in the running application until you restart. The second line tells Grails where to load the views and layouts from.
The trailing slash on the grails.gsp.view.dir value is important! Without it, Grails will look for 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 server's deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers 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 directory. On a Unix-like 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. So you end up with 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 at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views. There are also some System properties to control GSP reloading: Name grails.gsp.enable.reload grails.gsp.reload.interval Description altervative system property for enabling the GSP reload mode without changing Config.groovy interval between checking the lastmodified time of the gsp source 5000 file, unit is milliseconds Default
the number of milliseconds leeway to give before deciding a file grails.gsp.reload.granularity is out of date. this is needed because different roundings usually 1000 cause a 1000ms difference in lastmodified times GSP reloading is supported for precompiled GSPs since Grails 1.3.5 .
240
Adding "?showSource=true" or "&showSource=true" to the url shows the generated Groovy source code for the view instead of 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.keepgenerateddir" (in 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/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).
Each comment block has a unique id so that you can find the start & end of each template call.
Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content: 241
The attrs argument is a Map of the attributes of the tag, whilst the body argument is a Closure that returns the body content when 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 append content to the response. Then you can reference the tag inside your GSP; no imports are necessary:
<g:emoticon happy="true">Hi John</g:emoticon>
242
To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures with @attr descriptions. Since taglibs use Groovy code it can be 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) } }
243
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
The above uses Java's SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a 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 the content directly:
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:
244
def formatBook = { attrs, body -> out << render(template: "bookTemplate", model: [book: attrs.book]) }
And then have a separate GSP template that does the actual rendering.
The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:
<g:isAdmin user="${myUser}"> // some restricted content </g:isAdmin>
In this example we check for a times attribute and if it exists convert it to a number, then use Groovy's times method to iterate the 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 when we invoked the body we passed in the current value inside the iteration:
out << body(num)
245
That value is then passed as the default variable it to the tag. However, if you have nested tags this can lead to conflicts, so you should should instead name the variables that the body uses:
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 this line:
out << body((var):num)
Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are 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 that variable within the body of the tag.
Here we have specified a namespace of my and hence the tags in this tag lib must then be referenced from GSP pages like this:
<my:example name="..." />
246
where the prefix is the same as the value of the static namespace property. Namespaces are particularly useful for plugins. Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:
out << my.example(name:"foo")
With the added bonus that you can invoke JSP tags like methods:
${fmt.formatNumber(value:10, pattern:".00")}
Throughout the documentation so far the convention used for URLs has been the default of /controller/action/id. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at grails-app/conf/UrlMappings.groovy. The UrlMappings class contains a single property called mappings that has been assigned a block of code:
class UrlMappings { static mappings = { } }
In this case we've mapped the URL /product to the list action of the ProductController. Omit the action definition to map 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 explicit URI (rather than a controller/action pair) do something like this:
"/hello"(uri: "/hello.dispatch")
Rewriting specific URIs is often useful when integrating with other frameworks.
248
The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash, '/'. A concrete token is one which is well defined such as as /product. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:
static mappings = { "/product/$id"(controller: "product") }
In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the params object) called id. For example given the URL /product/MacBook, the following code will render "MacBook" to 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 format could be mapped as follows:
static mappings = { "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show") }
The individual tokens in the URL would again be mapped into the params object with values available for year, month, day, id and so on.
Here the name of the controller, action and id are implicitly obtained from the variables controller, action and id embedded within the URL. You can also resolve the controller name and action name to execute dynamically using a closure:
249
Optional Variables
Another characteristic of the default mapping is the ability to append a ? at the end of a variable to make it an optional token. In a 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 params object:
Arbitrary Variables
You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the block passed to the mapping:
"/holiday/win" { id = "Marrakech" year = 2007 }
This variables will be available within the params object passed to the controller.
250
In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic.
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 }
251
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 illegalArgument action in ErrorsController, a NullPointerException will be handled by the nullPointer action, and a MyException will be handled by the customException action. Other exceptions will be handled by the catch-all rule and use the /errors/serverError view. You can access the exception from your custom error handing view or controller action using the request's exception attribute like 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 with a StackOverflowException.
252
This mapping will match all paths to images such as /image/logo.jpg. Of course you can achieve the same effect with a variable:
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") }
In this cases the mapping will match /image/logo.jpg as well as /image/other/logo.jpg. Even better you can use a 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 object:
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 process. To do this you can 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.
Another great feature of URL mappings is that they automatically customize the behaviour of the link tag so that changing the 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 given a mapping such as the blog one from an earlier section:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
254
This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to 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 relieving you of that burden later on.
For example:
static mappings = { name personList: "/showPeople" { controller = 'person' action = 'list' } name accountDetails: "/details/$acctNumber" { controller = 'product' action = 'accountDetails' } }
Alternatively you may reference a named mapping using the link namespace.
<link:personList>List People</link:personList>
To specify attributes that should be applied to the generated href, specify a Map value to the attrs attribute. These attributes will be 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>
256
The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named addNumbers in a controller named MathHelperController would be something like /mathHelper/addNumbers. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated URLs assign a value 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 adding an instance of that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NAME. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the 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 in URLs } }
257
Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the next. Since the state is managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some multi step flow, as web flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and any application that has multi page work flows.
From Grails 1.2 onwards Webflow is no longer in Grails core, so you must install the Webflow plugin to 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 example:
class BookController { def index() { redirect(action: "shoppingCart") } def shoppingCartFlow = { } }
Notice when redirecting or referring to the flow as an action we omit the Flow suffix. In other words the name of the action of the above flow is shoppingCart.
Here the showCart node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a view state that, by convention, refers to the view grails-app/views/book/shoppingCart/showCart.gsp.
258
Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow: grails-app/views/book/shoppingCart. The shoppingCart flow also has two possible end states. The first is displayCatalogue which performs an external redirect to another controller and action, thus exiting the flow. The second is displayInvoice which is an end state as it has no events at all and will simply render a view called grails-app/views/book/shoppingCart/displayInvoice.gsp whilst ending the 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 state.
It will look for a view called grails-app/views/book/shoppingCart/enterPersonalDetails.gsp by default. Note that the enterPersonalDetails state defines two events: submit and return. The view is responsible for triggering these events. Use the render method to change the view to be rendered:
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 view parameter with a / to use a shared view:
enterPersonalDetails { render(view: "/shared/enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }
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 dictate flow transition. To create an action state you define an action to to be executed. This is done by calling the action method and passing it a block of code to be executed: 259
As you can see an action looks very similar to a controller action and in fact you can reuse controller actions if you want. If the action successfully returns with no errors the success event will be triggered. In this case since we return a Map, which is regarded as the "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:
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 Order object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".
Transition Actions
Another form of action is what is known as a transition action. A transition action is executed directly prior to state transition once an event has been triggered. A simple example of a transition action can be seen below:
260
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 very useful for data binding and validation, which is covered in a later section.
Since the showCart event is a view state it will render the view grails-app/book/shoppingCart/showCart.gsp. Within this view you need to have components that trigger flow execution. On a form this can be done use the submitButton tag:
<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 signals which event 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" />
261
Prior to 2.0.0, it was required to specify the controller and/or action in forms and links, which caused the url to change when entering a subflow state. When the controller and action are not specified, all url's are relative to the main flow execution url, which makes your flows reusable as subflows and prevents issues with the browser's back button.
In this case because of the error the transition action will make the flow go back to the enterPersonalDetails state. 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" }
Grails service classes can be automatically scoped to a web flow scope. See the documentation on Services for more information. Returning a model Map from an action will automatically result in the model being placed in flow scope. For example, using a 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 state (for example) will not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another. Also note that Web 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 shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).
To place an instance of the Book class in a flow scope you will need to modify it as follows:
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 }
263
Here if the Author association is not Serializable you will also get an error. This also impacts closures used in GORM events such as onLoad, onSave and so on. The following domain class will cause an error if an instance is placed in a flow scope:
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 declare all events as 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" } }
The flow scope contains a reference to the Hibernate session. As a result, any object loaded into the session 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 evict the entity manually before the end of the state:
flow.persistenceContext.evict(it)
264
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 use a flow transition 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 scope. Also interesting is that we perform validation and invoke the error() method if validation fails. This signals to the flow that the transition should halt and return to the enterPersonalDetails view so valid entries can be entered by the user, otherwise the transition should 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 the closure:
enterPersonalDetails { on("submit") { PersonDetailsCommand cmd -> flow.personDetails = cmd !flow.personDetails.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }
265
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 defined in the same controller as the calling flow. Prior to 1.3.5, the previous subflow call would look like subflow(new SearchExtensionsController().extendedSearchFlow), with the requirement that the name of the subflow state be the same as the called subflow (minus Flow). This way of calling a subflow is deprecated and only supported for backward compatibility. The subflow is another flow entirely:
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 lets you share state that spans the whole conversation, i.e. a flow execution including all subflows, not just the flow itself. Also notice that the end state (either moreResults or noResults of the subflow triggers the events in the main flow:
266
extendedSearch { // Extended search subflow subflow(controller: "searchExtensions", action: "extendedSearch") on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" }
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 input. The consequence 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 evaluated at the end of each flow execution. If the value is not a closure, the value will be a constant that is only calculated once at flow definition time. When a subflow is called, we can provide it a map with input values: 267
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" } ... }
Notice again the difference between constant values like expertise : "management" and dynamic values like expertise : { flow.technology } The subflow output is available via currentEvent.attributes
6.6 Filters
Although Grails controllers support fine grained interceptors, these are only really useful when applied to a few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied across a whole group of controllers, a URI space or to a specific action. Filters are far easier to plugin and maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns such as security, logging, and so on.
Each filter you define within the filters block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example to define a filter that applies to all controllers and all actions you can use wildcards:
sampleFilter(controller:'*', action:'*') { // interceptor definitions }
268
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 compiled 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 java.util.regex.Matcher.find()) invert (true/false) - invert the rule (NOT rule) Some examples of filters include: All controllers and actions with partial match (see
269
All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'
someURIs(uri: '/book/**') { }
allURIs(uri: '/**') { }
In addition, the order in which you define the filters within the filters code block dictates the order in which they are executed. To control the order of execution between Filters classes, you can use the dependsOn property discussed in filter dependencies section.
Note: When exclude patterns are used they take precedence over the matching patterns. For example, if action is 'b*' and actionExclude is 'bad*' then actions like 'best' and 'bien' will have that filter applied but actions like 'bad' and 'badlands' will not.
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 the session and if not 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:
271
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 } } } } }
272
In this logging example we just log various request information, but note that the model map in the after filter is mutable. If you need to add or remove items from the model map you can do that in the after filter.
273
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 } } } } }
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 scope matches the current request to be executed before those in MyFilters. For a request of "/test", which will match the scope of every filter in the example, the 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 class. Execution order between Filters classes are enabled and the execution order of filters within each Filters class are preserved. If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of the filter chain and processing will continue. Information about any cyclical dependencies that are detected will be written to the logs. Ensure that your root logging level is set to at least WARN or configure an appender for the Grails Filters Plugin ( org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin) when debugging filter dependency issues.
6.7 Ajax
274
Ajax is the driving force behind the shift to richer web applications. These types of applications in general are better suited to agile, dynamic frameworks written in languages like Groovy and Ruby Grails provides support for building Ajax applications through its Ajax tag library. For a full list of these see the Tag Library Reference.
You can replace jQuery with any other library supplied by a plugin you have installed. This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to): jQuery Prototype Dojo YUI MooTools
The above link sends an asynchronous request to the delete action of the current controller with an id of 1.
275
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 case "Book 1 was deleted". This is done by the update attribute on the tag, which can also take a Map to indicate what should be updated on failure:
<div id="message"></div> <div id="error"></div> <g:remoteLink update="[success: 'message', failure: 'error']" action= "delete" id="1"> Delete Book </g:remoteLink>
Or alternatively you can use the submitToRemote tag to create a submit button. This allows some buttons to submit remotely and some 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>
276
The above code will execute the "showProgress()" function which may show a progress bar or whatever is appropriate. Other events 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 found!')") 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:
<g:javascript> function fireMe(e) { alert("XmlHttpRequest = " + e) } } </g:javascript> <g:remoteLink action="example" update="success" onSuccess= "fireMe(e)">Ajax Link</g:remoteLink>
This will download the current supported version of the Prototype plugin and install it into your Grails project. With that done you can add the following reference to the top of your page:
<g:javascript library="prototype" />
277
Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Prototype remoting.
This will download the current supported version of Dojo and install it into your Grails project. With that done you can add the 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.
278
And then on the client parse the incoming JSON request using an Ajax event handler:
<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>
279
The important thing to remember is to set the contentType to text/javascript. If you use Prototype on the client the returned 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 client breaking the server. This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature such as RJS there is a Dynamic JavaScript Plugin that offers similar capabilities.
def listBooks() { def books = Book.list(params) if (request.xhr) { render template: "bookTable", model: [books: books] } else { render view: "list", model: [books: books] } }
The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.
Which simply means anything. However, on newer browser something all together more useful is sent such as (an example of a Firefox Accept header):
text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5
281
Grails parses this incoming format and adds a property to the response object that outlines the preferred response format. For the 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. If you have an older 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 Controllers you can use the 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 a view called either grails-app/views/books/list.html.gsp or grails-app/views/books/list.gsp. If the format is xml then the 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 whichever one you want 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 of the withFormat method is used by the action to dictate what happens next.
282
The withFormat available on controllers deals specifically with the response format. If you wish to add logic that deals with the request format then you can do so using a separate withFormat method available on the request:
request.withFormat { xml { // read XML } json { // read JSON } }
You can also define this parameter in the URL Mappings definition:
"/book/list"(controller:"book", action:"list") { format = "xml" }
Grails will remove the extension and map it to /book/list instead whilst simultaneously setting the content format to xml based on this extension. This behaviour is enabled by default, so if you wish to turn it off, you must set the grails.mime.file.extensions property in grails-app/conf/Config.groovy to false:
grails.mime.file.extensions = false
283
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 }
284
7 Validation
Grails validation capability is built on Spring's Validator API and data binding capabilities. However Grails takes this further and 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 domain classes, however URL Mappings and Command Objects also support constraints.
You then use method calls that match the property name for which the constraint applies in combination with named parameters to 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 be blank and must be 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: false constraint).
A complete reference for the available constraints can be found in the Quick Reference section under the Constraints heading. Note that constraints are only evaluated once which may be relevant for a constraint that relies on a value like an instance of java.util.Date.
285
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() } }
See how the inList constraint references the instance property survey? That won't work. Instead, use a custom validator:
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 can access its survey property and return a boolean to indicate whether the new value for the answer property, val, is valid.
286
def user = new User(params) if (user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }
The errors property on domain classes is an instance of the Spring Errors interface. The Errors interface provides methods to 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 request parameters onto 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 Strings to Dates). You 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 bound values againts the constraints you defined. For example, by default the save method calls validate before executing, allowing you to write code like:
if (user.save()) { return user } else { user.errors.allErrors.each { println it } }
287
Typically if you get a validation error you redirect back to the view for rendering. Once there you need some way of displaying errors. 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 also be done with the hasErrors by invoking it as a method. For example:
<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 the div, allowing you to use CSS rules to highlight the div.
This code will check for an existing FieldError in the User bean and if there is obtain the originally input value for the login field.
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 the following in your grails-app/i18n/messages.properties file:
user.login.blank=Your login name must be specified!
The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, com.mycompany.myapp.User.login.blank will be used before user.login.blank. This allows for cases where your domain class message 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 of rendering you can 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 argument to read the message for the given error.
Domain classes and command objects support validation by default. Other classes may be made validateable by defining the static constraints property in the class (as described above) and then telling the framework about them. It is important that the application register the validateable classes with the framework. Simply defining the constraints property is not sufficient.
290
Creating a Service
You can create a Grails service by running the create-service command from the root of your project in a terminal window:
grails create-service helloworld.simple
If no package is specified with the create-service script, Grails automatically uses the application name as the package name. The above example will create a service at the location grails-app/services/helloworld/SimpleService.groovy. A service's name ends with the convention Service, other than that a service is a plain Groovy class:
package helloworld class SimpleService { }
291
You may also set this property to true to make it clear that the service is intentionally transactional.
Warning: dependency injection is the only way that declarative transactions work. You will not get a 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 runtime exception (i.e. one that extends RuntimeException) or an Error. The propagation level of the transaction is by default set to PROPAGATION_REQUIRED.
Checked exceptions do not roll back transactions. Even though Groovy blurs the distinction between checked and unchecked exceptions, Spring isn't aware of this and its default behaviour is used, so it's important to understand the distinction between checked and unchecked exceptions.
Annotating a service method with Transactional disables the default Grails transactional behavior for that service (in the same way that adding transactional=false does) so if you use any annotations you must annotate all methods that require transactions. In this example listBooks uses a read-only transaction, updateBook uses a default read-write transaction, and deleteBook is 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 override that default per-method. For example, this service is equivalent to one that has no annotations (since the default is implicitly transactional=true): 292
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 listBooks method 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 from the class-level 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 needed and Grails will detect them up automatically.
293
class Author { String name Integer age static hasMany = [books: Book] }
Only the second author would be saved since the first transaction rolls back the author save() by clearing the Hibernate session. If the Hibernate session were not cleared then both author instances would be persisted and it would lead to very unexpected results. 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}" } } }
294
In the above example the transaction will be rolled back if the Author's age exceeds the maximum value defined in the isTooOld() method by throwing an AuthorException. The AuthorException references the author but when the books association is accessed a LazyInitializationException will be thrown because the underlying Hibernate session has been cleared. To solve this problem you have a number of options. One is to ensure you query eagerly to get the data you will need:
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 retrieve the data for the 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}" } } }
295
To re-render the same view that a transaction was rolled back in you can re-associate the errors with a refreshed instance before 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] } } }
296
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 sub flows 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 must implement java.io.Serializable and can only be used in the context of a Web Flow
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"
In this case, the Spring container will automatically inject an instance of that service based on its configured scope. All dependency injection is done by name. You can also specify the type as follows:
class AuthorService { BookService bookService }
297
NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an 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 upper case, the property name is the same as the class name. For example, the property name of the JDBCHelperService class would be JDBCHelperService, not jDBCHelperService or jdbcHelperService . See section 8.8 of the JavaBean specification for more information on de-capitalization rules.
298
However, this can be rectified by placing this class in a package, by moving the class into a sub directory such as 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) }
This latter technique is arguably cleaner, as the Java side only has a reference to the interface and not to the implementation class (although it's always a good idea to use packages). Either way, the goal of this exercise to enable Java to statically resolve the class (or 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 type and the name of 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/resources.xml (for more information see the section on Grails and Spring):
299
or in grails-app/conf/spring/resources.groovy:
import bookstore.BookConsumer beans = { bookConsumer(BookConsumer) { bookStore = ref("bookService") } }
300
9 Testing
Automated testing is a key part of Grails. Hence, Grails provides many ways to making testing easier from low level unit testing to 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 testing in a JUnit 3 style. Grails 2.0.x and above deprecates these test harnesses in favour of mixins that can be applied 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 integration tests 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.groovy, and also a unit test at test/unit/com/acme/app/SimpleControllerTests.groovy. What Grails won't do however is populate the 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
301
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 original XML files. The HTML reports are generally the best ones to look at. Using Grails' interactive mode confers some distinct advantages when executing tests. First, the tests will execute significantly faster 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 SimpleController you 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
302
This will run the testLogin test in the SimpleController tests. You can specify as many patterns in combination as you like...
grails test-app some.org.* SimpleController.testLogin BookController
Grails organises tests by phase and by type. A test phase relates to the state of the Grails application during the tests, and the type relates to the testing mechanism. Grails comes with support for 4 test phases (unit, integration, functional and other) and JUnit test types for the unit and integration phases. These test types have the same name as the phase. Testing plugins may provide new test phases or new test types for existing phases. Refer to the plugin 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 test types in the unit 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, integration and 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
303
This would run all tests in the integration and unit phases that are in the package some.org or a subpackage.
The previous JUnit 3-style GrailsUnitTestCase class hierarchy is still present in Grails for backwards compatibility, but is now deprecated. The previous documentation on the subject can be found in the Grails 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 find that your IDE for example can't find the classes, here they all are:
304
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.
The TestFor annotation defines the class under test and will automatically create a field for the type of class under test. For example in the above case a "controller" field will be present, however if TestFor was defined for a service a "service" field would be created and so on. The Mock annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API. For those interactions that are not automatically mocked you can use the built in support for 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" }
You use the grails.test.mixin.TestFor annotation to unit test controllers. Using TestFor in this manner activates the 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 for the controller under test.
The TestFor annotation will also automatically annotate any public methods starting with "test" with 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" } }
The response object is an instance of GrailsMockHttpServletResponse (from the package org.codehaus.groovy.grails.plugins.testing) which extends Spring's MockHttpServletResponse class and 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' } }
306
Many actions make use of the parameter data associated with the request. For example, the 'sort', 'max', and 'offset' parameters are quite 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 request:
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, you can mark a request as AJAX like so:
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.
307
// 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 the directory named after the action's controller.
In this example the controller will look for a template grails-app/views/simple/_snippet.gsp. You can test this as follows:
void testDisplay() { controller.display() assert response.text == 'contents of template' }
in
However, you may not want to render the real template, but just test that is was rendered. In this case you can provide mock Groovy Pages:
void testDisplay() { views['/simple/_snippet.gsp'] = 'mock contents' controller.display() assert response.text == 'mock contents' }
When a controller action returns a java.util.Map that Map may be inspected directly to assert that it contains the expected data:
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' } }
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" } }
309
// 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 which is a map-like structure that is useful for parsing JSON responses.
To test this Grails provides an easy way to specify an XML or JSON packet via the xml or json properties. For example the above 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 request:
void testConsumeBookXml() { request.xml = new Book(title:"The Shining") controller.consumeBook() assert response.text == 'The Shining' }
310
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 tested too. For example 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' }
311
The controller is auto-wired by Spring just like in a running Grails application. Autowiring even occurs if you instantiate subsequent 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 }
// 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 }
you want to verify the logic that is executed on a good form submission and the logic that is executed on a duplicate submission. Testing the bad submission is simple. Just invoke the controller:
void testDuplicateFormSubmission() { controller.handleForm() assert "Bad" == response.text }
If you test both the valid and the invalid request in the same test be sure to reset the response between executions of the controller:
controller.handleForm() // first execution response.reset() controller.handleForm() // second execution
To test this action you can register a GrailsMockMultipartFile with the request:
313
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 mock implementation of the transferTo method that simply records the targetFileLocation and doesn't write to disk.
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' }
314
void testRenderBasicTemplateWithTags() { messageSource.addMessage("foo.bar", request.locale, "Hello World") controller.showMessage() assert response.text == "Hello World" }
Note that if you are testing invocation of a custom tag from a controller you can combine the ControllerUnitTestMixin and the GroovyPageUnitTestMixin using the Mock annotation:
@TestFor(SimpleController) @Mock(SimpleTagLib) class GroovyPageUnitTestMixinTests { }
You can test this tag library by using TestFor and supplying the name of the tag library:
315
@TestFor(SimpleTagLib) class SimpleTagLibTests { void testHelloTag() { assert applyTemplate('<s:hello />') == 'Hello World' assert applyTemplate('<s:hello name="Fred" />') == 'Hello Fred' } }
Alternatively, you can use the TestMixin annotation and mock multiple tag libraries using the mockTagLib() method:
@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 equals or matches an 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" />') } }
This will attempt to render a template found at the location grails-app/views/simple/_hello.gsp. Note that if the template depends on any custom tag libraries you need to call mockTagLib as described in the previous section.
316
Overview
The mocking support described here is best used when testing non-domain artifacts that use domain classes, to let you focus on testing the artifact without needing a database. But when testing persistence it's best to use integration tests which configure Hibernate and use a database. Domain class interaction can be tested without involving a database connection using DomainClassUnitTestMixin. This implementation mimics the behavior of GORM against an in-memory ConcurrentHashMap implementation. Note that this has limitations compared to a real GORM implementation. The following features of GORM for Hibernate can only be tested within an 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 DomainClassUnitTestMixin including: 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 mock the missing pieces. Alternatively you can write an integration test which bootstraps the complete Grails environment at a cost of test execution time.
The Basics
DomainClassUnitTestMixin is typically used in combination with testing either a controller, service or tag library where the domain is a mock collaborator defined by the Mock annotation:
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 as well. For example consider a typical scaffolded save controller action: 317
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]) } } }
Mock annotation also supports a list of mock collaborators if you have more than one domain to mock:
@TestFor(BookController) @Mock([Book, Author]) class BookControllerTests { }
Alternatively you can also use the DomainClassUnitTestMixin directly with the TestMixin annotation:
318
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 configure a domain, which is 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 tricky to track down (particularly as by default save() doesn't throw an exception when it fails). If your answer is that it's too hard or fiddly, that is no longer an excuse. Enter the mockForConstraintsTests() method. This method is like a much reduced version of the mockDomain() method that simply adds a validate() method to a given domain class. All you have to do is mock the class, create an instance with populated data, and then call validate(). You can then access the errors property to determine if validation failed. So if all we are doing is mocking the validate() method, why the 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:
class Book { String title String author static constraints = { title blank: false, unique: true author blank: false, minSize: 5 } }
319
Don't worry about whether the constraints are sensible (they're not!), they are for demonstration only. To test these constraints we can 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 thing we will explain is the way the errors property is used. First, is a real Spring Errors instance, so you can access all the properties and methods you would normally expect. Second, this particular Errors object also has map/property access as shown. Simply specify the name of the field you are interested in and the map/property access will return the name of the constraint that was violated. Note that it is the 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 catches a common error: typos in the "constraints" property name! It is currently one of the hardest bugs to track down normally, and yet a unit test for your constraints will highlight the problem straight away.
320
This filter interceptors the list action of the simple controller and redirects to the book controller. To test this filter you start off with a test that targets the SimpleController class and add the CancellingFilters as a mock collaborator:
@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 execution:
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 actually called. The controller parameter is optional and taken from the controller under test. If it is a another controller you are testing then you can specify it:
withFilters(controller:"book",action:"list") { controller.list() }
Note that since the default UrlMappings class is in the default package your test must also be in the default package With that done there are a number of useful methods that are defined by the grails.test.mixin.web.UrlMappingsUnitTestMixin for testing URL mappings. These include:
321
assertForwardUrlMapping - Asserts a URL mapping is forwarded for the given controller class (note that controller will 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 given controller and action assertUrlMapping - Asserts a URL mapping is valid for the given URL. This combines the assertForwardUrlMapping and assertReverseUrlMapping assertions
322
@TestFor(SimpleController) @Mock(UrlMappings) class SimpleControllerTests { void testControllerMapping() { SimpleController controller = mapURI('/simple/list') assert controller != null def model = controller.list() assert model != null } }
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 which the order in which 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 name of the method to mock, with an optional range argument. This range determines how many times you expect the method to be called, and if the number of invocations falls outside of that range (either too few or too many) then an assertion error will be thrown. If no range is specified, a 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 arguments must match the number and types of the mocked method, but otherwise you are free to add whatever you want in the body. Call mockControl.createMock() to get an actual mock instance of the class that you are mocking. You can call this multiple times to create as many mock instances as you need. And once you have executed the test method, call mockControl.verify() 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 matter. 323
the "starting tests" message is logged using a different system than the one used by the application. The log property in the example above is an instance of java.util.logging.Logger (inherited from the base class, not injected by Grails), which doesn't have the same methods as the log property injected into your application artifacts. For example, it doesn't have debug() or trace() 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 means that data saved during a test is not persisted to the database. Add a transactional property to your test class to check transactional behaviour:
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 these tests don't interfere 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 MockHttpSession that you can use in your tests. For example consider the following controller:
324
In the above case response is an instance of MockHttpServletResponse which we can use to obtain the generated content with contentAsString (when writing to the response) or the redirected URL. These mocked versions of the Servlet API are completely mutable (unlike the real versions) and hence you can set properties on the request such as the contextPath and so on. Grails does not invoke interceptors or servlet filters when calling actions during integration testing. You should test interceptors and filters in isolation, using functional testing if necessary.
325
class FilmStarsTests extends GroovyTestCase { def popularityService void testInjectedServiceInController () { def fsc = new FilmStarsController() fsc.popularityService = popularityService fsc.update() } }
Grails auto-magically sees your call to signup() as a call to the action and populates the command object from the mocked request parameters. During controller testing, the params are mutable with a mocked request supplied by Grails.
326
In the above example the result of the model of the action is not available as the return value, but instead is stored within the modelAndView property of the controller. The modelAndView property is an instance of Spring MVC's ModelAndView class and you can use it to the test the result of an action:
def bookController = new BookController() bookController.save() def model = bookController.modelAndView.model.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 }
327
With JSON don't forget the class property to specify the name the target type to bind to. In XML this is implicit within the name of the <book> node, but this property is required as part of the JSON packet. For more information on the subject of REST web services see the section on REST.
You need to tell the test harness what to use for the "flow definition". This is done via overriding the abstract getFlow method:
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:
328
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() }
Here we have signaled to the flow to execute the event "go" which causes a transition to the "next" state. In the example a transition action placed a hello variable into the flow scope.
329
class FooTagLib { def bar = { attrs, body -> out << "<p>Hello World!</p>" } def bodyTag out out out } } = { attrs, body -> << "<${attrs.name}>" << body() << "</${attrs.name}>"
Notice that for the second example, testBodyTag, we pass a block that returns the body of the tag. This is convenient to representing the body as a String.
330
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 class:
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 } }
This test will fail because calling save does not actually persist the Book instances when called. Calling save only indicates to Hibernate that at some point in the future these instances should be persisted. To commit changes immediately you "flush" them:
void testQuery() { def books = [ new Book(title: "The Stand"), new Book(title: "The Shining")] books*.save(flush: true) assertEquals 2, Book.list().size() }
331
In this case since we're passing the argument flush with a value of true the updates will be persisted immediately and hence will be available to the query later on.
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 tests your application in a production-like state, but it has a longer startup time than the -inline option. It also runs the war in a forked JVM, meaning that 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 compatible with both the -inline and -war options.
grails test-app functional: -https
332
Note that this does not change the test base url to be https, it will still be http unless the -httpsBaseUrl option is also given.
httpsBaseUrl
The -httpsBaseUrl causes the implicit base url to be used for tests to be a https url.
grails test-app functional: -httpsBaseUrl
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 use a custom base url but still test against the local Grails application you must specify one of either the -inline or -war options.
333
10 Internationalization
Grails supports Internationalization (i18n) out of the box by leveraging the underlying Spring MVC internationalization support. With Grails you are able to customize the text that appears in a view based on the user's Locale. To quote the javadoc for the Locale class: A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's 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, whilst "en_GB" is the for British English.
Grails will automatically switch the user's locale and store it in a cookie so subsequent requests will have the new header.
334
As long as you have a key in your messages.properties (with appropriate locale suffix) such as the one below then Grails will look up the message:
my.localized.content=Hola, Me llamo John. Hoy es domingo.
The message declaration specifies positional parameters which are dynamically specified:
my.localized.content=Hola, Me llamo {0}. Hoy es {1}.
The same technique can be used in tag libraries, but if your tag library uses a custom namespace then you must prefix the call with g.:
def myTag = { attrs, body -> def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes']) }
335
11 Security
Grails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinning the code. Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write.
336
def safe() { def books = Book.find("from Book as b where b.title = ?", [params.title]) }
or
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 communication policy with your customers. Customers need to know how to identify valid emails.
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 not cause the expected behaviour, and may redirect to another site or alter request parameters.
337
HTML/URL injection is easily handled with the codecs supplied by Grails, and the tag libraries supplied by Grails all use encodeAsURL where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.
Denial of service
Load balancers and other appliances are more likely to be useful here, but there are also issues relating to excessive queries for example where a link is created by an attacker to set the maximum value of a result set so that a query could exceed the memory limits of the server or slow the system down. The solution here is to always sanitize request parameters before passing them to dynamic finders or other GORM query methods:
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. Especially in the case of 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 returning the response to the user. Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on. You must assume that every unprotected URL is publicly accessible one way or another.
Codec Classes
A Grails codec class is one that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails 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. For example one of the 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 Object class with a name representing the codec that defined the encode closure. For example, the HTMLCodec class defines an encode closure, so Grails attaches it with the name encodeAsHTML.
338
The HTMLCodec and URLCodec classes also define a decode closure, so Grails attaches those with the names decodeHTML and decodeURL respectively. Dynamic codec methods may be invoked from anywhere in a Grails application. For example, consider a case where a report contains a property called 'description' which may contain special characters that must be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:
${report.description.encodeAsHTML()}
Standard Codecs
HTMLCodec This codec performs HTML escaping and unescaping, so that values can be rendered safely in an HTML page without creating any HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn't be able to show this safely within an HTML page because the > will look like it closes a tag, which is especially bad if you render this data within an attribute, such as the value attribute of an input field. 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 quotes 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 URL. It prevents illegal characters from getting into the URL and changing its meaning, for example "Apple & Blackberry" is not going to work well as a 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>
339
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 into byte arrays. For 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 encoding), as a lowercase hexadecimal string. Example of usage:
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 encoding), as a byte array. 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 encoding), as a lowercase 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 encoding), as a byte array. Example of usage:
340
SHA256Codec Uses the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a 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 encoding), as a byte array. Example of usage:
byte[] passwordHash = params.password.encodeAsSHA256Bytes()
Custom Codecs
Applications may define their own codecs and Grails will load them along with the standard codecs. A custom codec class must be defined in the grails-app/utils/ directory and the class name must end with Codec. The codec may contain a static encode closure, a static decode closure or both. The closure must accept a single argument which will be the object that the 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()}
11.3 Authentication
Grails has no default mechanism for authentication as it is possible to implement authentication in many different ways. It is however, easy to implement a simple authentication mechanism using either interceptors or filters. This is sufficient for simple use cases but it's highly preferable to use an established security framework, for example by using the Spring Security or the Shiro plugin. Filters let you apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called grails-app/conf/SecurityFilters.groovy by running: 341
Here the loginCheck filter intercepts execution before all actions except login are executed, and if there is no user in the session then redirect to the login action. The login action itself is simple too:
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"]) } }
342
There is a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc. and secondary dependent plugins provide alternate functionality such as OpenID authentication, ACL support, single sign-on with Jasig CAS, LDAP authentication, Kerberos authentication, and a plugin providing user interface extensions and security workflows. See the Core plugin page for basic information and the user guide for detailed information.
11.4.2 Shiro
Shiro is a Java POJO-oriented security framework that provides a default domain model that models realms, users, roles and permissions. With Shiro you extend a controller base class called called JsecAuthBase in each controller you want secured and then 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' ]) } }
343
12 Plugins
Grails is first and foremost a web application framework, but it is also a platform. By exposing a number of extension points that let you extend anything from the command line interface to the runtime configuration engine, Grails can be customised to suit almost any 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 powerful. If you know how to build a Grails application, you'll know how to create a plugin for sharing a data model or some static resources.
This will create a plugin project for the name you specify. For example running grails create-plugin example would create 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 of the plugin directory you will find a plugin Groovy file called the "plugin descriptor". Being a regular Grails project has a number of benefits in that you can immediately test your plugin by running:
grails run-app
The plugin descriptor name ends with the convention GrailsPlugin and is found in the root of the plugin project. For example:
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 the plugin and other metadata, and optionally various hooks into plugin extension points (covered shortly). You can also provide additional information about your plugin using several special properties:
344
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 1.2 or higher) 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" }
This will create a zip file of the plugin starting with grails- then the plugin name and version. For example with the example plugin created earlier this would be grails-example-0.1.zip. The package-plugin command will also generate a plugin.xml 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
345
346
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, for example:
grails install-plugin webtest -global
The default location is $USER_HOME/.grails/<grailsVersion>/global-plugins but this can be customized with the grails.global.plugins.dir setting in BuildConfig.groovy.
which lists all plugins that are in the central repository. Your plugin will also be available to the plugin-info command:
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 instructions 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-plugin command to release your plugin:
grails install-plugin release grails publish-plugin
347
This will automatically commit any remaining source code changes to your SCM provider and then publish the plugin to the central repository. If the command is successful, it will immediately be available on the plugin portal at http://grails.org/plugin/<pluginName>. You can find out more about the Release plugin and its other features in its user guide.
You can also define a SVN-based Grails repository (such as the one hosted at http://plugins.grails.org) using the grailsRepo method:
repositories { grailsRepo "http://myserver/mygrailsrepo" // ...or with a name grailsRepo "http://myserver/svn/grails-plugins", "mySvnRepo" }
The order in which plugins are resolved is based on the ordering of the repositories. So in this case the Grails central repository will be 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 example that uses an SSH resolver:
348
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 detailed explanation on Ivy patterns see the relevant section in the Ivy user guide.
You can also provide this settings in the $USER_HOME/.grails/settings.groovy file if you prefer to share the same settings across multiple projects. Once this is done use the repository argument of the release-plugin command to specify the repository to release the plugin into:
grails release-plugin -repository = myRepository
349
+ 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 directory such as plugins/example-1.0/grails-app. They will not be copied into the main source tree. A plugin never interferes with a project's primary source tree. Dealing with static resources is slightly different. When developing a plugin, just like an application, all static resources go in the web-app directory. You can then link to static resources just like in an application. This example links to a JavaScript source:
<g:resource dir="js" file="mycode.js" />
When you run the plugin in development mode the link to the resource will resolve to something like /js/mycode.js. However, when the plugin is installed into an application the path will automatically change to something like /plugin/example-0.1/js/mycode.js and Grails will deal with making sure the resources are in the right place. There is a special pluginContextPath variable that can be used whilst both developing the plugin and when in the plugin is 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/example depending on 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 be compiled into the main project's web-app/WEB-INF/classes directory so that they are made available at runtime.
350
Note the usage of the plugin attribute, which contains the name of the plugin where the template resides. If this is not specified then Grails will look for the template relative to the application.
Excluded Artefacts
By default Grails excludes the following files during the packaging process:
351
grails-app/conf/BootStrap.groovy grails-app/conf/BuildConfig.groovy dependencies.groovy) 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 modify the plugin's 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 you are free to add a UrlMappings definition under a different name which will be included. For example a file called 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" ]
(although
it
is
used
to
generate
This is useful for example to include demo or test resources in the plugin repository, but not include them in the final distribution.
352
GrailsApplication has a few "magic" properties to narrow the type of artefact you are interested in. For example to access 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.controllerClasses. get*Class - Retrieves a named class for a particular artefact. For example application.getControllerClass("PersonController") is*Class - Returns true if the given class is of the given artefact type. For example application.isControllerClass(PersonController) The GrailsClass interface has a number of useful methods that let you further evaluate and work with the conventions. These 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 applicable 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 with the package name getPropertyName - Returns the name of the class as a property name getLogicalPropertyName - Returns the logical property name of the class in the application without the trailing convention 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.
353
_Install.groovy is executed after the plugin has been installed and _Upgrade.groovy is executed each time the user 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 variables there is also a 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 directory and install a configuration template:
ant.mkdir(dir: "${basedir}/grails-app/jobs") ant.copy(file: "${pluginBasedir}/src/samples/SamplePluginConfig.groovy", todir: "${basedir}/grails-app/conf")
Scripting events
It is also possible to hook into command line scripting events. These are events triggered during execution of Grails target and plugin scripts. For example, you can hook into status update output (i.e. "Tests passed", "Server running") and the creation of files or artefacts. A plugin just has to provide an _Events.groovy script to listen to the required events. Refer the documentation on Hooking into Events for further information.
354
This plugin configures the Grails messageSource bean and a couple of other beans to manage Locale resolution and switching. It using the Spring Bean Builder syntax to do so.
Here the plugin gets a reference to the last <servlet-mapping> element and appends Grails' servlet after it using XmlSlurper's 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 matter since order is not important, so it's simplest to insert your custom filter definition immediately after the last <context-param> element. Order is 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'('/*') } } }
355
In some cases you need to ensure that your filter comes after one of the standard Grails filters, such as the Spring character encoding filter or the SiteMesh filter. Fortunately you can insert filter mappings immediately after the standard ones (more accurately, any that 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'('/*') } } }
356
In this case we use the implicit application object to get a reference to all of the controller classes' MetaClass instances and add a new method called myNewMethod to each controller. If you know beforehand the class you wish the add a method to you can simply 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() } }
Also because of the autowiring and dependency injection capability of the Spring container you can implement more powerful dynamic constructors that use the application context to wire dependencies into your object at runtime:
357
class MyConstructorPlugin { def doWithDynamicMethods = { applicationContext -> for (domainClass in application.domainClasses) { domainClass.metaClass.constructor = {-> return applicationContext.getBean(domainClass.name) } } } }
Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!
First it defines watchedResources as either a String or a List of strings that contain either the references or patterns of the resources to watch. If the watched resources specify a Groovy file, when it is changed it will automatically be reloaded and passed into 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
358
These objects are available to help you apply the appropriate changes based on what changed. In the "Services" example above, a new service bean is re-registered with the ApplicationContext when one of the service classes changes.
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 while the application is running.
359
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 and core plugins. The dependencies will be loaded before the Hibernate plugin and if all dependencies do not load, then the plugin will not load. The dependsOn property also supports a mini expression language for specifying version ranges. A few examples of the syntax can be seen below:
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 suffixes such as -BETA, -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
Here the plugin will be loaded after the controllers plugin if it exists, otherwise it will just be loaded. The plugin can then adapt to the presence of the other plugin, for example the Hibernate plugin has this code in its doWithSpring closure:
360
Here the Hibernate plugin will only register an OpenSessionInViewInterceptor if the controllers plugin has been loaded. The manager variable is an instance of the GrailsPluginManager interface and it provides methods to interact with other plugins. You can also use the loadBefore property to specify one or more plugins that your plugin should load before:
def loadBefore = ['rabbitmq']
In this example, the plugin will only load in the 'development' and 'test' environments. Nor will it be packaged into the WAR file, because it's excluded from the 'war' phase. This allows development-only plugins to not be packaged for production use. 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,
361
In this case, artefactType is the property name form of the artefact type. With core Grails you have:
362
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) { }
You need to be aware that the objects returned by these properties are not instances of Class. Instead, they are instances of GrailsClass that has some particularly useful properties and methods, including one for the underlying Class: 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 MyGreatController becomes '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 one. This works best 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'. The second will check whether a class is a particular type of artefact. For example, you can use grailsApplication.isControllerClass(org.example.MyGreatController) to check whether MyGreatController is in fact a controller.
363
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 interface. To make life a 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 GrailsClass. Again, skeleton implementations are available such as AbstractInjectableGrailsClass, which is particularly useful as it turns your artefact into a Spring 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.
Packaging
To package a plugin in binary form you can use the package-plugin command and the --binary flag: 364
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"
Since binary plugins are packaged as JAR files, they are declared as dependencies in the dependencies block, not in the plugins block as you may be naturally inclined to do. The plugins block is used for declaring traditional source plugins packaged as zip files
365
13 Web Services
Web services are all about providing a web API onto your web application and are typically implemented in either REST or SOAP
13.1 REST
REST is not really a technology in itself, but more an architectural pattern. REST is very simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system, and HTTP 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 for updating and so on. 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 and DELETE map to 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 or JSON marshalling unless you specify the parseRequest argument:
"/product/$id"(controller: "product", parseRequest: true) { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }
366
HTTP Methods
In the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then easy (example in Groovy's HTTPBuilder module):
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 help from Grails. When 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. Another alternative for changing the method for non-browser clients is to use the X-HTTP-Method-Override to specify the alternative method name.
If there is an id we search for the Product by name and return it, otherwise we return all Products. This way if we go to /products we get all products, otherwise if we go to /product/MacBook we only get a MacBook.
367
you can read this XML packet using the same techniques described in the Data Binding section, using the params object:
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 bind the XML using the 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 JSON request.
If you require different responses to different clients (REST, HTML etc.) you can use content negotation The Product object is then saved and rendered as XML, otherwise an error message is produced using Grails' validation capabilities in the form:
<error> <message>The property 'title' of class 'Person' must be specified</message> </error>
368
There also is a JAX-RS Plugin which can be used to build web services based on the Java API for RESTful Web Services (JSR 311: JAX-RS).
13.2 SOAP
There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a Spring WS plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this 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 taken from the CXF plugin:
class BookService { static expose = ['cxf'] Book[] getBooks() { Book.list() as Book[] } }
The WSDL can then be accessed at the http://127.0.0.1:8080/your_grails_app/services/book?wsdl For more information on the CXF plugin refer to the documentation on the wiki.
location:
369
370
You can easily register new (or override existing) beans by configuring them in grails-app/conf/spring/resources.groovy which uses the Grails Spring DSL. Beans are defined inside a beans property (a Closure):
beans = { // beans here }
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 injection (for example BootStrap.groovy and integration tests) by declaring a public field whose name is your bean's name (in this case myBean):
class ExampleController { def myBean }
Using the DSL has the advantage that you can mix bean declarations and logic, for example based on the environment:
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 to access the Grails configuration (amongst other things): 371
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 Grails or an installed plugin, your bean will replace the previous registration. This is a convenient way to customize behavior without resorting to editing plugin code or other approaches that would affect maintainability.
Using XML
Beans can also be configured using a grails-app/conf/spring/resources.xml. In earlier versions of Grails this file was automatically generated for you by the run-app script, but the DSL in resources.groovy is the preferred approach now so it 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 Spring beans. 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 }
372
Beans declared in resources.groovy or resources.xml can reference other beans by convention. For example if you had a BookService class its Spring bean name would be bookService, so your bean would reference it like this in the DSL:
beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" bookService = ref("bookService") } }
The bean needs a public setter for the bean reference (and also the two simple properties), which in Groovy would be defined like this:
package my.company class MyBeanImpl { Integer someProperty String otherProperty BookService bookService // or just "def bookService" }
Using ref (in XML or the DSL) is very powerful since it configures a runtime reference, so the referenced bean doesn't have to exist yet. As long as it's in place when the final application context configuration occurs, everything will be resolved correctly. 373
For a full reference of the available beans see the plugin reference in the reference guide.
Within plugins and the grails-app/conf/spring/resources.groovy file you don't need to create a new instance of BeanBuilder. Instead the DSL is implicitly available inside the doWithSpring and beans blocks 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 in Spring. The first argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you can set properties on the bean using standard Groovy syntax. 374
Bean references are resolved automatically using the name of the bean. This can be seen in the example above with the way the 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:
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.
375
You can use the BeanBuilder class to load external Groovy scripts that define beans using the same path matching syntax defined here. For example:
def bb = new BeanBuilder() bb.loadBeans("classpath:*SpringBeans.groovy") def applicationContext = bb.createApplicationContext()
Here the BeanBuilder loads all Groovy files on the classpath ending with SpringBeans.groovy and parses them into bean 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"] } }
Then you can access the maxSize and productGroup properties in your DSL files.
376
This configuration corresponds to a MyExampleBean with a constructor that looks like this:
MyExampleBean(String foo, int bar) { }
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" }
377
Another common approach is provide the name of the factory method to call on the factory bean. This can be done using Groovy's named parameter syntax:
bb.beans { myFactory(ExampleFactoryBean) { someProperty = [1, 2, 3] } myBean(myFactory: "getInstance") { name = "blah" } }
Here the getInstance method on the ExampleFactoryBean bean will be called to create the myBean bean.
In this case the beanName variable defined earlier is used when invoking a bean defining method. The example has a hard-coded value but would work just as well with a name that is generated programmatically based on configuration, system properties, etc. Furthermore, because sometimes bean names are not known until runtime you may need to reference them by name when wiring 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 method can also be used to refer to beans from a parent ApplicationContext that is provided in the constructor of the BeanBuilder:
378
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.
In the above example we set the marge bean's husband property to a block that creates an inner bean reference. Alternatively if you 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] } }
379
class KnightOfTheRoundTable { String name String leader HolyGrailQuest quest KnightOfTheRoundTable(String name) { this.name = name } def embarkOnQuest() { quest.start() } }
Here we define an abstract bean that has a leader property with the value of "Lancelot". To use the abstract bean set it as the 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 properties on the bean! If you want an abstract bean that has a Class specified you can do it this way:
380
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 set it to abstract. Later we define a knights bean that has no Class defined, but inherits the Class from the parent bean.
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 given JNDI name. With Spring namespaces you also get full access to all of the powerful AOP support in Spring from BeanBuilder. For example given these two classes:
381
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)" } } }
You can then specify placeholders in resources.xml as follows using the familiar ${..} syntax:
382
<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>
383
The individual mapping files, like 'org.example.Book.hbm.xml' in the above example, also go into the grails-app/conf/hibernate directory. To find out how to map domain classes with XML, check out the Hibernate manual. If the default location of the hibernate.cfg.xml file doesn't suit you, you can change it by specifying an alternative location in grails-app/conf/DataSource.groovy:
hibernate { config.location = "file:/path/to/my/hibernate.cfg.xml" }
Grails also lets you write your domain model in Java or reuse an existing one that already has Hibernate mapping files. Simply place the mapping files into grails-app/conf/hibernate and either put the Java files in src/java or the classes in the project's lib directory if the domain model is packaged as a JAR. You still need the hibernate.cfg.xml though!
To map a domain class with annotations, create a new class in src/java and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the Hibernate Annotations Docs):
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 by adding relevant entries to the grails-app/conf/hibernate/hibernate.cfg.xml file as follows:
<!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 with a Hibernate domain class see the section on Scaffolding.
385
You can still use GORM validation even if you use a Java domain model. Grails lets you define constraints through separate scripts in the src/java directory. The script must be in a directory that matches the package of the corresponding domain class and its name must have a Constraints suffix. For example, if you had a domain class org.example.Book, then you would create the script src/java/org/example/BookConstraints.groovy. 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!
386
16 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 scaffold property in the 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. To scaffold a specific 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. The following actions are dynamically implemented by default by the runtime scaffolding mechanism: list show edit delete create save update A CRUD interface will also be generated. http://localhost:8080/app/book in a browser. To access this open
If you prefer to keep your domain model in Java and mapped with Hibernate you can still use scaffolding, simply import the domain class and set its name as the scaffold argument. You can add new actions to a scaffolded controller, for example:
387
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) } }
All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runtime.
By default, the size of text areas in scaffolded views is defined in the CSS, so adding 'rows' and 'cols' attributes will have no effect. Also, the standard scaffold views expect model variables of the form <propertyName>InstanceList for collections and <propertyName>Instance for single instances. It's tempting to use properties like 'books' and 'book', but those won't work.
You can also get the generator to generate lists instead of text inputs if you use the inList constraint: 388
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 the logic and views. Grails lets you generate a controller and the views used to create the above interface from the command line. To generate a controller type:
grails generate-controller 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 include the fully qualified package name:
grails generate-all com.bookstore.Book
389
390
17 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 application during the development phase. An embedded Tomcat server is launched that loads the web application from the development sources, thus 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. Checking for and loading changes places a sizable overhead on the server. Having said that, grails prod run-app removes the per-request overhead and lets you fine tune how frequently the regular check takes place. Setting the system property "disable.auto.recompile" to true disables this regular check completely, while the property "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you want between each 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 development sources. Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsewhere.
WAR file
When it comes down to it, current java infrastructures almost mandate that web applications are deployed as WAR files, so this is by far the most common approach to Grails application deployment in production. Creating a WAR file is as simple as executing the war command:
grails war
There are also many ways in which you can customise the WAR file that is created. For example, you can specify a path (either 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 location and filename:
grails.project.war.file = "foobar-prod.war"
Any command line argument that you provide overrides this setting. 391
It is also possible to control what libraries are included in the WAR file, for example to avoid conflicts with libraries in a shared directory. The default behavior is to include in the WAR file all libraries required by Grails, plus any libraries contained in plugin "lib" directories, plus any libraries contained in the application's "lib" directory. As an alternative to the default behavior you can explicitly specify the complete list of libraries to include in the WAR file by setting the property grails.war.dependencies in BuildConfig.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are invoked from within an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is included. Any closure or 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 certainly fail. Here is 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 own application, the application will probably not work. You can find a list of dependencies required by Grails in the "dependencies.txt" file in the root directory of the unpacked distribution. You can also find a list of the default dependencies included in WAR generation in the "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.war.resources. The first of these lets you customise what files are included in the WAR file from the "web-app" directory. The second lets you do any extra processing you want before the WAR file is finally created.
392
// 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") }
Application servers
Ideally you should be able to simply drop a WAR file created by Grails into any application server and it should work straight away. However, things are rarely ever this simple. The Grails website contains an up-to-date list of application servers that Grails has been tested with, along with any additional steps required to get a Grails WAR file working.
393
18 Contributing to Grails
Grails is an open source project with an active community and we rely heavily on that community to help make Grails better. As such, there are various ways in which people can contribute to Grails. One of these is by writing useful plugins and making them publicly available. In this chapter, we'll look at some of the other options.
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 these alone, so a very 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 haven't been reviewed by 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 be closed, then also check the "Flagged" field and add a short comment explaining why. Once those changes are saved, the issue will disappear from the 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 "Issues" drop down. Just click on the star next to a filter to make it a favourite.
394
This will create a "grails-core" directory in your current working directory containing all the project source files. The next step is to get a Grails installation from the source.
This will fetch all the standard dependencies required by Grails and then build a GRAILS_HOME installation. Note that this target skips 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 directory and add the "bin" directory to your path. When you next type run the grails command, you'll be using the version you just built.
These will take a while (15-30 mins), so consider running individual tests using the command line. For example, to run the test case 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 work....
395
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 build errors. To fix them do the following: Add the springloaded-core JAR $GRAILS_HOME/lib/com.springsource.springloaded/springloaded-core/jars classpath. file in to grails-core's
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 errors in grails-scripts, do "../gradlew cleanEclipse eclipse" in that directory and edit the .classpath file again (remove the line "<classpathentry kind="src" path="../scripts"/>"). Remove possible empty "scripts" directory under grails-scripts if you are not able to add the linked folder. 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 click -> Team -> Share project (not "Share projects"). Choose "Git". Then check "Use or create repository in parent folder of project" and click "Finish". Get the recommended code style settings from the mailing list thread (final style not decided yet, currently profile.xml). Import the code style xml file to STS in Window->Preferences->Java->Code Style->Formatter->Import . Grails code uses spaces instead of tabs for indenting.
and then connect to the JVM remotely via the IDE ("remote debugging") using the port 5005. Of course, if you have modified the grails-debug script to use a different port number, connect using that one. If you need to debug stuff that happens during application startup, then you should modify the "grails-debug" script and change the "suspend" option from 'n' to 'y'. You can read more about the JPDA connection settings TODO here: http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#Invocation.
396
It's also possible to get Eclipse to wait for incoming debugger connections and instead of using "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005" you could use this "-Xrunjdwp:transport=dt_socket,server=n,address=8000" (which assumes the Eclipse default port for remote java applications) Inside eclipse you create a new "Remote Java Application" launch configuration and change the connection type to "Standard (Socket Listen)" and click debug. This allows you to start a debugger session in eclipse and just leave it running and you're free to debug anything without having to keep remembering to relaunch a "Socket Attach" launch configuration. You might find it handy to have 2 scripts, one called "grails-debug", and another called "grails-debug-attach"
This will create a new local branch called "mine" based off the "master" branch. Of course, you can name the branch whatever you like - you don't have to use "mine".
397
Let's say you have the main repository set up as a remote called "upstream" and you want to submit a pull request. Also, all your changes are currently on the local "mine" branch but not on "master". The first step involves pulling any changes from the main 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 master:
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. Think adding some 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:
git checkout master git merge mine
Finally, you must push your changes to your remote repository on GitHub, otherwise the core developers won't be able to pick them up:
git push
You're now ready to send the pull request from the GitHub user interface.
398
./gradlew docs
Be warned: this command can take a while to complete and you should probably increase your Gradle memory settings by giving the 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 specify the location of the 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 generated. If you don't specify a grails.home property, then the build will fetch the Grails source - a download of 10s of megabytes. It must then compile the Grails source which can take a while too. Additionally you can create a local.properties file with this variable set:
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 it once:
./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 containing the user guide part and the ref folder containing the reference material. To view the user guide, simply open build/docs/index.html.
Publishing
The publishing system for the user guide is the same as the one for Grails projects. You write your chapters and sections in the gdoc wiki format which is then converted to HTML for the final guide. Each chapter is a top-level gdoc file in the src/<lang>/guide directory. Sections and sub-sections then go into directories with the same name as the chapter gdoc but without the suffix.
399
The structure of the user guide is defined in the src/<lang>/guide/toc.yml file, which is a YAML file. This file also defines 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 category, which also appears in the docs. Hence the directories need different names for the different languages. Inside the directories go the gdoc files, 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 one, simply create a 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 have replaced, rather 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]:
Because the English text remains in your gdoc files, diff will show differences on the English lines. You can then use the output of diff to see which bits of your translation need updating. On top of that, the {hidden} macro ensures that the text inside it is not displayed in the browser, although you can display it by adding this URL as a bookmark: javascript:toggleHidden(); (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 translating. You run it like so:
./left_to_do.groovy es
This will then print out a recursive diff of the given translation against the reference English user guide. Anything in {hidden} blocks that hasn't changed since being translated will not appear in the diff output. In other words, all you will see is content that hasn't been translated yet and content that has changed since it was translated. Note that {code} blocks are ignored, so you don't need to include them inside {hidden} macros. To provide translations for the headers, such as the user guide title and subtitle, just add language specific entries in the 'resources/doc.properties' file like so:
es.title=El Grails Framework es.subtitle=...
400
For each language translation, properties beginning <lang>. will override the standard ones. In the above example, the user guide title will be El Grails Framework for the Spanish translation. Also, translators can be credited by adding a '<lang>.translators' property:
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 "Translated by" header in the user guide itself. You can build specific translations very easily using the publishGuide_* and publishPdf_* tasks. For example, to build both 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/docs/fr . You can then 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 what the current state is 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
401