The Grails Framework - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
Table of Contents
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
1.1 What's new in Grails 2.0?
This section covers the new features that are present in 2.0 and is broken down into sections covering the build system, core APIs, the web tier, persistence enhancements and improvements in testing. Note there are many more small enhancements and improvements, these sections just cover some of the highlights.1.1.1 Development Environment Features
Interactive Mode and Console Enhancements
Grails 2.0 features brand new console output that is more concise and user friendly to consume. An example of the new output when running tests can be seen below:
In general Grails makes its best effort to display update information on a single line and only present the 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:
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
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.New Test Report and Documentation Templates
There are new templates for displaying test results that are clearer and more user friendly than the previous reports:
In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails application and plugin documentation:
See the section on the documentation engine for more usage info.Use a TOC for Project Docs
The old documentation engine relied on you putting section numbers into the gdoc filenames. Although convenient, this effectively made it difficult to restructure your user guide by inserting new chapters and sections. In addition, any such restructuring or renaming of section titles resulted in breaking changes to the URLs.You can now use logical names for your gdoc files and define the structure and section titles in a YAML table-of-contents file, as described in the section on the documentation engine. The logical names appear in the URLs, so as long as you don't change those, your URLs will always remain the same no matter how much restructuring or changing of titles you do.Grails 2.0 even provides a migrate-docs command to aid you in migrating existing gdoc user guides.Enhanced Error Reporting and Diagnosis
Error reporting and problem diagnosis has been greatly improved with a new errors view that analyses stack traces and recursively displays problem areas in your code:
In addition stack trace filtering has been further enhanced to display only relevant trace information:Line | Method
->> 9 | getValue in Book.groovy
- - - - - - - - - - - - - - - - - - - - - - - - -
| 7 | getBookValue in BookService.groovy
| 886 | runTask . . in ThreadPoolExecutor.java
| 908 | run in ''
^ 662 | run . . . . in Thread.javaH2 Database and Console
Grails 2.0 now uses the H2 database instead of HSQLDB, and enables the H2 database console in development mode (at the URI /dbconsole) so that the in-memory database can be easily queried from the browser:
Plugin Usage Tracking
To enhance community awareness of the most popular plugins an opt-in plugin usage tracking system has been included where users can participate in providing feedback to the plugin community on which plugins are most popular.This will help drive the roadmap and increase support of key plugins while reducing the need to support older or less popular plugins thus helping plugin development teams focus their efforts.Dependency Resolution Improvements
There are numerous improvements to dependency resolution handling via Ivy including:- Grails now makes a best effort to cache the previous resolve and avoid resolving again unless you change
BuildConfig.groovy. - Plugins dependencies now appear in the dependency report generated by
grails dependency-report - Plugins published with the release plugin now publish their transitive plugin dependencies in the generated POM which are later resolved.
- It is now possible to customize the ivy cache directory via
BuildConfig.groovy
grails.project.dependency.resolution = {
cacheDir "target/ivy-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
…
}
…
}- It is now possible to easily disable checksum validation errors:
grails.project.dependency.resolution = {
checksums false // whether to verify checksums or not
}1.1.2 Core Features
Binary Plugins
Grails plugins can now be packaged as JAR files and published to standard maven repositories. This even works for GSP and static resources (with resources plugin 1.0.1). See the section on Binary plugins for more information.Groovy 1.8
Grails 2.0 comes with Groovy 1.8 which includes many new features and enhancementsSpring 3.1 Profile Support
Grails' existing environment support has been bridged into the Spring 3.1 profile support. For example when running with a custom Grails environment called "production", a Spring profile of "production" is activated so that you can use Spring's bean configuration APIs to configure beans for a specific profile.1.1.3 Web Features
Controller Actions as Methods
It is now possible to define controller actions as methods instead of using closures as in previous versions of Grails. In fact this is now the preferred way of expressing an action. For example:// action as a method
def index() {}
// action as a closure
def index = {}Binding Primitive Method Action Arguments
It is now possible to bind form parameters to action arguments where the name of the form element matches the argument name. For example given the following form:<g:form name="myForm" action="save"> <input name="name" /> <input name="age" /> </g:form>
def save(String name, int age) { // remaining }
Static Resource Abstraction
A new static resource abstraction is included that allows declarative handling of JavaScript, CSS and image resources including automatic ordering, compression, caching and gzip handling.Servlet 3.0 Async Features
Grails now supports Servlet 3.0 including the Asynchronous programming model defined by the specification:def index() {
def ctx = startAsync()
ctx.start {
new Book(title:"The Stand").save()
render template:"books", model:[books:Book.list()]
ctx.complete()
}
}Link Generation API
A general purposeLinkGenerator 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 grailsLinkGeneratordef generateLink() {
grailsLinkGenerator.link(controller:"book", action:"list")
}Page Rendering API
Like theLinkGenerator the new PageRenderer can be used to render GSP pages outside the scope of a web request, such as in a scheduled job or web service. The PageRenderer class features a very similar API to the render method found within controllers:grails.gsp.PageRenderer groovyPageRenderervoid welcomeUser(User user) {
def contents = groovyPageRenderer.render(view:"/emails/welcomeLetter", model:[user: user])
sendEmail {
to user.email
body contents
}
}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 = {
// …
}
}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.1.1.4 Persistence Features
The GORM API
The GORM API has been formalized into a set of classes (GormStaticApi, GormInstanceApi and GormValidationApi) that get statically wired into every domain class at the byte code level. The result is better code completion for IDEs, better integration with Java and the potential for more GORM implementations for other types of data stores.New findOrCreate and findOrSave Methods
Domain classes have support for the findOrCreateWhere, findOrSaveWhere, findOrCreateBy and findOrSaveBy query methods which behave just like findWhere and findBy methods except that they should never return null. If a matching instance cannot be found in the database then a new instance is created, populated with values represented in the query parameters and returned. In the case of findOrSaveWhere and findOrSaveBy, the instance is saved before being returned.def book = Book.findOrCreateWhere(author: 'Douglas Adams', title: "The Hitchiker's Guide To The Galaxy")
def book = Book.findOrSaveWhere(author: 'Daniel Suarez', title: 'Daemon')
def book = Book.findOrCreateByAuthorAndTitle('Daniel Suarez', 'Daemon')
def book = Book.findOrSaveByAuthorAndTitle('Daniel Suarez', 'Daemon')Abstract Inheritance
GORM now supports abstract inheritance trees which means you can define queries and associations linking to abstract classes:abstract class Media { String title … } class Book extends Media { } class Album extends Media {} class Account { static hasMany = [purchasedMedia:Media] }..def allMedia = Media.list()
Multiple Data Sources Support
It is now possible to define multiple datasources inDataSource.groovy and declare one or more datasources a particular domain uses by default:class ZipCode { String code static mapping = {
datasource 'ZIP_CODES'
}
}def zipCode = ZipCode.auditing.get(42)
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.Database Reverse Engineering
A new database reverse engineering plugin has been designed and built for Grails 2.0 that allows you to generate a domain model from an existing database schema.Hibernate 3.6
Grails 2.0 is now built on Hibernate 3.6Bag Collections
You can now use Hibernate Bags for mapped collections to avoid the memory and performance issues of loading large collections to enforceSet uniqueness or List order.For more information see the section on Sets, Lists and Maps in the user guide.
1.1.5 Testing Features
New Unit Testing Console Output
Test output from the test-app command has been improved:
New Unit Testing API
There is a new unit testing API based on mixins that supports JUnit 3, 4 and Spock style tests (with Spock 0.6 and above). Example:import grails.test.mixin.TestFor@TestFor(SimpleController) class SimpleControllerTests { void testIndex() { controller.home() assert view == "/simple/homePage" assert model.title == "Hello World" } }
Unit Testing GORM
A new in-memory GORM implementation is present that supports many more features of the GORM API making unit testing of criteria queries, named queries and other previously unsupported methods possible.Faster Unit Testing with Interactive Mode
The new interactive mode (activated by typing 'grails') greatly improves the execution time of running unit and integration tests.Unit Test Scaffolding
A unit test is now generated for scaffolded controllers2 Getting Started
2.1 Downloading and Installing
The first step to getting up and running with Grails is to install the distribution. To do so follow these steps:- Download a binary distribution of Grails and extract the resulting zip file to a location of your choice
- Set the GRAILS_HOME environment variable to the location where you extracted the zip
- On Unix/Linux based systems this is typically a matter of adding something like the following
export GRAILS_HOME=/path/to/grailsto your profile - On Windows this is typically a matter of setting an environment variable under
My Computer/Advanced/Environment Variables - Then add the
bindirectory to yourPATHvariable: - On Unix/Linux based systems this can be done by adding
export PATH="$PATH:$GRAILS_HOME/bin"to your profile - On Windows this is done by modifying the
Pathenvironment variable underMy Computer/Advanced/Environment Variables
grails -version in the terminal window and see output similar to this:
Grails version: 2.0.0
2.2 Upgrading from previous versions of Grails
Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, 1.2.x, or 1.3.x applications to Grails 2.0. The major changes are described in detail below.Upgrading from Grails 1.3.x
HSQLDB Has Been Replaced With H2
HSQLDB is still bundled with Grails but is not configured as a default runtime dependency. Upgrade options include replacing HSQLDB references in DataSource.groovy with H2 references or adding HSQLDB as a runtime dependency for the application.If you want to run an application with different versions of Grails, it's simplest to add HSQLDB as a runtime dependency, which you can do in BuildConfig.groovy:grails.project.dependency.resolution = {
inherits("global") {
}
repositories {
grailsPlugins()
grailsHome()
grailsCentral()
} dependencies {
// Add HSQLDB as a runtime dependency
runtime 'hsqldb:hsqldb:1.8.0.10'
}
}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"
}
}
}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
}
}data column set to BINARY(2097152) by Hibernate.Abstract Inheritance Changes
In previous versions of Grails abstract classes ingrails-app/domain were not treated as persistent. This is no longer the case and has a significant impact on upgrading your application. For example consider the following domain model in a Grails 1.3.x application:abstract class Sellable {} class Book extends Sellable {}
Sellable class would be stored within the BOOK table. However, in Grails 2.0.x you will get 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:
- Move the abstract
Sellableclass into the src/groovy package. If theSellableclass is in thesrc/groovydirectory it will no longer be regarded a persistent - 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)
Criteria Queries Default to INNER JOIN
The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.Logging By Convention Changes
The packages that you should use for Grails artifacts have mostly changed. In particular:service->servicescontroller->controllerstagLib->taglib(case change)bootstrap->confdataSource->conf
log property into artefacts at compile time.jQuery Replaces Prototype
The Protoype Javascript library has been removed from Grails core and now new Grails applications have the jQuery plugin configured by default. This will only impact you if you are using Prototype with the adaptive AJAX tags in your application, e.g. <g:remoteLink/> etc, because those tags will break as soon as you upgrade.To resolve this issue, simply install the Prototype plugin in your application. You can also remove the prototype files from yourweb-app/js/prototype directory if you want.Access Control and Resources
The Resources plugin is a great new feature of Grails, but you do need to be aware that it adds an extra URL at/static. If you have access control in your application, this may mean that the static resources require an authenticated user to load them! Make sure your access rules take account of the /static URL.Controller Public Methods
As of Grails 2.0, public methods of controllers are now treated as actions in addition to actions defined as traditional Closures. If you were relying on the use of methods for privacy controls or as helper methods then this could result in unexpected behavior. To resolve this issue you should mark all methods of your application that are not to be exposed as actions asprivate methods.The redirect Method
The redirect method no longer commits the response. The result of this is code that relies of this behavior will break in 2.0. For example:redirect action: "next" if (response.committed) { // do something }
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 }
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.Content Negotiation
As of Grails 2.0 the withFormat method of controllers no longer takes into account the request content type (dictated by theCONTENT_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
}
}
}withFormat method provided on the request object:def processBook() {
request.withFormat {
xml {
// read request XML
}
html {
// read request parameters
}
}
}Command Line Output
Ant output is now hidden by default to keep the noise in the terminal to a minimum. That means if you useant.echo in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.For status related messages, you can use the event system:event "StatusUpdate", ["Some message"] event "StatusFinal", ["Some message"] event "StatusError", ["Some message"]
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().Updated Underlying APIs
Grails 2.0 contains updated dependencies including Servlet 3.0, Tomcat 7, Spring 3.1, Hibernate 3.6 and Groovy 1.8. This means that certain plugins and applications that that depend on earlier versions of these APIs may no longer work. For example the Servlet 3.0HttpServletRequest interface includes new methods, so if a plugin implements this interface for Servlet 2.5 but not for Servlet 3.0 then said plugin will break. The same can be said of any Spring interface.Removal of release-plugin
The built inrelease-plugin command for releases plugins to the central Grails plugin repository has been removed. The new release plugin should be used instead which provides an equivalent publish-plugin command.Removal of Deprecated Classes
The following deprecated classes have been removed:grails.web.JsonBuilder, grails.web.OpenRicoBuilderUpgrading from Grails 1.2.x
Plugin Repositories
As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. The plugin resolution mechanism in Grails 1.2 and below has been replaced by one built on Ivy, the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.Ivy supports a much richer setter of repository resolvers for resolving plugins, including support for Webdav, HTTP, SSH and FTP. See the section on resolvers in the Ivy docs for all the available options and the section of plugin repositories in the user guide which explains how to configure additional resolvers.If you still need support for resolving plugins against secured SVN repositories then the IvySvn project provides a set of resolvers for SVN repositories.Upgrading from Grails 1.1.x
Plugin paths
In Grails 1.1.x typically apluginContextPath variable was used to establish paths to plugin resources. For example:<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />
<g:resource dir="images" file="foo.jpg" />
<g:resource contextPath="" dir="images" file="foo.jpg" />
Tag and Body return values
Tags no longer returnjava.lang.String instances but instead return a Grails StreamCharBuffer instance. The StreamCharBuffer class implements all the same methods as String but doesn't extend String, so code like this will break:def foo = body() if (foo instanceof String) { // do something }
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 ofJSONBuilder 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=trueValidation 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 aStackOverflowError. For example:static constraints = { author validator: { a -> assert a != Book.findByTitle("My Book").author } }
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 } } }
Upgrading from Grails 1.0.x
Groovy 1.6
Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that was compiled with Groovy 1.5 you must recompile it against Groovy 1.6 or higher before using it with Grails 1.1.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 settinggrails.testing.reports.destDir has been renamed to grails.project.test.reports.dir for consistency.2) The following settings have been moved from grails-app/conf/Config.groovy to grails-app/conf/BuildConfig.groovy:
grails.config.base.webXmlgrails.project.war.file(renamed fromgrails.war.destFile)grails.war.dependenciesgrails.war.copyToWebAppgrails.war.resources
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=truePlugin Changes
As of version 1.1, Grails no longer stores plugins inside yourPROJECT_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")
grailsScript method to import a named script:includeTargets << grailsScript("_GrailsBootstrap")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")basedir property:new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream -> // read the file }
Command Line Changes
Therun-app-https and run-war-https commands no longer exist and have been replaced by an argument to run-app:grails run-app -https
Data Mapping Changes
1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:static mapping = { someEnum enumType:"ordinal" }
REST Support
Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using theparseRequest argument inside a URL mapping:"/book"(controller:"book",parseRequest:true)
resource argument, which enables parsing by default:"/book"(resource:"book")
2.3 Creating an Application
To create a Grails application you first need to familiarize yourself with the usage of thegrails command which is used in the following manner:grails [command name]
grails create-app helloworldThis will create a new directory inside the current one that contains the project. Navigate to this directory in your console:bc.
cd helloworld
2.4 A Hello World Example
To implement the typical "hello world!" example run the create-controller command:
grails create-controller helloThis will create a new controller (Refer to the section on Controllers for more information) in the grails-app/controllers directory called helloworld/HelloController.groovy.
If no package is specified with create-controller script, Grails automatically uses the application name as the package name. This default is configurable with the grails.project.groupId attribute in Config.groovy.
Controllers are capable of dealing with web requests and to fulfil the "hello world!" use case our implementation needs to look like the following:package helloworldclass HelloController { def world() { render "Hello World!" } }
grails run-appThis will start-up a server on port 8080 and you should now be able to access your application with the URL: http://localhost:8080/helloworldThe result will look something like the following screenshot:
This is the Grails intro page which is rendered by the web-app/index.gsp file. You will note it has a detected the presence of your controller and clicking on the link to our controller we can see the text "Hello World!" printed to the browser window.
2.5 Using Interactive Mode
Grails 2.0 features an interactive mode which makes command execution faster since the JVM doesn't have to be restarted for each command. To use interactive mode simple type 'grails' from the root of any projects and use TAB completion to get a list of available commands. See the screenshot below for an example:
For more information on the capabilities of interactive mode refer to the section on Interactive Mode in the user guide.
2.6 Getting Set Up in an IDE
IntelliJ IDEA
IntelliJ IDEA and the JetGroovy plugin offer good support for Groovy and Grails developers. Refer to the section on Groovy and Grails support on the JetBrains website for a feature overview.To integrate Grails with IntelliJ run the following command to generate appropriate project files:grails integrate-with --intellij
Eclipse
We recommend that users of Eclipse looking to develop Grails application take a look at SpringSource Tool Suite, 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
mate .
2.7 Convention over Configuration
Grails uses "convention over configuration" to configure itself. This typically means that the name and location of files is used instead of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails.Here is a breakdown and links to the relevant sections:grails-app- top level directory for Groovy sourcesconf- 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 sourcesgroovy- Other Groovy sourcesjava- Other Java sourcestest- Unit and integration tests.
2.8 Running an Application
Grails applications can be run with the built in Tomcat server using the run-app command which will load a server on port 8080 by default:grails run-app
server.port argument:grails -Dserver.port=8090 run-app
2.9 Testing an Application
Thecreate-* commands in Grails automatically create unit or integration tests for you within the test/unit or test/integration directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on Testing.To execute tests you run the test-app command as follows:grails test-app
2.10 Deploying an Application
Grails applications are deployed as Web Application Archives (WAR files), and Grails includes the war command for performing this task:grails war
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 implicationsWhen 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
2.11 Supported Java EE Containers
Grails runs on any container that supports Servlet 2.5 and above and is known to work on the following specific container products:- 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
2.12 Generating an Application
To get started quickly with Grails it is often useful to use a feature called Scaffolding to generate the skeleton of an application. To do this use one of thegenerate-* commands such as generate-all, which will generate a controller (and its unit test) and the associated views:grails generate-all Book
2.13 Creating Artefacts
Grails ships with a few convenience targets such as create-controller, create-domain-class and so on that will create Controllers and different artefact types for you.These are just for your convenience and you can just as easily use an IDE or your favourite text editor.For example to create the basis of an application you typically need a domain model:
grails create-domain-class book
grails-app/domain/Book.groovy such as:class Book {
}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.
3 Configuración
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.
Puede parecer extraño que en un framework que enfatiza la "Convención sobre configuración" abordemos este tema, pero como la configuración es normalmente algo que se modifica excepcionalmente, es mejor quitárselo de encima.Con la configuración predeterminada de Grails realmente puede desarrollar una aplicación sin hacer ninguna configuración alguna. Grails cuenta con un contenedor de servlet incrustado y una base de datos en memoria H2 de, por lo que no hay siquiera una base de datos que configurar.Sin embargo, normalmente deberÃa configurar una base de datos más robusto en algún momento, como se describe en la sección siguiente.
3.1 Configuración básica
For general configuration Grails provides a file called 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:
La configuración general Grails proporciona un archivo llamado grails-app/conf/Config.groovy. This file uses Groovy's ConfigSlurper which is very similar to Java properties files except it is pure Groovy hence you can reuse variables and use proper Java types!You can add your own configuration in here, for example:foo.bar.hello = "world"grails-app/conf/Config.groovy. Este archivo utiliza el ConfigSlurper de Groovy que es muy similar a los archivos de propiedades de Java excepto porque es puro Groovy, asà que puede reutilizar las variables y utilizar tipos propios de Java.Puede añadir su propia configuración aquÃ, por ejemplo:foo.bar.hello = "world"assert "world" == grailsApplication.config.foo.bar.hello
The other way involves getting a reference to the ConfigurationHolder class that holds a reference to the configuration object:
La otra forma consiste en obtener una referencia a la clase ConfigurationHolder que contiene una referencia al objeto de configuración: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 theGrailsApplicationand config from thegrailsApplicationvariable.
ConfigurationHolder y ApplicationHolder están deprecadas y se eliminarán en una versión futura de Grails, asà que es preferible acceder al objetoGrailsApplicationy a la configuración desde la variablegrailsApplication.
3.1.1 Opciones disponibles
Grails also provides the following configuration options:
Grails también proporciona las siguientes opciones de configuración:
grails.config.locations- The location of properties files or addition Grails Config files that should be merged with main configurationgrails.enable.native2ascii- Set this to false if you do not require native2ascii conversion of Grails i18n properties filesgrails.views.default.codec- Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.grails.views.gsp.encoding- The file encoding used for GSP source files (default is 'utf-8')grails.mime.file.extensions- Whether to use the file extension to dictate the mime type in Content Negotiationgrails.mime.types- A map of supported mime types used for Content Negotiationgrails.serverURL- A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See createLink.
grails.config.locations- la ubicación de archivos de propiedades o archivos de configuración de Grails que deben combinarse con la configuración principal.grails.enable.native2ascii- se establece en false si no necesita convertir archivos de propiedades de i18n de Grails a native2ascii.grails.views.default.codec- establece la de codificación predeterminada para GSPs, puede ser 'none', 'html' o 'base64' (por defecto: 'none'). Para reducir el riesgo de ataques XSS, definir 'html'.grails.views.gsp.encoding- establece la codificación de archivos para los archivos GSP (el valor por defecto es 'utf-8').grails.mime.file.extensions- si se utiliza la extensión de archivo para dictar el tipo mime tipo en contenido Negotiationgrails.mime.types- un mapa de tipos mime admitidos utilizados al negociar contenidosgrails.serverURL- una cadena que especifica la parte URL del servidor de enlaces absolutos, incluyendo el nombre del servidor, por ejemplo, grails.serverURL="http://my.yourportal.com". Consulte createLink.
War generation
grails.project.war.file- Sets the name and location of the WAR file generated by the war commandgrails.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
Generación de wars
grails.project.war.file- establece el nombre y la ubicación del archivo war generado por el comando war.grails.war.dependencies- una closure que contiene la sintaxis del constructor de Ant o una lista de nombres de archivo JAR. Le permite personalizar qué librerÃas se incluyen en el archivo war.grails.war.copyToWebApp- una closure que contiene la sintaxis del constructor de Ant que es legal dentro de un copy de Ant, por ejemplo "fileset()". Le permite controlar qué se incluye en el archivo war desde el directorio "web-app".grails.war.resources- una closure que contiene la sintaxis del constructor de Ant. Permite a la aplicación hacer otros trabajos antes de construir el archivo war final.
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 alog4j setting to the file grails-app/conf/Config.groovy.So what does this log4j setting look like? Here's a basic example:Los conceptos básicos
Grails utiliza su mecanismo de configuración para proporcionar la configuración base para el sistema de logs Log4j por lo que todo lo que tiene que hacer es agregar la configuración paralog4j al archivo grails-app/conf/Config.groovyAsà que ¿cómo es la configuración para este log4j? Aquà tiene un ejemplo básico:log4j = {
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages' // GSP warn '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.
Esto dice que para los loggers cuyo nombre comienza con 'org.codehaus.groovy.grails.web.servlet' o 'org.codehaus.groovy.grails.web.pages', sólo se registran mensajes a nivel de 'error' y superiores. Los loggers con nombres que empiezan con 'org.apache.catalina' sólo resgistran mensajes de nivel 'warn' y superiores. ¿Qué significa eso? En primer lugar, hay que entender cómo funcionan los niveles.Logging levels
The are several standard logging levels, which are listed here in order of descending priority:- off
- fatal
- error
- warn
- info
- debug
- trace
- all
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:Niveles de registro
Existen varios niveles de registro estándar, que se listan en orden descendente de prioridad:- off
- fatal
- error
- warn
- info
- debug
- trace
- all
log.error(msg) registrará un mensaje en el nivel de "error". Asimismo, log.debug(msg) se registrará en 'debug'. Cada uno de los niveles anteriores aparte de 'off' y 'all' tienen un método de registro correspondiente con el mismo nombre.El sistema de registro utiliza el nivel del mensaje combinado con la configuración para el logger (consulte la siguiente sección) para determinar si se escribe el mensaje. Por ejemplo, si tienes un logger de 'org.example.domain' configurado asÃ:warn 'org.example.domain'
then messages with a level of 'warn', 'error', or 'fatal' will be written out. Messages at other levels will be ignored.Before we go on to loggers, a quick note about those 'off' and 'all' levels. These are special in that they can 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.
luego se escribirán los mensajes con un nivel de 'warn', 'error' o 'fatal'. Se omitirán los mensajes a otros niveles.Antes de continuar con los loggers, una nota rápida sobre los nivels 'off' y 'all'. Estos son especiales ya que sólo pueden utilizarse en la configuración; no se puede registrar los mensajes en estos niveles. Asà que si configura un registrador con un nivel de 'off', ningún mensaje se escribirá. Un nivel de 'all' significa que se verán todos los mensajes. 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 calllog.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:
- use the
loginstance injected into artifacts such as domain classes, controllers and services; - use the Commons Logging API directly.
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:
Loggers
Los loggers son fundamentales para el sistema de log, pero son una fuente de confusión. Para empezar, ¿qué son? ¿son compartidos? ¿cómo configurarlos?Un logger es el objeto en el que registras mensajes, por lo que en la llamadalog.debug(msg), log es una instancia de logger (del tipo Log). Estos loggers se almacenan en caché y se identifica por su nombre, por lo que si dos clases distintas utilizan dos loggers con el mismo nombre, los loggers son realmente la misma instancia.Hay dos formas principales de apoderarse de un registrador:
- Usar la instancia de
logque se inyecta en los artefactos, como las clases de dominio, los controladores y servicios; - Utilizar la API de Commons Logging directamente.
log, entonces el nombre del log es "grails.app.<tipo>. <nombreClase> ', Donde tipo es el tipo de artefacto, por ejemplo 'controlador' o 'servicio" y nombreClase es el nombre completo del artefacto. Por ejemplo, si usted tiene este servicio:package org.exampleclass 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:
el nombre del logger será 'grails.app.services.org.example.MyService'.Para otras clases, el enfoque tÃpico es almacenar un logger basado en el nombre de clase en un campo estático constante:package org.otherimport org.apache.commons.logging.LogFactoryclass 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
Esto creará un logger con el nombre 'org.other.MyClass' - nota la falta de un prefijo 'grails.app.' ya que la clase no es un artefacto. También se puede pasar un nombre al método 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:getLog(), como "myLogger", pero esto es menos común porque el sistema de registro trata los nombres con puntos ('. ') de una manera especial.Configuración de los loggers
Ya has visto cómo configurar los loggers en Grails:log4j = {
error 'org.codehaus.groovy.grails.web.servlet'
}This example configures loggers with names starting with 'org.codehaus.groovy.grails.web.servlet' to ignore any 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
Este ejemplo configura los loggers con nombres que empiecen por 'org.codehaus.groovy.grails.web.servlet' para ignorar cualquier mensaje enviado a ellos a un nivel de 'warn' o inferior. ¿Pero hay un logger con este nombre en la aplicación? No. Asà que ¿por qué tiene una configuración para ello? Debido a la regla anterior aplica a cualquier logger cuyo nombre empiece con 'org.codehaus.groovy.grails.servlet.' asÃ, por ejemplo, la regla se aplica a la clase 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:org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet y a org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest.En otras palabras, los loggers son jerárquicos. Esto hace que configurarlos por paquete mucho más simple de lo que serÃa de otra manera.Las cosas más comunes que desea capturar el registro de salida son los controladores, servicios y otros artefactos. Utilice la convención mencionada anteriormente para ello: grails.app.<tipoArtefacto>.<nombreClase> . En particular el nombre de clase debe ser plenamente cualificado, es decir, con el paquete si hay uno: log4j = {
// Establece el nivel de todos los artefactos de aplicación
info "grails.app" // Establece el nivel para un controlador especÃfico en un paquete predeterminado
debug "grails.app.controllers.YourController" // Establece el nivel para una clase de dominio especÃfico
debug "grails.app.domain.org.example.Book" // Establecer el nivel para todos taglibs
info "grails.app.taglib"
}The standard artifact names used in the logging configuration are:
Los nombres de artefacto estándar utilizados en la configuración de log son:
conf- For anything undergrails-app/confsuch asBootStrap.groovyand filterstaglib- For tag librariesservices- For service classescontrollers- For controllersdomain- For domain entities
conf- para cualquier cosa bajograils-app/confcomo elBootStrap.groovyy filtros.taglib- para las bibliotecas de etiquetas.servicios- para las clases de servicio.controllers- Para los controladores.domain- para entidades de dominio
org.codehaus.groovy.grails.commons- Core artifact information such as class loading etc.org.codehaus.groovy.grails.web- Grails web request processingorg.codehaus.groovy.grails.web.mapping- URL mapping debuggingorg.codehaus.groovy.grails.plugins- Log plugin activitygrails.spring- See what Spring beans Grails and plugins are definingorg.springframework- See what Spring is doingorg.hibernate- See what Hibernate is doing
org.codehaus.groovy.grails.commons- información del núcleo como carga de clases etc..org.codehaus.groovy.grails.web- Procesamiento de solicitudes web de Grails.org.codehaus.groovy.grails.web.mapping- Depuración de mapeo de URLs.org.codehaus.groovy.grails.plugins- registro de actividad de plugins.grails.spring- ver qué hace beans de Spring y plugins Grails estan definidos.org.springframework- ver qué hace Spring.org.hibernate- ver lo que está haciendo ibernate.
The Root Logger
All logger objects inherit their configuration from the root logger, so if no explicit configuration is provided for a given logger, then any messages that go to that logger are subject to the rules defined for the root logger. In other words, the root logger provides the default configuration for the logging system.Grails automatically configures the root logger to only handle messages at 'error' level and above, and all the messages are directed to the console (stdout for those with a C background). You can customise this behaviour by specifying a 'root' section in your logging configuration like so:El registrador raÃz
Todos los registradores heredarán su configuración del logger raÃz, por lo que si no se proporciona ninguna configuración explÃcita para un logger determinado y asà todos los mensajes que llegan a ese registrador están sujetos a las reglas definidas para el logger raÃz. En otras palabras, el logger raÃz proporciona la configuración predeterminada para el sistema de log.Grails configura automáticamente el logger raÃz para sólo gestionar los mensajes "error" y superiores, y todos los mensajes se dirigen a la consola (stdout para aquellos con un pasado con C). Puede personalizar este comportamiento especificando una sección de 'root' en la configuración del log de este modo:log4j = {
root {
info()
}
…
}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):
En el ejemplo anterior se configura el logger raÃz para registrar mensajes a nivel de 'info' y por encima en el appender de consola predeterminada. También puede configurar el logger raÃz para registrar a uno o más appenders con nombre (sobre lo que ya hablaremos más en breve):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
En el ejemplo anterior, el registrador raÃz registrará a dos appenders, el appender predeterminada 'debug' (consola) y un appender personalizado 'file'.Para usuarios avanzados existe una sintaxis alternativa para configurar el logger raÃz: la instancia de logger raiz org.apache.log4j.Logger instance is passed as an argument to the log4j closure. This lets you work with the logger directly:org.apache.log4j.Logger se pasa como un argumento a la closure de log4j. Esto le permite trabajar directamente con el logger:log4j = { root ->
root.level = org.apache.log4j.Level.DEBUG
…
}For more information on what you can do with this
Para obtener más información sobre lo que puede hacer con esta instancia de 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:Logger, consulte la documentación de la API de Log4j.Esos son los elementos básicos de registro bastante bien cubiertos y son suficientes si sólo quieres enviar mensajes de log a la consola. Pero ¿qué sucede si desea registrar en un archivo? ¿Cómo asegurarnos de que los mensajes de un logger particular vayan a un archivo, pero no a la consola? Se responderá estas preguntas y más revisando los appenders.Appenders
Los loggers son un mecanismo útil para el filtrado de mensajes, pero fÃsicamente no escriben los mensajes en ningún sitio. Esto es trabajo del appender, de los cuales hay varios tipos. Por ejemplo, el appender por defecto escribe los mensajes de la consola, existe otro que escribe en un archivo y algunos otros. ¡Incluso puede crear su propia implementación!Este diagrama muestra cómo encajan en el flujo de registro:
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:
Como puede ver, un logger puede tener varios appenders conectados a él. En una configuración estándar de Grails, el appender de consola denominada 'debug' está unido a todos los logger mediante la configuración predeterminada del logger raÃz. Pero es el único. Agregar más appenders puede hacerse dentro de un bloque de 'appenders':log4j = {
appenders {
rollingFile name: "myAppender",
maxFileSize: 1024,
file: "/tmp/logs/myApp.log"
}
}The following appenders are available by default:
Las siguientes appenders están disponibles de forma predeterminada:| Name | Class | Description |
|---|---|---|
| jdbc | JDBCAppender | Logs to a JDBC connection. |
| console | ConsoleAppender | Logs to the console. |
| file | FileAppender | Logs to a single file. |
| rollingFile | RollingFileAppender | Logs to rolling files, for example a new file each day. |
| Nombre | Clase | Descripción |
|---|---|---|
| jdbc | JDBCAppender | Registra a una conexión JDBC. |
| consola | ConsoleAppender | Registra en la consola. |
| file | FileAppender | Registra a un archivo. |
| rollingFile | RollingFileAppender | Registra a varios archivos, por ejemplo un archivo nuevo cada dÃa. |
Each named argument passed to an appender maps to a property of the underlying Appender implementation. So the previous example sets the
Cada argumento con nombre pasado a un appender se asigna a una propiedad de la implementación subyacente del Appender. Asà que el ejemplo anterior establece las propiedades 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:
nombre, maxFileSize y file de la instancia de RollingFileAppender.Puede tener tantos appenders como quiera, solo asegúrese que todos tienen nombres únicos. Incluso puede tener varias instancias del mismo tipo appender, por ejemplo de varios appenders file que registran en archivos diferentes.Si prefiere crear el appender mediante programación o si desea utilizar una implementación de appender que no está disponible en la sintaxis anterior, simplemente declarar una entrada appender con la instancia del appender que desee: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 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:
Este enfoque puede utilizarse para configurar 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"JMSAppender, SocketAppender, SMTPAppender y muchos más.Una vez que ha declarado sus appenders adicionales, puede conectarlos a loggers especÃficos pasando el nombre como clave a uno de los métodos de registro de niveles de la sección anterior:error myAppender: "grails.app.controllers.BookController"error myAppender: "grails.app.controllers.BookController", myFileAppender: ["grails.app.controllers.BookController", "grails.app.services.BookService"], rollingFile: "grails.app.controllers.BookController"
The above example also shows how you can configure more than one logger at a time for a given appender (
El ejemplo anterior muestra cómo puede configurar más de un logger para un determinado appender (myFileAppender) by using a list.
myFileAppender) usando una lista.
Be aware that you can only configure a single level for a logger, so if you tried this code: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.
Tenga en cuenta que sólo se puede configurar un único nivel de un logger, asà que si has probado este código:error myAppender: "grails.app.controllers.BookController" debug myFileAppender: "grails.app.controllers.BookController" fatal rollingFile: "grails.app.controllers.BookController"
error myAppender: "grails.app.controllers.BookController" debug myFileAppender: "grails.app.controllers.BookController" fatal rollingFile: "grails.app.controllers.BookController"
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:
Un appender que está conectada a un logger configurado con el nivel 'all' va a generar una gran cantidad de información de registro. Esto puede estar bien en un archivo, pero hace difÃcil trabajar en la consola. Asà que configuramos el appender consola sólo para escribir mensajes a nivel de 'info' o superior:log4j = {
appenders {
console name: "stdout", threshold: org.apache.log4j.Level.INFO
}
}The key here is the
La clave aquà es el argumento 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 filehtml- Creates an HTML log filesimple- A simple textual logpattern- A Pattern layout
threshold que determina el lÃmite de mensajes de log. Este argumento está disponible para todos los appenders, pero tenga en cuenta que actualmente tiene que especificar una instancia Level, una cadena como "info" no funcionará.Esquemas personalizados
De forma predeterminada el DSL asume que desea utilizar PatternLayout. Sin embargo, hay otros esquemas disponibles incluyendo:xml- crear un archivo de log XMLhtml- crea un archivo de log HTMLsimple- un simple log textualpatrón- diseño de un esquema
You can specify custom patterns to an appender using the
Puede especificar esquemas personalizados para un appender mediante el parámetro layout setting:layout: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:
Esto también funciona para el appender incorporado "debug", que inicia una sesión en la consola:
log4j = {
appenders {
console name: "stdout",
layout: pattern(conversionPattern: "%c{2} %m%n")
}
}Environment-specific configuration
Since the logging configuration is insideConfig.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:Configuración especÃfica para el entorno
Desde que la configuración de registro está dentro deConfig.groovy, puede colocarlo dentro de un bloque especÃfico de entorno. Sin embargo, hay un problema con este enfoque: tiene que proporcionar la configuración de registro completa cada vez que se defina la configuración log4j. En otras palabras, no se puede anular de manera selectiva elementos de la configuración, es todo o nada.Para evitar esto, el DSL de log proporciona sus propios bloques de entorno que puede colocar en cualquier parte de la configuración: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.controller"
}
}
}The one place you can't put an environment block is inside the
El lugar no se puede poner un bloque de entorno es dento la definición 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.When this happens, the full trace is always logged to theStackTrace 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:root, pero puede poner la definición root dentro de un bloque de entorno.Stacktraces completa
Cuando se producen excepciones, puede haber mucho ruido en el stacktrace de Java y Groovy. Grails filtra estos detalles tÃpicamente irrelevantes y restringe la traza a paquetes de clase Groovy/Grails complementarios.Cuando esto sucede, la traza completa siempre se registra para el loggerStackTrace, que, por defecto, escribe su salida a un archivo denominado stacktrace.log. Como con otros loggers, puede cambiar su comportamiento en la configuración. Por ejemplo, si prefiere que estas trazasvayan a la consola, puede agregar esta entrada: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:
Esto no impedirá que Grails intente crear el archivo stacktrace.log, simplemente redirige donde se escriben trazas. Un método alternativo es cambiar la ubicación del archivo del appender 'stacktrace':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:
o, si no desea el appender 'stacktrace', puede configurarlo como un appender 'null':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
Por supuesto puede combinarlo con anexar el appender 'stdout' al logger 'StackTrace' si desea toda la salida de la consola.Por último, puede deshabilitar completamente el filtrado stacktrace estableciendo la propiedad VM grails.full.stacktrace VM property to true:grails -Dgrails.full.stacktrace=true run-appgrails.full.stacktrace a true:grails -Dgrails.full.stacktrace=true run-appMasking Request Parameters From Stacktrace Logs
When Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request. To mask out the values of secure request parameters, specify the parameter names in thegrails.exceptionresolver.params.exclude config property:grails.exceptionresolver.params.exclude = ['password', 'creditCard']
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.grails.exceptionresolver.logRequestParameters=falseEnmascaramiento de parámetros de request de registros Stacktrace
Cuando Grails registra una stacktrace, el mensaje de log puede incluir los nombres y valores de todos los parámetros de la petición de la request actual. Para ocultar los valores de parámetros de request segura, especifique los nombres de parámetro en la propiedad de configuracióngrails.exceptionresolver.params.exclude:grails.exceptionresolver.params.exclude = ['password', 'creditCard']
grails.exceptionresolver.logRequestParameters a false. El valor predeterminado es true cuando la aplicación se ejecuta en modo de desarrollo y false para todos los demás modos.Grails.exceptionresolver.logRequestParameters=falseLogger 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:Herencia de logger
Anteriormente, se mencionó que todos los registradores heredarán del logger raÃz y que los registradores son jerárquicos basados en el separador '.'. Esto significa que a menos que reemplace a un padre, un logger mantiene el nivel y las appenders configurados para ese padre. Por lo tanto con esta configuración: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:
todos los loggers en la aplicación tendrán un nivel de 'debug' y registrarán a los appenders 'stdout' y 'file'. ¿Y si sólo desea registrar a 'stdout' para un registrador particular? Cambie el 'additivity' para un logger en ese caso.'Additivity' simplemente determina si un registrador hereda la configuración de su padre. Si 'additivity' es falso, entonces es no heredado. El valor predeterminado para todos los registradores es cierto, es decir, heredan la configuración. Entonces, ¿cómo se cambia esta configuración? Aquà está un ejemplo: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:
Asà que cuando se especifica un nivel de registro, agregue un argumento 'additivity'. Tenga en cuenta que cuando se especifica la 'additivity', debe configurar los loggers para un appender con nombre. La siguiente sintaxis no funcionará:info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]
Customizing stack trace printing and filtering
info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]
Personalización de impresión y filtro de stacktraces
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 In addition, Grails customizes the display of the filtered stacktrace to make the information more readable. To customize this, implement the
Las tacktraces en general y aquellas generadas al usar Groovy en particular son bastante detallados y contienen muchos lÃneas que no son interesantes al diagnosticar problemas. Asà Grails utiliza una implementación de la interfaz 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'org.codehaus.groovy.grails.exceptions.StackTracePrinter interface in a class in src/groovy or src/java and register it in Config.groovy:org.codehaus.groovy.grails.exceptions.StackTraceFilterer para filtrar las lÃneas irrelevantes. Para personalizar el enfoque utilizado para filtrar, puede implementar esta interfaz en una clase en src/groovy o src/java y registrarlo en Config.groovy:grails.logging.stackTraceFiltererClass =
'com.yourcompany.yourapp.MyStackTraceFilterer'org.codehaus.groovy.grails.exceptions.StackTracePrinter en una clase en src/groovy o src/java y registrarlo en 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
Por último, para procesar información de error en error del SGP, es necesaria una implementación de impresora generadora de HTML. La implementación predeterminada es 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:org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter y está registrada como un bean de Spring. Para utilizar su propia implementación, puede implementar org.codehaus.groovy.grails.exceptions.StackTraceFilterer directamente o hacer una subclase de ErrorsViewStackTracePrinter y regÃstrarla en grails-app/conf/spring/resources.groovy asÃ:import com.yourcompany.yourapp.MyErrorsViewStackTracePrinterbeans = { errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter,
ref('grailsResourceLocator'))
}3.1.3 GORM
Grails provides the following GORM configuration options:
and to enable failOnError for domain classes by package:
Grails ofrece las siguientes opciones de configuración de GORM:
grails.gorm.failOnError- If set totrue, causes thesave()method on domain classes to throw agrails.validation.ValidationExceptionif 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.
grails.gorm.failOnError=truegrails.gorm.failOnError- si establece entruecausas save()método en las clases de dominio a tirar ungrails.validation.ValidationExceptionvalidation falle durante un save. Esta opción puede asignarse también una lista de cadenas que representan los nombres de los paquetes. Si el valor es una lista de cadenas, a continuación, el comportamiento failOnError sólo se aplicará a las clases de dominio de los paquetes (incluyendo sub-paquetes). Consulte a la documentación de método save para obtener más información.
Grails.Gorm.failOnError=truegrails.gorm.failOnError = ['com.companyname.somepackage',
'com.companyname.someotherpackage']Grails.Gorm.failOnError = ['com.companyname.somepackage',
'com.companyname.someotherpackage']grails.gorm.autoFlush= si se establece en truecausas merge, save y delete métodos para realizar el vaciado de la sesión, reemplazando a la necesidad de vaciar explÃcitamente utilizandosave(flush: true).
3.2 Entornos
Per Environment Configuration
Grails supports the concept of per environment configuration. TheConfig.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:Configuración por entornos
Grails es compatible con el concepto de configuración por entornos. Los archivosConfig.groovy, DataSource.groovy y BootStrap.groovy en el directorio grails-app/conf pueden utilizar configuración por entorno por medio con la sintaxis proporcionada por ConfigSlurper. Como ejemplo, considere la siguiente definición por defecto del DataSource proporcionada por Grails:dataSource {
pooled = false
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
environments {
development {
dataSource {
dbCreate = "create-drop"
url = "jdbc:h2:mem:devDb"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb"
}
}
}Notice how the common configuration is provided at the top level and then an
Observe cómo la configuración común se proporciona en el nivel superior y, a continuación, especifica un bloque environments block specifies per environment settings for the dbCreate and url properties of the DataSource.Packaging and Running for Different Environments
Grails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:grails [environment] [command name]
environments especificando valores por entorno para dbCreate y la propiedad url para el DataSource.Empaquetado y ejecución para distintos entornos
La lÃnea de comando de Grails tiene capacidad para ejecutar cualquier comando dentro del contexto de un entorno especÃfico. El formato es:Grails [entorno] [nombre de comando]
In addition, there are 3 preset environments known to Grails: To target other environments you can pass a
Además, hay 3 entornos preestablecidos para 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
grails.env variable to any command:grails -Dgrails.env=UAT run-app
dev, prod, y test, para development, production y test. Por ejemplo, para crear un WAR para el entorno de test puede ejecutar:grails test war
grails.env para cualquier comando:Grails-Dgrails.env=UAT run-app
Programmatic Environment Detection
Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:Detección de entorno mediante programación
Dentro del código, como en un script de Gant o una clase de bootstrap se puede detectar el entorno mediante la clase Environment:import grails.util.Environment...switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }
Per Environment Bootstrapping
Its often desirable to run code when your application starts up on a per-environment basis. To do so you can use thegrails-app/conf/BootStrap.groovy file's support for per-environment execution:Bootstrap por entorno
A menudo es deseable ejecutar código cuando la aplicación se inicia dependiendo del entorno. Para ello puede utilizar el soporte por entornos del archivograils-app/conf/BootStrap.groovy :def init = { ServletContext ctx ->
environments {
production {
ctx.setAttribute("env", "prod")
}
development {
ctx.setAttribute("env", "dev")
}
}
ctx.setAttribute("foo", "bar")
}Generic Per Environment Execution
The previousBootStrap example uses the grails.util.Environment class internally to execute. You can also use this class yourself to execute your own environment specific logic:Ejecución genérica por entorno
En el ejemplo anterior deBootStrap se utiliza la clase grails.util.Environment internamente para ejecutar. También puede utilizar esta clase para ejecutar su propia lógica especÃfica del entorno:Environment.executeForCurrentEnvironment {
production {
// hacer algo en producción
}
development {
// hacer algo en desarrollo
}
}3.3 El orÃgen de datos
Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).If you use a database other than H2 you need a JDBC driver. For example for MySQL you would need Connector/JDrivers typically come in the form of a JAR archive. It's best to use Ivy to resolve the jar if it's available in a Maven repository, for example you could add a dependency for the MySQL driver like this:
Dado que Grails se basa en la tecnologÃa Java configurar un origen de datos requiere algunos conocimientos de JDBC (la tecnologÃa que no es Java Database Connectivity).Si utiliza una base de datos que no sea H2 necesita un driver JDBC. Por ejemplo para MySQL serÃa necesario Connector/JLos drivers suelen empaquetarse en forma de un archivo JAR. Es mejor utilizar Ivy para resolver el jar si está disponible en un repositorio de Maven, por ejemplo podrÃa añadir una dependencia para el controlador de MySQL como esta: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
Tenga en cuenta que el repositorio incorporado 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:mavenCentral() se incluye aquà ya es un lugar confiable para esta biblioteca.Si no puede utilizar Ivy, ponga el jar en el directorio lib del proyecto.Una vez que tenga el jar resuelto necesita familiarizarse con el descriptor del origen de datos de Grails, ubicado en grails-app/conf/DataSource.groovy. Este archivo contiene la definición de origen de datos que incluye las siguientes opciones:driverClassName- The class name of the JDBC driverusername- The username used to establish a JDBC connectionpassword- The password used to establish a JDBC connectionurl- The JDBC URL of the databasedbCreate- 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 stdoutformatSql- Format logged SQLdialect- 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- Iftruemakes the DataSource read-only, which results in the connection pool callingsetReadOnly(true)on eachConnectionproperties- Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
driverClassName- el nombre de clase del controlador JDBC.username- el nombre de usuario utilizado para establecer una conexión JDBC.password- la contraseña utilizada para establecer una conexión JDBC.url- la URL JDBC de la base de datos.dbCreate- si se va a generar automáticamente la base de datos del dominio modelo - uno de 'create-drop'(borrar-crear), 'create'(crear), 'update'(actualizar) o 'validate' (valiadar).pooled- si va a utilizar un pool de conexiones (de forma predeterminada es true)logSql- habilitar el registro de SQL a stdout.formatSql- formato del SQL.dialect- clase o una cadena representa el dialecto de hibertnate utilizado para comunicarse con la base de datos. Ver el paquete org.hibernate.dialect para dialectos disponibles.readOnly- sitruehace el origen de datos de sólo lectura, lo que resulta en que el pool de conexiones llama asetReadOnly(true)con cadaconexión.properties- propiedades adicionales para establecer en el bean DataSource. Consulte la documentación de Commons DBCP BasicDataSource.
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:
Cuando configurando el origen de datos se incluyen el tipo o la palabra clave de def antes de cualquiera de las opciones de configuración, Groovy tratará estas como definiciones de variables locales y no se procesarán. Por ejemplo, lo siguiente es inválido:
dataSource {
boolean pooled = true // type declaration results in ignored local variable
…
}
Example of advanced configuration using extra properties:
Ejemplo de configuración avanzada utilizando propiedades adicionales:
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost/yourDB"
driverClassName = "com.mysql.jdbc.Driver"
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = "yourUser"
password = "yourPassword"
properties {
maxActive = 50
maxIdle = 25
minIdle = 5
initialSize = 5
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
validationQuery = "/* ping */"
}
}More on dbCreate
Hibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through thedbCreate property, which can take these values:
- 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
Más sobre dbCreate
Hibernate puede crear automáticamente las tablas de base de datos necesarias para su modelo de dominio. Tiene algún control sobre cuándo y cómo lo hace a través de la propiedaddbCreate, que puede tomar estos valores:
- create - borra la estructura vigente el esquema en el inicio, borrando tablas, Ãndices, etc. primero.
- create-drop - igual que create, pero también borra las tablas cuando se cierra la aplicación sin errores.
- update - crea las tablas e Ãndices que faltan y actualiza el esquema actual sin perder datos ni las tablas. Tenga en cuenta que esto no puede manejar correctamente muchos cambios en el esquema como cambios de nombre de columna (te dejan la antigua columna que contiene los datos existentes).
- validate - no modifica la base de datos. Compara la configuración con el esquema de base de datos existente y las reporta los avisos.
- cualquier otro valor - no hace nada
You can also remove the
También puede quitar el parámetro 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).
dbCreate, que es lo recomendado una vez que su esquema es relativamente estable y definitivamente cuando su base de datos y aplicaciones se implementan en producción. Los cambios de la base de datos son administrados a través de las migraciones adecuadas, con secuencias de comandos SQL o una herramienta de migración como Liquibase (el plugin Database Migration utiliza Liquibase y está estrechamente integrado con Grails y GORM).
3.3.1 OrÃgenes de datos y entornos
The previous example configuration assumes you want the same config for all environments: production, test, development etc.Grails' DataSource definition is "environment aware", however, so you can do:
La configuración del ejemplo anterior asume que desea la misma configuración para todos los entornos: producción, pruebas, desarrollo, etc..La definición de origen de datos de Grails es sensible al entorno, por lo que puedes hacer o siguiente:dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
// other common settings here
}environments {
production {
dataSource {
url = "jdbc:mysql://liveip.com/liveDb"
// other environment-specific settings here
}
}
}3.3.2 OrÃgenes de datos JNDI
Referring to a JNDI DataSource
Most Java EE containers supplyDataSource instances via Java Naming and Directory Interface (JNDI). Grails supports the definition of JNDI data sources as follows:Utilizando un origen de datos JNDI
La mayorÃa de los contenedores J2EE proporcionan instancias deDataSource a través de Java Naming and Directory Interface (JNDI). Grails es compatible con la definición de orÃgenes de datos JNDI como sigue:dataSource {
jndiName = "java:comp/env/myDataSource"
}The format on the JNDI name may vary from container to container, but the way you define the
El formato del nombre JNDI puede variar de un contenedor a otro, pero la manera de definir el DataSource in Grails remains the same.Configuring a Development time JNDI resource
The way in which you configure JNDI data sources at development time is plugin dependent. Using the Tomcat plugin you can define JNDI resources using thegrails.naming.entries setting in grails-app/conf/Config.groovy:DataSource en Grails sigue siendo la misma.Configuración de un recurso JNDI de tiempo de desarrollo
La forma en que puede configurar orÃgenes de datos JNDI al tiempo de desarrollo depende del plugin utilizado. Utilizando el plugin de Tomcat plugin puede definir recursos JNDI mediantegrails.naming.entries en grails-app/conf/Config.groovy:grails.naming.entries = [
"bean/MyBeanFactory": [
auth: "Container",
type: "com.mycompany.MyBean",
factory: "org.apache.naming.factory.BeanFactory",
bar: "23"
],
"jdbc/EmployeeDB": [
type: "javax.sql.DataSource", //required
auth: "Container", // optional
description: "Data source for Foo", //optional
driverClassName: "org.h2.Driver",
url: "jdbc:h2:mem:database",
username: "dbusername",
password: "dbpassword",
maxActive: "8",
maxIdle: "4"
],
"mail/session": [
type: "javax.mail.Session,
auth: "Container",
"mail.smtp.host": "localhost"
]
]3.3.3 Migraciones automáticas de bases de datos
The
La propiedad dbCreate property of the DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are described in the DataSource section:
createcreate-dropupdatevalidate- no value
dbCreate is by default set to "create-drop", but at some point in development (and certainly once you go to production) you'll need to stop dropping and re-creating the database every time you start up your server.dbCreate de la definición del DataSource es importante ya que dicta lo que debe hacer Grails en tiempo de ejecución con respecto a la generación automática de las tablas de base de datos de clases GORM. Las opciones se describen en la sección DataSource:
createcreate-dropupdatevalidate- no value
dbCreate es por defecto "create-drop" (borrar y crear), pero en algún punto en el desarrollo (y, desde luego, una vez pase a la producción) deberá dejar de borrar y volver a crear la base de datos cada vez que inicie el servidor.It's tempting to switch to
Es tentador cambiar a update so you retain existing data and only update the schema when your code changes, but Hibernate's update support is very conservative. It won't make any changes that could result in data loss, and doesn't detect renamed columns or tables, so you'll be left with the old one and will also have the new one.Grails supports Rails-style migrations via the Database Migration plugin which can be installed by running
grails install-plugin database-migrationThe 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).
update (actualizar) para mantener los datos existentes y sólo actualizar el esquema cuando el código cambia, pero el soporte de actualización de Hibernate es muy conservador. No realizar los cambios que podrÃan dar lugar a pérdida de datos y no detecta renombrado de columnas o tablas, por lo que quedará con el viejo y también con el nuevo.Grails soporta migraciones estilo Rails a través del plugin Database Migration plugin que puede instalarse mediante la ejecución de
grails install-plugin database-migrationEl plugin utiliza Liquibase y proporciona acceso a toda su funcionalidad y también cuenta con soporte para GORM (por ejemplo generando un cambio comparando sus clases de dominio con una base de datos).
3.3.4 Proxy de origen de datos preparado para transacción
The actual
El dataSource bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate Session if one is active.If this were not the case, then retrieving a connection from the dataSource would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. READ_COMMITTED or better).The "real" unproxied dataSource is still available to you if you need access to it; its bean name is dataSourceUnproxied.You can access this bean like any other Spring bean, i.e. using dependency injection:
dataSource bean está envuelto en un proxy preparado para la transacción por lo que se le dará la conexión que se utiliza en la transacción actual o la Session Hibernate si está activa.Si esto no fuera el caso, entonces recuperar una conexión desde el datasource serÃa una nueva conexión, y no serÃa capaz de ver los cambios que no hayan sido comprometidos aún (suponiendo que tiene un aislamiento de transacción razonable, por ejemplo, READ_COMMITTED o mejor).El dataSource real fuera del proxy sigue estando disponible si necesita tener acceso a él; su nombre de bean es dataSourceUnproxied.Se puede acceder a este bean como a cualquier otro bean de Spring, es decir, mediante inyección de dependencias:class MyService { def dataSourceUnproxied
…
}
or by pulling it from the
o solicitándolo al ApplicationContext:
ApplicationContext:def dataSourceUnproxied = ctx.dataSourceUnproxied
3.3.5 La consola de la Base de Datos
The H2 database console is a convenient feature of H2 that provides a web-based interface to any database that you have a JDBC driver for, and it's very useful to view the database you're developing against. It's especially useful when running against an in-memory database.
La consola de base de datos H2 es una práctica función de H2 que proporciona una interfaz basada en web para cualquier base de datos que tenga un driver JDBC, y es muy útil para ver la base de datos contra la que se está desarrollando. Es especialmente útil cuando se ejecuta contra una base de datos en memoria.
You can access the console by navigating to http://localhost:8080/appname/dbconsole in a browser. The URI can be configured using the
Para acceder a la consola, vaya a la dirección http://localhost:8080/appname/dbconsole en un navegador. La URI se puede configurar mediante el atributo grails.dbconsole.urlRoot attribute in Config.groovy and defaults to '/dbconsole'.
grails.dbconsole.urlRoot en el Config.groovy y por defecto es '/dbconsole'.
The console is enabled by default in development mode and can be disabled or enabled in other environments by using the
La consola está activada por defecto en el modo de desarrollo y puede ser activada o desactivada en otros ambientes mediante el uso del atributo grails.dbconsole.enabled attribute in Config.groovy. For example you could enable the console in production using
grails.dbconsole.enabled en el Config.groovy. Por ejemplo, podrÃa habilitar la consola en la producción asÃ: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 tojdbc: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.
Si habilita la consola en producción asegúrese de proteger el acceso a ella mediante un framework de seguridad de confianza.
Configuración
Por defecto, la consola está configurada para una base de datos H2 que funciona con la configuración predeterminada si no ha configurado una base de datos externa; basta con cambiar la URL JDBC ajdbc:h2:mem:devDB. Si ha configurado una base de datos externa (por ejemplo, MySQL, Oracle, etc.) puede utilizar la lista desplegable de Saved Settings para seleccionar una plantilla y rellenar la url, y el nombre de usuario y contraseña de tu DataSource.groovy.
3.3.6 OrÃgenes de datos multiples
By default all domain classes share a single
Por defecto, todas las clases de dominio compartan un solo DataSource and a single database, but you have the option to partition your domain classes into two or more DataSources.Configuring Additional DataSources
The defaultDataSource configuration in grails-app/conf/DataSource.groovy looks something like this:
DataSource y una única base de datos, pero tiene la opción de dividir las clases de dominio en dos o más DataSources.Configuración de orÃgenes de datos adicionales
La configuración delDataSource por defecto en grails-app/conf/DataSource.groovy es algo como esto: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
Esto configura un único 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:
DataSource con un bean de Spring llamado dataSource. Para configurar DataSources adicionales, agregue otro bloque dataSource (en el nivel superior, en un bloque de entorno, o ambos, al igual que la definición estándar de DataSource) con un nombre personalizado, separado por un guión bajo. Por ejemplo, esta configuración agrega un segundo DataSource, usando MySQL en el entorno de desarrollo y Oracle en producción: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.
Puede utilizar las mismos o diferentes bases de datos siempre y cuando esté soportadas por Hibernate.Configuring Domain Classes
If a domain class has noDataSource configuration, it defaults to the standard 'dataSource'. Set the datasource property in the mapping block to configure a non-default DataSource. For example, if you want to use the ZipCode domain to use the 'lookup' DataSource, configure it like this;
Configuración de clases de dominio
Si una clase de dominio no tiene ninguna configuración deDataSource, utiliza el 'dataSource' estándar. Debe establecer la propiedad datasource en el bloque mapping para configurar otro DataSource. Por ejemplo, si desea que el dominio ZipCode utilice el DataSource 'lookup', configurelo asÃ:class ZipCode { String code static mapping = {
datasource 'lookup'
}
}
A domain class can also use two or more
Una clase de dominio también puede utilizar dos o más DataSources. Use the datasources property with a list of names to configure more than one, for example:
DataSources. Use la propiedad datasources con una lista de nombres para configurar más de uno, por ejemplo:class ZipCode { String code static mapping = {
datasources(['lookup', 'auditing'])
}
}
If a domain class uses the default
Si una clase de dominio utiliza el DataSource and one or more others, use the special name 'DEFAULT' to indicate the default DataSource:
DataSource por defecto y algún o algunos otros, utilice el nombre especial 'DEFAULT' para indicar el DataSource por defecto:class ZipCode { String code static mapping = {
datasources(['lookup', 'DEFAULT'])
}
}
If a domain class uses all configured
Si una clase de dominio utiliza todos los DataSources use the special value 'ALL':
DataSources configurados use el valor especial 'ALL':class ZipCode { String code static mapping = {
datasource 'ALL'
}
}Namespaces and GORM Methods
If a domain class uses more than oneDataSource then you can use the namespace implied by each DataSource name to make GORM calls for a particular DataSource. For example, consider this class which uses two DataSources:
Espacios de nombres y métodos GORM
Si una clase de dominio utiliza más de unDataSource puede utilizar el espacio de nombres que implica cada nombre de DataSource para hacer llamadas GORM para un determinado DataSource. Por ejemplo, esta clase que utiliza dos DataSources:class ZipCode { String code static mapping = {
datasources(['lookup', 'auditing'])
}
}
The first As you can see, you add the
El primer 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:def zipCode = ZipCode.auditing.get(42) … zipCode.auditing.save()
DataSource to the method call in both the static case and the instance case.
DataSource especificado es el valor por defecto cuando no se utiliza un espacio de nombre explÃcito, por lo que en este caso el predeterminado es 'lookup'. Pero puede llamar a métodos GORM con el DataSource con nombre del DataSource, por ejemplo:def zipCode = ZipCode.auditing.get(42) … zipCode.auditing.save()
DataSource a la llamada de método tanto en el caso de llamada estática como en el caso de la instancia.Services
Like Domain classes, by default Services use the defaultDataSource and PlatformTransactionManager. To configure a Service to use a different DataSource, use the static datasource property, for example:
Servicios
Como las clases de dominio, los servicios utilizan elDataSource por defecto y el PlatformTransactionManager. Para configurar un servicio para que utilice un DataSource diferente , utilice la propiedad estática datasource, por ejemplo:class DataService { static datasource = 'lookup' void someMethod(...) {
…
}
}
A transactional service can only use a single
Un servicio transaccional puede sólo utilizar un único 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.DataSource, asà que asegúrese de sólo hacer cambios para las clases de dominio cuyos DataSource es el mismo que el del servicio.Tenga en cuenta que la fuente de datos que se especifica en un servicio no tiene relación con las fuentes de datos que se utilizan para las clases de dominio, que son determinadas por los orÃgenes de datos declarados en las clases de dominio. Se utiliza para declarar que administrador de transacciones se utilizará.Lo que verá es que si usted tiene una clase de dominio Foo en un DataSource1 y una clase de dominio Bar en el dataSource2 y un servicio WahooService utiliza el DataSource1, un método del servicio que salva un nuevo Foo y un nuevo Bar sólo será transaccional para Foo, ya que comparten la fuente de datos, y la operación no afectará a la instancia de Bar. Si quieres ser transaccional para ambas instancias tendrá que utilizar dos servicios y fuentes de datos con commit en dos fases, por ejemplo, con el plugin Atomikos.XA and Two-phase Commit
Grails has no native support for XADataSources or two-phase commit, but the Atomikos plugin makes it easy. See the plugin documentation for the simple changes needed in your DataSource definitions to reconfigure them as XA DataSources.XA y commit en dos fases
Grails no tiene soporte nativo paraDataSources XA o commit en dos fases, pero el plugin Atomikos hace que sea fácil. Consulte la documentación de plugin para conocer los cambios que debe hacer en la definición de su DataSource para configurarlos como DataSources XA.
3.4 Externalizando la configuración
Some deployments require that configuration be sourced from more than one place and be changeable without requiring a rebuild of the application. In order to support deployment scenarios such as these the configuration can be externalized. To do so, point Grails at the locations of the configuration files that should be used by adding a
Algunas implementaciones requieren que la configuración proceda de más de una ubicación y sea intercambiables sin necesidad de un redespliegue de la aplicación. Para admitir estos escenarios de despliegue la configuración puede ser externalizada. Para ello, señale a Grails las ubicaciones de los archivos de configuración que deben utilizarse mediante la adición de un valor de grails.config.locations setting in Config.groovy, for example:grails.config.locations en Config.groovy, por ejemplo:Grails.config.Locations = [
"classpath:$ {appName}-config.properties",
"classpath:$ {appName}-config.groovy",
"file:${userHome}/.grails/${appName}-config.properties",
"file:${userHome}/.grails/${appName}-config.groovy"]In the above example we're loading configuration files (both Java Properties files and ConfigSlurper configurations) from different places on the classpath and files located in 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.
En el ejemplo anterior estamos cargando archivos de configuración (archivos de propiedades Java y configuraciones de ConfigSlurper de diferentes lugares del classpath y archivos ubicados en 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]
USER_HOME.También es posible cargar configuración especificando una clase que es un script de configuración.Grails.config.Locations = [com.my.app.MyConfig]
Ultimately all configuration files get merged into the
En última instancia todos los archivos de configuración se fusionaron en la propiedad 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 thegrails.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.config del objeto GrailsApplication y, por tanto, puede obtenerse a partir de ahÃ.Los valores que tienen el mismo nombre que otros valores definidos anteriormente sobrescribirán los valores existentes y las referencias de configuración se cargan en el orden en el que se definen.Valores de configuración predeterminados
Los valores de configuración contenidos en los lugares descritos por la propiedadgrails.config.locations sobreescribirán los valores definidos en el archivo Config.groovy de la aplicación que puede no ser lo que quiere. Puede que desee tener un conjunto de valores por defecto cargados que pueden ser sobreescritos en el archivo Config.groovy de la aplicación o en cualquier localización definida. Para ello puede utilizar la propiedad grails.config.defaults.locations.Esta propiedad soporta los mismos valores que la propiedad grails.config.locations (es decir, rutas para scripts de configuración, los archivos de propiedad o clases), pero la configuración descrita por grails.config.defaults.locations será cargada antes que todos los demás valores y por lo tanto, se puede reemplazar. Algunos plugins usan este mecanismo para proporcionar uno o más conjuntos de configuración por defecto que puede incluir en la configuración de su aplicación.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
Grails también soporta el concepto de titulares de la propiedad y configuradores de reemplazo de propiedad tal como se define en Spring Para obtener más información sobre estos, consulte la sección Grails y Spring
3.5 Versionado
Versioning Basics
Grails has built in support for application versioning. The version of the application is set to0.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.To change the version of your application you can edit the file manually, or run the set-version command:Conceptos básicos de versionado
Grails se ha construido con soporte a la creación de versiones de aplicaciones. La versión de la aplicación se establece en0,1 cuando se crea una aplicación con el comando create-app. La versión se almacena en el archivo de meta datos de la aplicación application.properties en la raÃz del proyecto.Para cambiar la versión de la aplicación puede editar manualmente el archivo o ejecute el comando set-version: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.
La versión se utiliza en varios comandos incluyendo el comando war que anexará la versión de la aplicación al final en el nombre del archivo war creado.Detecting Versions at Runtime
You can detect the application version using Grails' support for application metadata using the GrailsApplication class. For example within controllers there is an implicit grailsApplication variable that can be used:Detectar versiones en tiempo de ejecución
Puede detectar la versión de la aplicación mediante el soporte de Grails para metadatos de aplicación mediante la clase GrailsApplication. Por ejemplo dentro de los controllers es una variable implÃcita grailsApplication que puede utilizarse:def version = grailsApplication.metadata['app.version']
You can retrieve the the version of Grails that is running with:
Puede recuperar la versión de Grails que se ejecuta con:def grailsVersion = grailsApplication.metadata['app.grails.version']
or the
o en la clase GrailsUtil class:
GrailsUtil:import grails.util.GrailsUtil
…
def grailsVersion = GrailsUtil.grailsVersionnull
3.6 Documentación del projecto
Since Grails 1.2, the documentation engine that powers the creation of this documentation has been available for your own Grails projects.The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.
Desde Grails 1.2, el motor de documentación usado para la creación de esta documentación ha estado disponible para sus propios proyectos de Grails.El motor de documentación utiliza una variación de la sintaxis de Textile para crear automáticamente la documentación del proyecto con enlaces, formato, etc..Creating project documentation
To use the engine you need to follow a few conventions. First, you need to create asrc/docs/guide directory where your documentation source files will go. Then, you need to create the source docs themselves. Each chapter should have its own gdoc file as should all numbered sub-sections. You will end up with something like:Creación de documentación del proyecto
Para utilizar el motor tiene que seguir unos convenios. En primer lugar, debe crear a un directoriosrc/docs/guide donde irán sus archivos de documentación. A continuación, debe crear a los documentos propiamente. Cada capÃtulo debe tener su propio archivo de gdoc asà como las subsecciones. Acabará con algo asà como:+ src/docs/guide/introduction.gdoc + src/docs/guide/introduction/changes.gdoc + src/docs/guide/gettingStarted.gdoc + src/docs/guide/configuration.gdoc + src/docs/guide/configuration/build.gdoc + src/docs/guide/configuration/build/controllers.gdoc
Note that you can have all your gdoc files in the top-level directory if you want, but you can also put sub-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
Tenga en cuenta que puede tener todos los archivos gdoc en el directorio de nivel superior si quiere, pero también puede poner subsecciones en subdirectorios después de la sección principal, como se muestra en el ejemplo anterior.Una vez que tenga los archivos origen, aún necesita decirle al motor de documentación lo que va a ser la estructura de la GuÃa de Usuario. Para hacerlo, debe agregar un archivo 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:src/docs/guide/toc.yml que contiene la estructura y los tÃtulos de cada sección. Este archivo está en formato YAML y básicamente representa la estructura de la GuÃa de Usuario en forma de árbol. Por ejemplo, los archivos anteriores podrÃan representarse como: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
El formato es bastante sencillo. Cualquier sección que tiene subsecciones se representa con el nombre de archivo correspondiente (menos la extensión .gdoc) seguido de dos puntos. La siguiente lÃnea debe contener 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.Creating reference items
Reference items appear in the Quick Reference section of the documentation. Each reference item belongs to a category and a category is a directory located in thesrc/docs/ref directory. For example, suppose you have defined a new controller method called renderPDF. That belongs to the Controllers category so you would create a gdoc text file at the following location:title: además el tÃtulo de la sección como lo verá el usuario final. AsÃ, cada subsección tiene su propia lÃnea después del tÃtulo. Los nodos hoja, es decir, aquellos sin ningún subsección, declaran su tÃtulo en la misma lÃnea que el nombre de sección pero después de los dos puntos.Eso es todo. Puede agregar, eliminar y mover secciones dentro de toc.yml para reestructurar la GuÃa de Usuario generada. También debe asegurarse de que todos los nombres de sección, es decir, los nombres de los archivos gdoc, deben ser únicos, ya que se utilizan para crear enlaces internos y los nombres de archivo HTML. No se preocupe de ello, porque el motor de documentación le avisará de los nombres de sección duplicados.Creación de elementos de referencia
Elementos de referencia aparecen en la sección de referencia rápida de la documentación. Cada elemento de referencia pertenece a una categorÃa y una categorÃa es un directorio ubicado en el directoriosrc/docs/ref. Por ejemplo, suponga que ha definido un nuevo método de controlador llamado renderPDF. Pertenece a la categorÃa controladores por lo que debe crear un archivo de texto gdoc en la siguiente ubicación:+ src/docs/ref/Controllers/renderPDF.gdoc
Configuring Output Properties
There are various properties you can set within yourgrails-app/conf/Config.groovy file that customize the output of the documentation such as:
- 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
Configuración de las propiedades de salida
Hay varias propiedades que se pueden definir en el archivograils-app/conf/Config.groovy que personalizan el resultado de la documentación, como:
- grails.doc.authors - los autores de la documentación
- grails.doc.license - la licencia del software
- grails.doc.copyright - el mensaje de copyright para mostrar
- grails.doc.footer - el pie de página para utilizar
Other properties such as the name of the documentation and the version are pulled from your project itself.
Otras propiedades como el nombre de la versión y la documentación son extraÃdos de su propio proyecto.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:Generación de documentación
Una vez haya creado alguna documentación (consulte la GuÃa de sintaxis en el capÃtulo siguiente) puede generar una versión HTML de la documentación mediante el comando:grails doc
This command will output an
Este comando generará un 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
docs/manual/index.html que se puede abrir en un navegador para ver la documentación.Sintaxis de documentación
Como se ha mencionado, la sintaxis es muy similar al estilo de marcado de wiki de Textile o Confluence. Las siguientes secciones le guÃan a través de los fundamentos de la sintaxis.Formato básico
Monospace:monospace
@monospace@
_italic_
*bold*
_italic_

!http://grails.org/images/new/grailslogo_topNav.png!
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/]
"SpringSource":http://www.springsource.com/Enlazando
Hay varias formas de crear vÃnculos con el generador de documentación. Un enlace externo básico puede definirse mediante el estilo marcado de Confluence o Textile:[SpringSource|http://www.springsource.com/]
"SpringSource":http://www.springsource.com/
For links to other sections inside the user guide you can use the 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:
Para enlaces a otras secciones dentro de la GuÃa de Usuario puede utilizar el prefijo guide: prefix with the name of the section you want to link to:[Intro|guide:introduction]
guide: con el nombre de la sección que desea enlazar:[Intro|guide:introduction]
[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
En este caso la categorÃa del elemento de referencia es el lado izquierdo de la | y el nombre del elemento de referencia es el de la derecha.Finalmente, para vincular a las API externas puede utilizar el prefijo api: prefix. For example:api:. Por ejemplo:[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 The above example configures classes within the
El motor de documentación creará automáticamente el vÃnculo javadoc apropiado en este caso. Para agregar APIs adicionales al motor se puede configurar en grails-app/conf/Config.groovy. For example:grails.doc.api.org.hibernate=
"http://docs.jboss.org/hibernate/stable/core/javadocs"org.hibernate package to link to the Hibernate website's API docs.grails-app/conf/Config.groovy. Por ejemplo:grails.doc.api.org.hibernate=
"http://docs.jboss.org/hibernate/stable/core/javadocs"org.hibernate para vincular documentos de APIs del sitio web de Hibernate.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
Listas y cabeceras
Las cabeceras pueden crearse mediante la especificación de la letra 'h' seguido de un número y un punto:h3.<space>TÃtulo3 h4.<space>Heading4
* item 1 ** subitem 1 ** subitem 2 * item 2
Numbered lists can be defined with the # character:
Las listas numeradas pueden definirse con el carácter #:# item 1
Tables can be created using the
Las tablas pueden ser generadas usando la macro table macro:| Name | Number |
|---|---|
| Albert | 46 |
| Wilma | 1348 |
| James | 12 |
table:| Name | Number |
|---|---|
| Albert | 46 |
| Wilma | 1348 |
| James | 12 |
{table}
*Nombre* | *Número*
Albert | 46
Wilma | 1348
James | 12
{table}Code and Notes
You can define code blocks with thecode macro:Código y notas
Puede definir bloques de código con la macrocode:class Book {
String title
}{code}
class Book {
String title
}
{code}
The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:
El ejemplo anterior proporciona resaltado de sintaxis para código Java y Groovy, pero también puede resaltar código XML:<hello>world</hello>
{code:xml}
<hello>world</hello>
{code}There are also a couple of macros for displaying notes and warnings:
También hay un par de macros para mostrar notas y avisos:Note:
This is a note!
{note}
This is a note!
{note}Warning:
Advertencia:This is a warning!
{warning}
This is a warning!
{warning}3.7 Resolución de dependencias
Grails features a dependency resolution DSL that lets you control how plugins and JAR dependencies are resolved.You specify a
Grails ofrece un DSL de resolución de dependencia que le permite controlar cómo se resuelven las dependencias de plugins y de los JAR.Especifica una propiedad grails.project.dependency.resolution property inside the grails-app/conf/BuildConfig.groovy file that configures how dependencies are resolved:grails.project.dependency.resolution dentro del archivo grails-app/conf/BuildConfig.groovy que configura cómo se resuelven las dependencias:grails.project.dependency.resolution = {
// config here
}The default configuration looks like the following:
La configuración por defecto el siguiente aspecto: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.
Los detalles sobre lo anterior se explica en las siguientes secciones.
3.7.1 Configuración y dependencias
Grails features five dependency resolution configurations (or 'scopes'):
Grails ofrece cinco configuraciones de resolución de dependencia (o 'ámbitos'):
-
build: Dependencies for the build system only -
compile: Dependencies for the compile step -
runtime: Dependencies needed at runtime but not for compilation (see above) -
test: Dependencies needed for testing but not at runtime (see above) -
provided: Dependencies needed at development time, but not during WAR deployment
dependencies block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at runtime you can specify that like this:build: dependencias sólo para el sistema de compilación.compile: dependencias para el tiempo de compilación.runtime: dependencias necesarias en tiempo de ejecución, pero no para la compilación (véase más arriba).test: dependencias necesarias para las pruebas, pero no en tiempo de ejecución (véase más arriba).provided: dependencias necesarias en el tiempo de desarrollo, pero no durante el despliegue de WAR.
dependencies puede especificar una dependencia que corresponde con una de estas configuraciones llamando al método equivalente. Por ejemplo, si su aplicación requiere el controlador MySQL funcione en tiempo de ejecución(runtime) puede especificaro asÃ:runtime 'com.mysql:mysql-connector-java:5.1.16'
This uses the string syntax:
Esto utiliza la sintaxis de cadena: group:name:version. You can also use a Map-based syntax:group:name:version. También puede utilizar una sintaxis basada en mapas:runtime group: 'com.mysql',
name: 'mysql-connector-java',
version: '5.1.16'In Maven terminology,
En la terminologÃa de Maven, group corresponds to an artifact's groupId and name corresponds to its artifactId.Multiple dependencies can be specified by passing multiple arguments:group corresponde al groupId de un artefacto y name corresponde a su artifactId.Varias dependencias pueden especificarse pasando varios argumentos:runtime 'com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1'// oruntime(
[group:'com.mysql', name:'mysql-connector-java', version:'5.1.16'],
[group:'net.sf.ehcache', name:'ehcache', version:'1.6.1']
)Disabling transitive dependency resolution
By default, Grails will not only get the JARs and plugins that you declare, but it will also get their transitive dependencies. This is usually what you want, but there are occasions where you want a dependency without all its baggage. In such cases, you can disable transitive dependency resolution on a case-by-case basis:Deshabilitar la resolución de dependencias transitiva
De forma predeterminada, Grails no sólo obtendrá los jars y plugins que se declaran, sino también sus dependencias transitivas. Esto suele ser lo que se desea, pero hay ocasiones donde desea una dependencia sin todo su equipaje. En tales casos, puede deshabilitar la resolución de dependencia transitivas:runtime('com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') {
transitive = false
}// o
runtime group:'com.mysql',
name:'mysql-connector-java',
version:'5.1.16',
transitive:falseExcluding specific transitive dependencies
A far more common scenario is where you want the transitive dependencies, but some of them cause issues with your own dependencies or are unnecessary. For example, many Apache projects have 'commons-logging' as a transitive dependency, but it shouldn't be included in a Grails project (we use SLF4J). That's where theexcludes option comes in:Excluyendo las dependencias transitivas especÃficas
Un escenario mucho más común es cuando desea las dependencias transitivas, pero algunos de ellos causan problemas con sus propias dependencias o son innecesarias. Por ejemplo, muchos proyectos de Apache tienen 'commons-logging' como una dependencia transitiva, pero no deberÃa ser incluido en un proyecto Grails (utilizamos SLF4J). Ahà es donde la opciónexcludes interviene:runtime('com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') {
excludes "xml-apis", "commons-logging"
}// o
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
Como puede ver, puede excluir las dependencias por su ID de artefacto (también conocido como un nombre de módulo) o cualquier combinación de ID de grupo y artefacto (si se utiliza la notación del mapa). También puede utilizar exclude as well, but that can only accept a single string or Map:exclude, pero este sólo puede aceptar una sola cadena o mapa:runtime('com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') {
exclude "xml-apis"
}Using Ivy module configurations
If you use Ivy module configurations and wish to depend on a specific configuration of a module, you can use thedependencyConfiguration method to specify the configuration to use.Utilizando las configuraciones de módulo de Ivy
Si utiliza las configuraciones de módulo de Ivy y desea depender de una configuración especÃfica de un módulo, puede utilizar el métododependencyConfiguration para especificar la configuración a usar.provided("my.org:web-service:1.0") { dependencyConfiguration "api" }
If the dependency configuration is not explicitly set, the configuration named
Si no se establece explÃcitamente la configuración de la dependencia, la configuración denominada "default" will be used (which is also the correct value for dependencies coming from Maven style repositories).
"default" se utilizará (que es también el valor correcto para dependencias procedentes de repositorios de estilo Maven).
3.7.2 Repositorios de dependencias
Remote Repositories
Initially your BuildConfig.groovy does not use any remote public Maven repositories. There is a defaultgrailsHome() repository that will locate the JAR files Grails needs from your Grails installation. To use a public repository, specify it in the repositories block:Repositorios remotos
Inicialmente su BuildConfig.groovy no utiliza los repositorios Maven públicos remotos. Existe un repositorio por defectograilsHome() que buscará los archivos JAR Grails necesarios para la instalación de Grails. Para usar un público, especifiquelo en bloque repositories:repositories {
mavenCentral()
}In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the
En este caso se especifica el repositorio de Maven público predeterminado. Para utilizar el repositorio de paquetes empresarial de SpringSource (Enterprise Bundle Repository) puede utilizar el método ebr() method:ebr() método:repositories {
ebr()
}You can also specify a specific Maven repository to use by URL:
También puede especificar un repositorio Maven especÃfico utilizando una URL:repositories {
mavenRepo "http://repository.codehaus.org"
}Controlling Repositories Inherited from Plugins
A plugin you have installed may define a reference to a remote repository just as an application can. By default your application will inherit this repository definition when you install the plugin.Repositorios de control heredados de Plugins
Un plugin que ha instalado puede definir una referencia a un repositorio remoto igual que una aplicación. Por defecto la aplicación heredará esta definición de repositorio al instalar el plugin.If you do not wish to inherit repository definitions from plugins then you can disable repository inheritance:
Si no desea heredar las definiciones de repositorio de plugins puede desactivar herencia del repositorio:repositories {
inherit false
}En este caso su aplicación no heredará las definiciones de repositorio de plugins y es su labor proporcionar definiciones adecuadas de repositorio (posiblemente internos).
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'
}Resoluciones locales
Si no desea usar un repositorio Maven puede especificar un repositorio de archivos planos:repositories {
flatDir name:'myRepo', dirs:'/path/to/repo'
}~/.m2/repository) as a repository:Para especificar su memoria caché local de Maven (
~/.m2/repository) como un repositorio:repositories {
mavenLocal()
}Custom Resolvers
If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:Resoluciones personalizadas
Si todo lo demás falla como Grails se basa en Apache Ivy puede especificar una resolución Ivy:/* * 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 = ivySettingsresolver 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:
También es posible extraer las dependencias de un repositorio mediante SSH. Ivy viene con una resolutor dedicado que puede configurar e incluir en el proyecto como tal: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:
Descargue el JAR JSch y añadalo al classpath de Grails para utilizar el resolutor SSH. Puede hacerlo pasando la ruta en la lÃnea de comandos de Grails:grails -classpath /path/to/jsch compile|run-app|etc.
You can also add its path to the
También puede agregar su ruta a la variable de entorno 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.CLASSPATH pero tenga en cuenta este afecta a muchas aplicaciones de Java. Una alternativa en Unix es crear un alias para grails - classpath..., por lo que no es necesario que escriba los argumentos adicionales cada vez.Authentication
If your repository requires authentication you can configure this using acredentials block:Autenticación
Si su repositorio requiere autenticación puede configurar esto utilizando el bloquecredentials:credentials {
realm = ".."
host = "localhost"
username = "myuser"
password = "mypass"
}This can be placed in your
Esto puede ser colocado en el archivo USER_HOME/.grails/settings.groovy file using the grails.project.ivy.authentication setting:USER_HOME/.grails/settings.groovy mediante la configuración de grails.project.ivy.authentication:grails.project.ivy.authentication = {
credentials {
realm = ".."
host = "localhost"
username = "myuser"
password = "mypass"
}
}3.7.3 Depurando la resolución de dependencias
If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the
Si está teniendo problemas para conseguir que una dependencia se resuelva puede habilitar un modo de depueración más detallado del motor subyacente mediante el método log method:log:// log level of Ivy resolver, either 'error', 'warn',
// 'info', 'debug' or 'verbose'
log "warn"3.7.4 Dependencias heredadas
By default every Grails application inherits several framework dependencies. This is done through the line:Inside the
De forma predeterminada cada aplicación Grails hereda varias dependencias del framework. Esto se realiza a través de la lÃnea:inherits "global"BuildConfig.groovy file. To exclude specific inherited dependencies you use the excludes method:inherits "global"BuildConfig.groovy. Para excluir dependencias heredadas especÃficas usa el método excludes:inherits("global") { excludes "oscache", "ehcache" }
3.7.5 Dependencias por defecto
Most Grails applications have runtime dependencies on several jar files that are provided by the Grails framework. These include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container.The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. This is done by invoking the
La mayorÃa de las aplicaciones Grails tienen dependencias de tiempo de ejecución sobre varios archivos jar que proporcionan el framwork Grails. Estos incluyen bibliotecas como Spring, Sitemesh, Hibernate, etc… Cuando se crea un archivo war, todas estas dependencias se incluirá en él. Sin embargo, una aplicación puede excluir estos archivos jar del war. Esto es útil cuando los archivos jar serán proporcionados por el contenedor, ya que normalmente serÃa el caso si varias aplicaciones Grails se despliegan en el mismo contenedor.La resolución de dependencias DSL proporciona un mecanismo para expresar que todas las dependencias predeterminado serán proporcionados por el contenedor. Esto se hace invocando al método defaultDependenciesProvided method and passing true as an argument:defaultDependenciesProvided y pasando true como argumento:grails.project.dependency.resolution = { defaultDependenciesProvided true // all of the default dependencies will
// be "provided" by the container inherits "global" // inherit Grails' default dependencies repositories {
grailsHome()
…
}
dependencies {
…
}
}defaultDependenciesProvidedmust come beforeinherits, otherwise the Grails dependencies will be included in the war.
defaultDependenciesProvideddebe venir antes deinherits, de lo contrario las dependencias Grails se incluirá en el war.
3.7.6 Informes de dependencias
As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.To obtain a report of an application's dependencies you can run the dependency-report command:By default this will generate reports in the
Como se menciona en la sección anterior una aplicación Grails consiste en dependencias heredadas del framwork, los plugins instalados y las dependencias de las aplicaciones en sÃ.Para obtener un informe de las dependencias de una aplicación puede ejecutar el comando dependency-report:grails dependency-report
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
target/dependency-report. Puede especificar qué configuración (alcance) desea en un informe pasando un argumento que contiene el nombre de configuración:grails dependency-report runtime
3.7.7 Dependencias Jar de plugins
Specifying Plugin JAR dependencies
The way in which you specify dependencies for a plugin is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.To define a dependency that is resolved for use with the plugin but not exported to the application then you can set theexport property of the dependency:Especificación de las dependencias JAR de un plugin
La forma en que se especifican las dependencias para un plugin es idéntica a la que permite especificar las dependencias en una aplicación. Cuando se instala un plugin en una aplicación la aplicación hereda automáticamente las dependencias del plugin.Para definir una dependencia que se resuelve para su uso con el plugin pero no se exporta a la aplicación, puede definir la propiedadexport de la dependencia:test('org.spockframework:spock-core:0.5-groovy-1.8') {
export = false
}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:
En este caso la dependencia Spock estará disponibles sólo para el plugin y no será resuelta como una dependencia de la aplicación. Alternativamente, si utiliza la sintaxis de mapa:test group: 'org.spockframework', name: 'spock-core',
version: '0.5-groovy-1.8', export: falseYou can useexported = falseinstead ofexport = false, but we recommend the latter because it's consistent with the Map argument.
Puede utilizarexported = falseen lugar deexport = false, pero recomendamos este último porque es coherente con el argumento de mapa.
Overriding Plugin JAR Dependencies in Your Application
If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:Reemplazar las dependencias JAR de un plugin en su aplicación
Si un plugin está utilizando un JAR que crea conflictos con otro plugin, o con una dependencia de la aplicación, se puede modificar cómo un plugin resuelve sus dependencias dentro de una aplicación mediante las exclusiones. Por ejemplo:plugins {
compile(":hibernate:$grailsVersion") {
excludes "javassist"
}
}dependencies {
runtime "javassist:javassist:3.4.GA"
}In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the
En este caso la aplicación explÃcitamente declara una dependencia en el plugin de "hibernate" y especifica una exclusión utilizando el método excludes method, effectively excluding the javassist library as a dependency.
excludes, excluyendo la biblioteca de javassist como una dependencia.
3.7.8 Integración con Maven
When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies with Maven's
Cuando se utiliza el plugin Grails Maven, los mecánismos de resolución de dependencias de Grails están deshabilitados porque se supone que gestionará las dependencias con el archivo de pom.xml file.However, if you would like to continue using Grails regular commands like run-app, test-app and so on then you can tell Grails' command line to load dependencies from the Maven pom.xml file instead.To do so simply add the following line to your BuildConfig.groovy:pom.xml de Maven.Sin embargo, si desea seguir utilizando los comandos Grails como run-app, test-app,etc… puede indicarle a la lÃnea de comandos de Grails que cargue las dependencias del archivo pom.xml Maven en su lugar.Asà que simplemente añada la siguiente lÃnea a su BuildConfig.groovy :grails.project.dependency.resolution = {
pom true
..
}
The line
La lÃnea pom true tells Grails to parse Maven's pom.xml and load dependencies from there.
pom true le dice a Grails que analice el pom.xml de Maven y cargue las dependencias desde allÃ.
3.7.9 Desplegando a un repositorio Maven
If you use Maven to build your Grails project, you can use the standard Maven targets
Si utiliza a Maven para construir su proyecto Grails, puede utilizar el target estándar de Maven mvn install and mvn deploy.
If not, you can deploy a Grails project or plugin to a Maven repository using the maven-publisher plugin.The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories. There are two key additional targets added by the plugin:
- maven-install - Installs a Grails project or plugin into your local Maven cache
- maven-deploy - Deploys a Grails project or plugin to a remote Maven repository
pom.xml for you unless a pom.xml is already present in the root of the project, in which case this pom.xml file will be used.mvn install and mvn deploy.
Si no es asÃ, puede desplegar un proyecto Grails o un plugin en un repositorio de Maven utilizando el plugin maven-publisher.El plugin permite publicar proyectos Grails y plugins en repositorios Maven locales y remotos. Hay dos target principales adicionales agregados por el plugin:
- maven-install - instala un plugin o un proyecto Grails en la caché local de Maven.
- maven-deploy - despliega un proyecto Grails o plugin para un repositorio Maven remoto.
pom.xml válido a menos que un pom.xml ya está presente en la raÃz del proyecto, en cuyo caso se utilizará este archivo pom.xml.maven-install
Themaven-install command will install the Grails project or plugin artifact into your local Maven cache:grails maven-install
maven-install
El comandomaven-install instalará el proyecto o plugin Grails en la caché local de Maven:grails maven-install
maven-deploy
Themaven-deploy command will deploy a Grails project or plugin into a remote Maven repository:grails maven-deploy
<distributionManagement> configuration within a pom.xml or that you specify the id of the remote repository to deploy to:maven-deploy
El comandomaven-deploy desplegará un proyecto Grails o plugin en un repositorio de Maven remoto:grails maven-deploy
<distributionmanagement> dentro de un pom.xml o que especifica el id del repositorio remoto en el que desplegar:grails maven-deploy --repository=myRepo
The
El argumento 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:repository especifica el 'id' para el repositorio. Configure los detalles del repositorio especificado por este 'id' en el archivo grails-app/conf/BuildConfig.groovy o en el archivo $USER_HOME/.grails/settings.groovy: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:
La sintaxis para configurar repositorios remotos coincide con la sintaxis del elemento remoteRepository en las tareas Ant Maven. Por ejemplo, el siguiente XML:<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>
Can be expressed as:
Puede ser expresada como:remoteRepository(id: "myRepo", url: "scp://localhost/www/repository") { authentication username: "...", privateKey: "${userHome}/.ssh/id_dsa" }
By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however to specify a different protocol you can do:
De forma predeterminada el plugin intentará detectar el protocolo a usar desde la URL del repositorio (es decir "http" desde "http://..." etc.), sin embargo para especificar otro protocolo puede hacer:grails maven-deploy --repository=myRepo --protocol=webdav
The available protocols are:
Los protocolos disponibles son:
- http
- scp
- scpexe
- ftp
- webdav
- http
- scp
- scpexe
- ftp
- webdav
Groups, Artifacts and Versions
Maven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from the Grails project conventions or plugin descriptor.Versiones, artefactos y grupos
Maven define la noción de 'IdGrupo', 'artifactId' y 'versión'. Este plugin extrae esta información de los convenciones de proyecto Grails o del descriptor del plugin.Projects
For applications this plugin will use the Grails application name and version provided by Grails when generating thepom.xml file. To change the version you can run the set-version command:Proyectos
Para las aplicaciones de este plugin utilizará el nombre de la aplicación de Grails y la versión proporcionada por Grails al generar el archivopom.xml. Para cambiar la versión puede ejecutar el comando set-version:grails set-version 0.2
The Maven
El groupId will be the same as the project name, unless you specify a different one in Config.groovy:groupId de Maven será el mismo que el nombre del proyecto, a menos que se especifique otro diferente en Config.groovy:grails.project.groupId="com.mycompany"Plugins
With a Grails plugin thegroupId and version are taken from the following properties in the GrailsPlugin.groovy descriptor:Plugins
Con un plugin de Grails elgroupId y version proceden de las siguientes propiedades en el descriptor de GrailsPlugin.groovy:String groupId = 'myOrg' String version = '0.1'
The 'artifactId' is taken from the plugin name. For example if you have a plugin called
El 'artifactId' se toma del nombre del plugin. Por ejemplo, si tienes un plugin llamado FeedsGrailsPlugin the artifactId will be "feeds". If your plugin does not specify a groupId then this defaults to "org.grails.plugins".FeedsGrailsPlugin el artifactId será "feeds". Si tu plugin no especifica el groupId entonces por defecto utiliza "org.grails.plugins".
3.7.10 Dependencias de plugin
As of Grails 1.3 you can declaratively specify plugins as dependencies via the dependency DSL instead of using the install-plugin command:
Como en Grails 1.3 puede especificar los plugins declarandolos como dependencias a través de la dependencia DSL en lugar de utilizar el comando install-plugin:grails.project.dependency.resolution = {
…
repositories {
…
} plugins {
runtime ':hibernate:1.2.1'
} dependencies {
…
}
…
}If you don't specify a group id the default plugin group id of
Si no especifica un id de grupo se utiliza el id de grupo del plugin predeterminado de 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:org.grails.plugins. Se puede especificar el uso de la versión más reciente de un plugin determinado mediante "latest.integration" como el número de versión:plugins {
runtime ':hibernate:latest.integration'
}Integration vs. Release
The "latest.integration" version label will also include resolving snapshot versions. To not include snapshot versions then use the "latest.release" label:Integration vs. Release
La etiqueta de versión "latest.integration" también incluirá resolver versiones snapshot. Para no incluir versiones snapshot utilice la etiqueta "latest.release":plugins {
runtime ':hibernate:latest.release'
}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:
La etiqueta de "latest.release" sólo funciona con repositorios compatibles con Maven. Si tienes un repositorio basado en SVN Grails debe utilizar "latest.integration".Y por supuesto si utiliza un repositorio Maven con un id de grupo alternativo puede especificar un id de grupo:
plugins {
runtime 'mycompany:hibernate:latest.integration'
}Plugin Exclusions
You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:Exclusiones de plugin
Puede controlar cómo los plugins resuelven transitoriamente tanto las dependencias de plugin como de JAR usando las exclusiones. Por ejemplo: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
Aquà hemos definido una dependencia en el plugin "weceem" que transitoriamente depende el plugin "searchable". Mediante el uso del método 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:excludes puede decirle a Grails que NO resuelva transitoriamente el plugin para búsquedas. Puede combinar esta técnica para especificar una versión alternativa de un plugin:plugins {
runtime(':weceem:0.8') {
excludes "searchable" // excludes most recent version
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolved:
Puede deshabilitar también completamente la instalación transitiva de plugins, en cuyo caso se resolverán las dependencias no transitivas:plugins {
runtime(':weceem:0.8') {
transitive = false
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}4 La lÃnea de comando
Grails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant.However, Grails takes it further through the use of convention and the
El sistema de comandos de Grails está construido sobre Gant, un envoltorio simple de Apache Ant.Sin embargo, Grails lleva un paso más alla el uso de la convención y del comando grails command. When you type:
grails. Cuando introduces:grails [command name]
Grails searches in the following directories for Gant scripts to execute:
Grails busca en los siguientes directorios scripts de Gant para ejecutar:
USER_HOME/.grails/scriptsPROJECT_HOME/scriptsPROJECT_HOME/plugins/*/scriptsGRAILS_HOME/scripts
Grails will also convert command names that are in lower case form such as run-app into camel case. So typing
Grails convertirá también los nombres de los comandos que están en minúsculas tales como run-app en "camel case", asà que introducir:grails run-app
Results in a search for the following files:
Produce una busqueda de los siguientes ficheros:
USER_HOME/.grails/scripts/RunApp.groovyPROJECT_HOME/scripts/RunApp.groovyPLUGINS_HOME/*/scripts/RunApp.groovyGLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovyGRAILS_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:
Si coincide con varios Grails le dejará elegir cúal se ejecuta.Cuando Grails ejecuta un script de Gant, invoca el target por defecto en es script. Si no hay target por defecto, Grails dejará de ejecutarse y dará un error.grails help
which outputs usage instructions and the list of commands Grails is aware of:
devuelve como salida instrucciones de uso y una lista de los comandos de Grails:Usage (optionals marked with *):
grails [environment]* [target] [arguments]*Examples:
grails dev run-app
grails create-app booksAvailable 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
Consulte la referencia de lÃnea de comandos en el menú de referencia rápida de la guÃa de referencia para obtener más información sobre cada uno de los comandos.
It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with
A menudo es útil proporcionar argumentos a la JVM cuando se ejecutan comandos de Grails, en particular con 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:
run-app donde se puede, por ejemplo, establecer un tamaño máximo más alto al "heap". El comando Grails utilizará todas las opciones JVM proporcionadas en la variable de entorno JAVA_OPTS, pero también se puede especificar una variable de entorno especÃfica de Grails también:export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m"
grails run-appnon-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:
Modo no interactivo
Cuando se ejecuta un script manualmente, y se solicita información, se puede responder a las preguntas y continuar la ejecución del script. Pero cuando se ejecuta un script como parte de un proceso automatizado, por ejemplo, un servidor de integración continua, no hay manera de responder a las preguntas. Por lo que puede pasar el parámetro--non-interactive al script para decirle a Grails que acepte la respuesta por defecto para cualquier pregunta, por ejemplo, si se instala un plugin que falta.Por ejemplo:grails war --non-interactive
4.1 Modo interactivo
Interactive mode is the a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:
If you need to open a file whilst within interactive mode you can use the
TAB completion also works for class names after the
If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:
El modo interactivo es una caracterÃstica de la lÃnea de comandos Grails que mantiene la JVM funcionando y permite ejecutar comandos más rápidamente. Para activar el modo interactivo escriba "grails" en la lÃnea de comandos y después use el tabulador para obtener una lista de comandos:
If you need to open a file whilst within interactive mode you can use the open command which will TAB complete file paths:
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 !:
Si necesita abrir un archivo cuando esté en modo interactivo se puede utilizar el comando open usando el tabulador para completar las rutas de archivos:
El tabulador también funciona para las clases después del comando create-* :
Si necesita ejecutar un proceso externo, cuando esté en el modo interactivo, puede hacerlo a partir del comando con un !
4.2 Crear Scripts de Gant
You can create your own Gant scripts by running the create-script command from the root of your project. For example the following command:Will create a script called
Puede crear sus propios scripts de Gant mediante la ejecución del comando create-script en la raÃz de su proyecto. Por ejemplo, el siguiente comando:grails create-script compile-sources
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") }
grails create-script compile-sources
scripts/CompileSources.groovy. Un script de Gant es muy similar a un script normal de Groovy, excepto que soporta el concepto de "targets" y las dependencias entre ellos: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
Como se demuestra en la secuencia anterior, hay una variable implÃcita ant variable (an instance of groovy.util.AntBuilder) that allows access to the Apache Ant API.
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.
ant (una instancia de groovy.util.AntBuilder) que permite el acceso a la Apache Ant API.
En las versiones anteriores de Grails (1.0.3 y anteriores), la variable era Ant, es decir, con una letra mayúscula en primer lugar.
También puede "depender" de otros targets utilizando el método depends mostrado en el valor default del target anterior.The default target
In the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use thesetDefaultTarget() method:
El target predeterminado
En el ejemplo anterior, se especifica un target con el nombre explÃcito "default". Esta es una manera de definir el target predeterminado para un script. Un enfoque alternativo es el uso del métodosetDefaultTarget():target("clean-compile": "Performs a clean compilation on the app source") { depends(clean, compile) }target(clean:"Clean out things") { ant.delete(dir:"output") }target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }setDefaultTarget("clean-compile")
This lets you call the default target directly from other scripts if you wish. Also, although we have put the call to
Esto permite llamar al target predeterminado directamente desde otros scripts si asà lo desea. Además, aunque hemos puesto la llamada a 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.
setDefaultTarget() al final de la secuencia de comandos en este ejemplo, puede ir en cualquier lugar, siempre y cuando esté después del objetivo que se refiere ("clean-compile" en este caso).¿Qué enfoque es mejor? En realidad puede utilizar lo que prefiera, no parece haber ninguna ventaja importante en cualquier caso. Una cosa que dirÃa es que si desea permitir que otros scripts llamen a su target por defecto, debe moverse en un script compartido que no tiene un target predeterminado. Hablaremos un poco más sobre esto en la siguiente sección.
4.3 Reusar scripts de Grails
Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands). Of particular use are the compile, package and bootstrap scripts.The bootstrap script for example lets you bootstrap a Spring ApplicationContext instance to get access to the data source and so on (the integration tests use this):
Grails tiene un montón de funcionalidades de serie mediante la lÃnea de comandos que pueden resultar útiles en sus propios scripts (consulte la referencia de la lÃnea de comandos en la GuÃa de referencia para la información sobre todos los comandos). Particularmente útiles son los scripts compile, package y bootstrap.El script bootstrap por ejemplo le permite iniciar una instancia del Contexto de aplicación de Spring para obtener acceso al origen de datos y asà sucesivamente (las pruebas de integración utilizan esto):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() } }
Pulling in targets from other scripts
Gant lets you pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is theincludeTargets property. Simply "append" a file or class to it using the left-shift operator:
includeTargets << new File("/path/to/my/script.groovy") includeTargets << gant.tools.Ivy
Usando targets de otros scripts
Gant permite usar todos los targets (excepto el "default") de otro script de Gant. Luego puede depender de o invocar esos targets como si se hubieran definido en el propio script. El mecanismo para hacerlo es el de la propiedadincludeTargets. Simplemente anexe un fichero o una clase a él utilizando el operador de desplazamiento a la izquierda:
includeTargets << File("/path/to/my/script.groovy") nueva
includeTargets << gant.tools.IvyCore Grails targets
As you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax forincludeTargets when including core Grails targets. Instead, you should use the special grailsScript() method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).The syntax for the grailsScript() method is pretty straightforward: simply pass it the name of the Grails script to include, without any path information. Here is a list of Grails scripts that you could reuse:Principales targets de Grails
Como se ha visto en el ejemplo al principio de esta sección, no se utiliza el fichero ni la sintaxis de clases paraincludeTargets cuando se incluyen targets principales de Grails. En su lugar, debe utilizar el método especial grailsScript() proporcionado por el lanzdor del comando Grails (tenga en cuenta que esto no está disponible en scripts de Gant normales, sólo en los de Grails).La sintaxis del método grailsScript() es bastante sencilla: simplemente pas el nombre del script de Grails que se debe incluir, sin ninguna información de ruta de acceso. Aquà hay una lista de los scripts de Grails que podrÃa volver a utilizar:| Script | Description |
|---|---|
| _GrailsSettings | 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. |
| _GrailsEvents | Include this to fire events. Adds an event(String eventName, List args) method. Again, included by almost all other Grails scripts. |
| _GrailsClasspath | 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. |
| _GrailsProxy | If you don't have direct access to the internet and use a proxy, include this script to configure access through your proxy. |
| _GrailsArgParsing | Provides a parseArguments target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the argsMap property. |
| _GrailsTest | Contains all the shared test code. Useful if you want to add any extra tests. |
| _GrailsRun | Provides all you need to run the application in the configured servlet container, either normally (runApp/runAppHttps) or from a WAR file (runWar/runWarHttps). |
Script architecture
| Script | Descripción |
|---|---|
| _GrailsSettings | ¡Realmente deberÃa usar esto! Afortunadamente, se usa automáticamente por todos los scripts de Grails excepto _GrailsProxy, por lo que normalmente no tiene que usarlo explÃcitamente. |
| _GrailsEvents | Use esto para desencadenar eventos. Agrega un método event(String eventName, List args). Una vez más, usada por casi todos los otros scripts de Grails. |
| _GrailsClasspath | Configura el classpath de la compilación, pruebas y tiempo de ejecución. Si desea usarlos o jugar con ellos, use este script. Una vez más, usado por casi todos los otros scripts de Grails. |
| _GrailsProxy | Si no tiene acceso directo a internet y utilizar a un proxy, use esta secuencia de comandos para configurar el acceso a través de proxy. |
| _GrailsArgParsing | Proporciona un target parseArguments que analiza los argumentos proporcionados por el usuario cuando ejecuta el script. Agrega a la propiedad argsMap. |
| _GrailsTest | Contiene todo el código compartido de prueba. Es útil si desea agregar cualquier prueba adicional. |
| _GrailsRun | Ofrece todo que lo necesario para ejecutar la aplicación en el contenedor de servlet configurado, ya sea normalmente (runApp/runAppHttps) o desde un fichero WAR (runWar/runWarHttps). |
Arquitectura un script
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:
Tal vez está pensando en lo que están haciendo esos caracteres de subrayado en los nombres de los scripts de Grails. Es la forma de Grails de determinar que una secuencia de comandos es interna , o en otras palabras que tiene "comando" correspondiente. Por lo que no se puede ejecutar "grails _grails-settings" por ejemplo. También es por esto qué no tienen un target predeterminado.Los scripts internos son todo para compartir código y reutilizarlo. De hecho, se recomienda adoptar un enfoque similar en sus propios scripts: poner todos sus targets en un script interno que puede ser fácilmente compartido y proporcionar script simples que analizen cualquier argumentos y deleguen en los targets de los scripts internos. Por ejemplo si tiene una secuencia de comandos que ejecuta algunas pruebas funcionales, se puede dividir asÃ:./scripts/FunctionalTests.groovy:includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) }./scripts/_FunctionalTests.groovy:includeTargets << grailsScript("_GrailsTest")target(runFunctionalTests: "Run functional tests.") { depends(...) … }
Here are a few general guidelines on writing scripts:
Aquà hay unas directrices generales sobre cómo escribir scripts:
- Split scripts into a "command" script and an internal one.
- Put the bulk of the implementation in the internal script.
- Put argument parsing into the "command" script.
- To pass arguments to a target, create some script variables and initialise them before calling the target.
- Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.
- Dividir los scripts un script de "comando" y uno interno.
- Poner la mayor parte de la implementación en la secuencia de comandos interno.
- Poner el análisis de los parámetros en el script de "comando".
- Para pasar argumentos a un target, crear algunas variables de script e inicializarlas antes de llamar al target.
- Evitar colisiones de nombres utilizando closures asignadas a las variables del script en lugar de targets. Asà puede pasar argumentos directamente a las closures.
4.4 Interceptando Eventos
Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.
Grails proporciona la capacidad de interceptar eventos de scripts. Estos eventos son activados durante la ejecución de scripts de Grails y plugins.El mecanismo es deliberadamente simple y vagamente especificado. La lista de posibles eventos no es fija en modo alguno, por lo que es posible enlazar eventos activados por los scripts de plugin, para los que no hay evento equivalente en los scripts del núcleo.Defining event handlers
Event handlers are defined in scripts called_Events.groovy. Grails searches for these scripts in the following locations:
USER_HOME/.grails/scripts- user-specific event handlersPROJECT_HOME/scripts- applicaton-specific event handlersPLUGINS_HOME/*/scripts- plugin-specific event handlersGLOBAL_PLUGINS_HOME/*/scripts- event handlers provided by global plugins
Definición de manejadores de eventos
Los controladores de eventos se definen en un scripts llamado_Events.groovy. Grails busca estos scripts en las siguientes ubicaciones:
USER_HOME/.grails/scripts- manejadores de eventos especÃficos del usuario.PROJECT_HOME/scripts- manejadores de eventos especÃficos de la aplicación.PLUGINS_HOME / * / scripts- manejadores de eventos especÃficos de plugin.GLOBAL_PLUGINS_HOME / * / scripts- manejadores de eventos proporcionados por plugins globales.
Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant
Cuando se desencadena un evento, se ejecutan todos los manejadores registrados para ese evento. Tenga en cuenta que el registro de controladores se realiza automáticamente por Grails, por lo que sólo es necesario declararlos en el archivo _Events.groovy file.Event handlers are blocks defined in _Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}_Events.groovy pertinente.Los manejadores de eventos son bloques definidos en _Events.groovy, con un nombre que empieza con "event". En el ejemplo siguiente se puede colocar en el directorio/scripts para demostrar esta caracterÃstica:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}You can see here the three handlers
Aquà puede ver tres controladores 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:
CompileStart- Called when compilation starts, passing the kind of compile - source or testsCompileEnd- 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:eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails proporciona algunos eventos estándar, que se describen en la GuÃa de referencia de lÃnea de comandos. Por ejemplo, el comando compile dispara los siguientes eventos:
CompileStart- llamado cuando se inicia la compilación, pasando el tipo de compilación - código fuente o pruebasCompileEnd- llamada una vez finalizada la compilación, pasando el tipo de compilación - código fuente o pruebas
Activación de eventos
Para desencadenar un evento simplemente debe incluir la secuencia de comandos Init.groovy y llamar a la closure event():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:includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Eventos habituales
A continuación es una tabla de algunos de los eventos habituales que se pueden utilizar:| Event | Parameters | Description |
|---|---|---|
| StatusUpdate | message | Passed a string indicating current script status/progress |
| StatusError | message | Passed a string indicating an error message from the current script |
| StatusFinal | message | 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 |
| CreatedArtefact | artefactType,artefactName | Called when a create-xxxx script has completed and created an artefact |
| CreatedFile | fileName | Called whenever a project source filed is created, not including files constantly managed by Grails |
| Exiting | returnCode | Called when the scripting environment is about to exit cleanly |
| PluginInstalled | pluginName | Called after a plugin has been installed |
| CompileStart | kind | Called when compilation starts, passing the kind of compile - source or tests |
| CompileEnd | kind | Called when compilation is finished, passing the kind of compile - source or tests |
| DocStart | kind | Called when documentation generation is about to start - javadoc or groovydoc |
| DocEnd | kind | Called when documentation generation has ended - javadoc or groovydoc |
| SetClasspath | rootLoader | 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. |
| PackagingEnd | none | Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated) |
| Evento | Parámetros | Descripción |
|---|---|---|
| StatusUpdate | mensaje | Pasa una cadena que indica el Estado y progreso de script actual. |
| StatusError | mensaje | Pasa una cadena que indica un mensaje de error en el script actual. |
| StatusFinal | mensaje | Pasa una cadena que indica el mensaje de estado final del script, es decir, al completar un target, incluso no cierra el entorno de script. |
| CreatedArtefact | artefactType, artefactName | Se llama cuando un script create-xxxx ha terminado y ha creado un artefacto |
| CreatedFile | nombre de archivo | Llamada siempre que se crea un fichero en el proyecto, sin incluir los archivos administrado por Grails. |
| Exiting | returnCode | Se llama cuando el entorno de script está a punto de cerrarse. |
| PluginInstalled | Nombre de Plugin | Se llama después de que se ha instalado un plugin. |
| CompileStart | tipo | Se llama cuando comienza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| CompileEnd | tipo | Se llama cuando finaliza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| DocStart | tipo | Se llama cuando la generación de documentación está a punto de empezar - javadoc o groovydoc |
| DocEnd | tipo | Se llama cuando se ha finalizado la generación de documentación - javadoc o groovydoc |
| SetClasspath | rootLoader | Llamado durante la inicialización del classpath para que los plugins pueda insertar entradas en el classpath con rootLoader.addURL(...). Dese cuenta de que esto inserta nuevas rutas después de que los scripts se cargen por lo que no se puede utilizar esto para cargar una clase su script de eventos necesita, aunque se puede hacer esto si carga la clase por su nombre. |
| PackagingEnd | ninguno | Llamado al final del empaquetamiento (que se llama antes de arrancar el servidor Tomcat y después de generar el web.xml) |
4.5 Personalizar la construcción
Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you can't configure it. In this section, we look at how you can influence and modify the standard Grails build.
Grails es definitivamente un framework opinionado y prefiere la convención sobre la configuración, pero esto no significa que no se pueda configurar. En esta sección, veremos cómo puede influir y modificar el la construcción estándar de Grails.The defaults
The core of the Grails build configuration is thegrails.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:
| Property | Config option | Default value |
|---|---|---|
| grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
| projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
| classesDir | grails.project.class.dir | <projectWorkDir>/classes |
| testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
| testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
| resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
| projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
| globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
| verboseCompile | grails.project.compile.verbose | false |
Los valores predeterminados
El núcleo de la configuración de la construcción de Grails es la clasegrails.util.BuildSettings, que contiene bastante información útil. Controla donde se guardan las clases se compiladas, que dependencias tiene la aplicación, y otros ajustes como estos.He aquà una selección de las opciones de configuración y sus valores predeterminados:
| Propiedad | Opción de configuración | Valor por defecto |
|---|---|---|
| grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
| projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
| classesDir | grails.project.class.dir | <projectWorkDir>/classes |
| testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
| testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
| resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
| projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
| globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
| verboseCompile | grails.project.compile.verbose | false |
The
La clase BuildSettings class has some other properties too, but they should be treated as read-only:
| Property | Description |
|---|---|
| baseDir | The location of the project. |
| userHome | The user's home directory. |
| grailsHome | The location of the Grails installation in use (may be null). |
| grailsVersion | The version of Grails being used by the project. |
| grailsEnv | 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. |
BuildSettings también tiene algunas otras propiedades, pero deben ser tratados como de sólo lectura:
| Propiedad | Descripción |
|---|---|
| baseDir | La ubicación del proyecto. |
| userHome | Directorio principal del usuario. |
| grailsHome | La ubicación de la instalación de Grails en uso (puede ser null). |
| grailsVersion | La versión de Grails utilizada por el proyecto. |
| grailsEnv | El entorno actual de Grails. |
| compileDependencies | Una lista de dependencias del proyecto en tiempo de compilación como instancias de File. |
| testDependencies | Una lista de dependencias del proyecto en tiempo de pruebas como instancias de File. |
| runtimeDependencies | Una lista de dependencias del proyecto en tiempo de ejecución como instancias de File. |
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
Por supuesto, estas propiedades no sirven para nada si no se puede conseguir accceso a ellas. Afortunadamente eso es fácil de hacer: una instancia de 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.Overriding the defaults
All of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command:grails -Dgrails.project.work.dir=work compile
BuildSettings está disponible para tus scripts como la variable grailsSettings. También se puede acceder desde el código mediante el uso de la clase grails.util.BuildSettingsHolder, pero esto no es recomendable.Sobreescribiendo los valores predeterminados
Todas las propiedades de la primera tabla se pueden sobreescribir por una propiedad del sistema o una opción de configuración, simplemente usar el nombre de "opción de configuración". Por ejemplo, para cambiar el directorio de trabajo del proyecto, podrÃa ejecutar este comando:grails -Dgrails.project.work.dir=work compile
or add this option to your
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
o añadir esta opción al archivo grails-app/conf/BuildConfig.groovy file:
grails.project.work.dir = "work"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.grails-app/conf/BuildConfig.groovy:
grails.project.work.dir = "work"BuildConfig.groovy, que a su vez tiene prioridad sobre los valores predeterminados.El archivo BuildConfig.groovy es un hermano de grails-app/conf/Config.groovy: la primera contiene opciones que sólo afectan a la construcción, mientras que el segundo contiene opciones que afectan a la aplicación en tiempo de ejecución. No se limita sólo a las opciones de la primera tabla: encontrará las opciones de configuración de generación en esta documentación, como las necesarias para especificar el puerto que se ejecuta el contenedor de servlet embebido o para determinar qué archivos se empaquetan en el archivo WAR.Available build settings
| Name | Description |
|---|---|
| grails.server.port.http | Port to run the embedded servlet container on ("run-app" and "run-war"). Integer. |
| grails.server.port.https | Port to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer. |
| grails.config.base.webXml | Path to a custom web.xml file to use for the application (alternative to using the web.xml template). |
| grails.compiler.dependencies | Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be 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. |
| grails.testing.nameSuffix | 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". |
| grails.project.war.file | A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war". |
| grails.war.dependencies | A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory. |
| grails.war.copyToWebApp | 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". |
| grails.war.resources | 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. |
| grails.project.web.xml | The location to generate Grails' web.xml to |
Configuración de construcción disponible
| Nombre | Descripción |
|---|---|
| grails.Server.Port.http | Puerto para ejecutar el contenedor de servlet embebido ("run-app" y "run-war"). Entero. |
| grails.Server.Port.https | Puerto para ejecutar el contenedor de servlet embebido bajo HTTPS ("run-app --https" y "run war --https"). Entero. |
| grails.config.base.webXml | Ruta del archivo web.xml personalizada para utilizar para la aplicación (alternativa al uso de la plantilla de web.xml). |
| grails.compiler.dependencies | Enfoque heredado para agregar dependencias adicionales a los classpath del compilador. Establézcalo en una closure que contenga las entradas "fileset()". Estas entradas serán procesadas por un AntBuilder por lo que la sintaxis es la forma Groovy de los correspondientes elementos XML en un fichero de construcción Ant, por ejemplo, fileset(dir: "$basedir/lib", include: "**/*.class). |
| grails.testing.Patterns | Una lista de patrones de rutas Ant que le permiten controlar qué archivos se incluyen en las pruebas. Los patrones no deben incluir el sufijo de caso de prueba, se establece mediante la propiedad siguiente. |
| grails.testing.nameSuffix | Por defecto, las pruebas se supone que tienen un sufijo de "Tests". Puede cambiarlo a cualquier cosa que le guste asignando esta opción. Por ejemplo, otro sufijo común es "Test". |
| grails.project.war.File | Una cadena que contiene la ruta del archivo WAR generado, junto con su nombre completo (incluye extensión). Por ejemplo, "target/my-app.war". |
| grails.war.dependencies | Una closure que contiene las entradas "fileset()" que permite un control total sobre lo que pasa en el directorio de "WEB-INF/lib" del WAR. |
| grails.war.copyToWebApp | Una closure que contiene las entradas "fileset()" que permite un control total sobre lo que pasa en la raÃz del WAR. Reemplaza el comportamiento predeterminado de incluir todo bajo "web-app". |
| grails.war.resources | Una closure que toma la ubicación del directorio provisional (staging) como primer argumento. Puede utilizar cualquier tarea de Ant para hacer cualquier cosa que le guste. Normalmente se utiliza para eliminar archivos del directorio provisional antes de ese directorio jar se incluya en un WAR. |
| grails.project.web.xML | La ubicación en la que se generará el fichero web.xml. |
4.6 Ant y Maven
If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).
Si todos los proyectos en su equipo o empresa se construyen utilizando una herramienta de construcción como Ant o Maven, se convierte en la oveja negra de la familia cuando utiliza la lÃnea de comandos de Grails para construir su aplicación. Afortunadamente, puede integrar fácilmente el sistema de construcción de Grails en las principales herramientas de construcción en uso hoy en dÃa (bueno, las que están en uso en proyectos de Java por lo menos).Ant Integration
When you create a Grails application with the create-app command, Grails doesn't automatically create an Antbuild.xml file but you can generate one with the integrate-with command:Integración con Ant
Cuando se crea una aplicación Grails con la create-app, Grails no crea automáticamente un archivo Antbuild.xml pero puede generar una con el comando integrate-with:
grails integrate-with --antThis creates a
Esto crea un archivo build.xml file containing the following targets:
clean- Cleans the Grails applicationcompile- Compiles your application's source codetest- Runs the unit testsrun- Equivalent to "grails run-app"war- Creates a WAR filedeploy- Empty by default, but can be used to implement automatic deployment
ant war
build.xml que contiene los siguientes targets:
clean- Limpia la aplicación Grailscompile- Compila el código fuente de su aplicacióntest- Ejecuta las pruebas unitariasrun- Equivalente a "ejecutar grails-app"war- Crea un archivo WARdeploy- Vacio por defecto, pero puede ser usado para implementar el despliegue automático
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:
El fichero de construcción está configurado para utilizar Apache Ivy para la gestión de la dependencias, lo que significa que se descargará automáticamente todos los archivos JAR necesarios y otras dependencias bajo demanda. ¡Ni siquiera tiene que instalar Grails localmente para usarlo! Esto lo hace especialmente útil para los sistemas de integración continua, tales como CruiseControl o Jenkins.Use la tarea Ant de Grails para enlazar con el actual sistema de construcción de Grails. La tarea le permite ejecutar cualquier script Grails que esté disponible, no sólo los utilizados por el fichero de construcción generado. Para utilizar la tarea, primero se debe declarar:<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>
<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:
Esto plantea la pregunta: ¿qué debe estar en "grails.classpath"? La tarea en sà misma está en el artefacto JAR "grails-bootstrap", por lo que tiene que estar en el classpath por lo menos. También debe incluir el "groovy-all" JAR. Con la tarea definida, ¡sólo tiene que usarla! La siguiente tabla muestra los atributos que están disponibles:
| Attribute | Description | Required |
|---|---|---|
| home | The location of the Grails installation directory to use for the build. | Yes, unless classpath is specified. |
| classpathref | Classpath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts". | Yes, unless home is set or you use a classpath element. |
| script | The name of the Grails script to run, e.g. "TestApp". | Yes. |
| args | The arguments to pass to the script, e.g. "-unit -xml". | No. Defaults to "". |
| environment | The Grails environment to run the script in. | No. Defaults to the script default. |
| includeRuntimeClasspath | Advanced setting: adds the application's runtime classpath to the build classpath if true. | No. Defaults to true. |
| Atributo | Descripción | Requerido |
|---|---|---|
| home | La ubicación del directorio de instalación de Grails que se utilizará para la construcción. | SÃ, a menos que se especifique un classpath. |
| classpathref | Classpath para la carga de Grails. Debe incluir el artefacto "grails-bootstrap" y debe incluir "grails-scripts". | SÃ, a menos que home se establezca o se utilice un elemento classpath. |
| script | El nombre del script Grails para ejecutar, por ejemplo, "TestApp". | SÃ. |
| args | Los argumentos que se pasan al script, por ejemplo, "-unit -xml". | No, por defecto "". |
| environment | El entorno de Grails para ejecutar el script in | No, por defecto los valores del script. |
| includeRuntimeClasspath | Configuración avanzada: añade el classpath de la aplicación al classpath de la construcción si es verdadero. | No, por defecto true. |
The task also supports the following nested elements, all of which are standard Ant path structures:
La tarea también es compatible con los siguientes elementos anidados, todos los cuales son estructuras estándar de Ant:
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 inruntimeClasspath.
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.
classpath- El classpath de construcción (se utiliza para cargar los scripts de Gant y Grails).compileClasspath- Classpath utilizados para compilar las clases de la aplicación.runtimeClasspath- Classpath que se utiliza para ejecutar la aplicación y empaquetar el WAR. Por lo general incluye todo lo de @compileClasspath .testClasspath- Classpath utilizado para compilar y ejecutar las pruebas. Por lo general incluye todo lo de @runtimeClasspath.
home y coloca su propias dependencias en el directorio lib, entonces ni siquiera tiene necesidad de utilizar ninguna de ellas. Para un ejemplo de su uso, eche un vistazo al fichero de construcción generado por Ant para nuevas aplicaciones.
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.
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"
Integración con Maven
Grails ofrece una integración con Maven 2 con un plugin de Maven. El actual plugin de Maven reemplaza y se basa en la versión creada por Octo, que hizo un gran trabajo con el original.Preparación
Para utilizar el nuevo plugin, todo lo que necesita es Maven 2 instalado y configurado. Esto se debe a que ¡ya no es necesario instalar Grails por separado para su uso con Maven!La integración de Maven 2 con Grails ha sido diseñado y probado para Maven 2.0.9 y superiores. No funcionará con versiones anteriores.
La configuración por defecto de Maven no proporciona suficiente memoria para ejecutar el entorno de Grails. Le recomendamos agregar la siguiente variable de entorno a su configuración para evitar que los malos rendimientos:export MAVEN_OPTS="-Xmx512m-XX: MaxPermSize = 256"
Creating a Grails Maven Project
To create a Mavenized Grails project simply run the following command:mvn archetype:generate -DarchetypeGroupId=org.grails \
-DarchetypeArtifactId=grails-maven-archetype \
-DarchetypeVersion=1.3.2 \
-DgroupId=example -DartifactId=my-app<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>Creación de un proyecto Grails con Maven
Para crear un proyecto Grails "mavenizado" sólo tiene que ejecutar el siguiente comando:mvn archetype: generate-DarchetypeGroupId org.grails =
-DarchetypeArtifactId = grails-maven-arquetipo
-DarchetypeVersion = 1.3.2
-DgroupId = ejemplo-DartifactId = my-app<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
Then you're ready to create the project structure:
Entonces estás listo para crear la estructura del proyecto:cd my-app mvn initialize
if you see a message similar to this:you need to add the plugins manually to application.properties:Resolving plugin JAR dependencies … :: problems summary :: :::: WARNINGS module not found: org.hibernate#hibernate-core;3.3.1.GAthen runplugins.hibernate=2.0.0 plugins.tomcat=2.0.0and the hibernate and tomcat plugins will be installed.mvn compile
cd mi-app mvn initialize
nullsi usted ve un mensaje similar a este:
Resolving plugin JAR dependencies …
:: problems summary ::
:::: WARNINGS
module not found: org.hibernate#hibernate-core;3.3.1.GAplugins.hibernate = 2.0.0 plugins.tomcat = 2.0.0
mvn compile
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:
Ahora tiene una aplicación Grails lista para funcionar. El plugin se integra en el ciclo estándar de construcción, asà que usted puede utilizar el estándar de las fases de Maven para construir y empaquetar su aplicación: 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:
grails:create-controller- Calls the create-controller commandgrails:create-domain-class- Calls the create-domain-class commandgrails:create-integration-test- Calls the create-integration-test commandgrails:create-pom- Creates a new Maven POM for an existing Grails projectgrails:create-script- Calls the create-script commandgrails:create-service- Calls the create-service commandgrails:create-taglib- Calls the create-tag-lib commandgrails:create-unit-test- Calls the create-unit-test commandgrails:exec- Executes an arbitrary Grails command line scriptgrails:generate-all- Calls the generate-all commandgrails:generate-controller- Calls the generate-controller commandgrails:generate-views- Calls the generate-views commandgrails:install-plugin- Calls the install-plugin commandgrails:install-templates- Calls the install-templates commandgrails:list-plugins- Calls the list-plugins commandgrails:package- Calls the package commandgrails:run-app- Calls the run-app commandgrails:uninstall-plugin- Calls the uninstall-plugin command
mvn grails:help
mvn clean , mvn compile , mvn test , mvn package , mvn install .También puede utilizar algunos de los comandos de Grails que se han creado como goals de Maven:
grails:create-controller- Invoca el comando create-controllergrails:create-domain-class- Invoca el comando create-domain-classgrails:create-integration-test- Invoca el comando create-integration-testgrails:create-pom- Crea un nuevo POM para un proyecto Grails existente.grails:create-script- Invoca el comando create-scriptgrails:create-service- Invoca el comando create-servicegrails:create-taglib- Invoca el comando create-tag-libgrails:create-unit-test- Invoca el comando create-unit-testgrails:exec- Invoca un script de grails.grails:generate-all- ] Invoca el comando generate-allgrails:generate-controller- ] Invoca el comando generate-controllergrails:generate-views- Invoca el comando generate-viewsgrails:install-plugin- Invoca el comando install-plugingrails:install-templates- Invoca el comando install-templatesgrails:list-plugins- Invoca el comando list-pluginsgrails:package- Invoca el comando packagegrails:run-app- Invoca el comando run-appgrails:uninstall-plugin- Invoca el comando uninstall-plugin
mvn grails:helpMavenizing an existing project
Creating a new project is great way to start, but what if you already have one? You don't want to create a new project and then copy the contents of the old one over. The solution is to create a POM for the existing project using this Maven command (substitute the version number with the grails version of your existing project):mvn org.grails:grails-maven-plugin:1.3.2:create-pom -DgroupId=com.mycompany
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.
Mavenizando un proyecto existente
Crear un nuevo proyecto es una buena forma de empezar, pero ¿qué hacer si tenemos un proyecto existente? No queremos crear un nuevo proyecto y luego copiar el contenido del proyecto existente. La solución es crear un POM para el proyecto existente con este comando Maven (sustituya el número de versión con la versión de su proyecto Grails):mvn org.grails: grails-maven-plugin: 1.3.2: create-pom-DgroupId = com.mycompany
mvn package. Tenga en cuenta que se tiene que especificar un ID de grupo al crear el POM.También es posible que desee establecer targets JDK de Java 6, ver arriba.
Adding Grails commands to phases
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>
Agregando comandos Grails a las fases
El POM estándar creado por Grails ya une los comandos Grails con sus fases de construcción correspondientes, por lo que "compile" va en la fase "compile" y "war" va en la fase "package". Sin embargo, esto no ayuda cuando se desea conectar un comando de un plugin con una fase determinada. El ejemplo clásico son la pruebas funcionales. ¿Cómo asegurarse de que las pruebas funcionales (con el plugin que sea) se ejecutan durante la fase "integration-test"?No temas, todo es posible. En este caso, se puede asociar un comando a una fase con un bloque de "execution":<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
Esto también muestra el goal 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
grails:exec, que se puede utilizar para ejecutar cualquier comando de Grails. Basta con pasar el nombre del comando como la propoiedad del sistema command, y, opcionalmente, especificar los argumentos con la propiedad args:mvn grails: exec-Dcommand = a crear webtest-Dargs = Libro
Debugging a Grails Maven Project
Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-appLa depuración de un proyecto Grails Maven
Maven puede ser lanzado en modo de depuración a través del comando "mvnDebug". Para iniciar su aplicación Grails en depuración, sólo tiene que ejecutar:mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-appRaising issues
If you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of GRAILS-3547.Notificando problemas
Si te encuentras con algún problema con la integración Maven, por favor, da de alta un asunto en JIRA como una sub-tarea de Grails-3547.5 Mapeo Objeto-relacional (GORM)
Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many.
Las clases de dominio son fundamentales para cualquier aplicación de negocios. Representan el estado de los procesos del negocio y es de esperar que también implementen el comportamiento. Están vinculadas entre si mediante relaciones: uno-a-uno, uno-a-varios o varios-a-varios.
GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.
GORM es la implementación del mapeo objeto-relacional (ORM por sus siglas en ingles) de Grails. Internamente se utiliza Hibernate 3 (una solución ORM de código abierto muy popular y flexible) que gracias a la naturaleza dinámica de Groovy con su tipado estático y dinámico, además de la convención empleada por Grails, requiere un mÃnimo de configuración en la creación de las clases de dominio de Grails.
You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:
También es posible escribir las clases de dominio de Grails utilizando Java. Consulte la sección sobre Integración con Hibernate para mas información acerca de como escribir las clases en Java sin perder los métodos dinámicos de persistencia. A continuación un ejemplo de GORM en acción:def book = Book.findByTitle("Groovy in Action")book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()
5.1 GuÃa de inicio rápido
A domain class can be created with the create-domain-class command:
Una clase de dominio puede ser creada con el comando create-domain-class:grails create-domain-class helloworld.Person
If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name.Si el paquete no se especifica con el script create-domain-class, Grails automáticamente utilizara el nombre de la aplicación como nombre del paquete.
This will create a class at the location
Esto creara una clase como la siguiente en la ubicación grails-app/domain/helloworld/Person.groovy such as the one below:
grails-app/domain/helloworld/Person.groovy:package helloworldclass Person {
}If you have theSi la propiedaddbCreateproperty set to "update", "create" or "create-drop" on your DataSource, Grails will automatically generate/modify the database tables for you.dbCreate, se establece a "update", "create" o "create-drop" en el origen de datos, Grails generara/modificara automáticamente las tablas de la base de datos por usted.
You can customize the class by adding properties:
Usted puede personalizar la clase añadiendo propiedades:class Person {
String name
Integer age
Date lastVisit
}grails console
This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext, GORM, etc.
Este comando cargara una GUI interactiva donde podrá ejecutar comandos Groovy y con acceso al ApplicationContext de Spring, GORM, etc.
5.1.1 CRUD Básico
Try performing some basic CRUD (Create/Read/Update/Delete) operations.
Pruebe realizando algunas operaciones CRUD (Create/Read/Update/Delete por sus siglas en ingles) básicas.Create
Crear
To create a domain class use Map constructor to set its properties and call save:
Para crear una clase de dominio utilice un constructor Mapa para establecer sus propiedades y llame 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.
El método save persistirá la clase a la base de datos utilizando la capa ORM subyacente de Hibernate.Read
Leer
Grails transparently adds an implicit
De forma transparente, Grails añade a la clase de dominio la propiedad implÃcita id property to your domain class which you can use for retrieval:
id que puede utilizarse para su recuperación:def p = Person.get(1) assert 1 == p.id
This uses the get method that expects a database identifier to read the
En este ejemplo se utiliza el método get que espera un identificador para leer el objeto Person object back from the database.
You can also load an object in a read-only state by using the read method:
Person desde la base de datos. Para cargar un objeto en estado de sólo-lectura utilice el método read: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.
En este caso el motor subyacente de Hibernate no hará ningún "dirty checking" y el objeto no sera persistido. Si usted de manera explicita llama al método save entonces el estado del objeto se modificara a lectura-escritura.
In addition, you can also load a proxy for an instance by using the load method:
Adicionalmente puede utilizar el método load para cargar un proxy para una instancia: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.
El uso de este método no incurre en acceso a la base de datos hasta que un método distinto a getId () es llamado, entonces Hibernate inicializara la instancia del proxy, o se producirá una excepción si no encuentra un registro con el id especificado.Update
Actualizar
To update an instance, change some properties and then call save again:
Para actualizar una instancia, modifique algunas propiedades y entonces llame save nuevamente:def p = Person.get(1)
p.name = "Bob"
p.save()Delete
Eliminar
To delete an instance use the delete method:
Para eliminar una instancia utilice el método delete:def p = Person.get(1) p.delete()
5.2 Modelado del dominio en GORM
When building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an Amazon-style bookstore you would be thinking about books, authors, customers and publishers to name a few.
Al crear aplicaciones Grails usted tiene que considerar el dominio del problema que está tratando de resolver. Por ejemplo, si estuviera construyendo una librerÃa al estilo de Amazon estarÃa pensando en libros, autores, clientes y editores solo por nombrar algunos.
These are modeled in GORM as Groovy classes, so a
Estos se modelan en GORM como clases Groovy, por lo que una clase Book class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.
Book puede tener un tÃtulo, una fecha de publicación, un número de ISBN y asà sucesivamente. Las siguientes secciones muestran cómo modelar el dominio en GORM.
To create a domain class you run the create-domain-class command as follows:
Para crear una clase de dominio ejecute el comando create-domain-class de la siguiente manera:grails create-domain-class org.bookstore.Book
The result will be a class at
El resultado será una clase en grails-app/domain/org/bookstore/Book.groovy:
grails-app/domain/org/bookstore/Book.groovy:package org.bookstoreclass Book {
}
This class will map automatically to a table in the database called
A esta clase se corresponde automáticamente una tabla en la base de datos llamada book (the same name as the class). This behaviour is customizable through the ORM Domain Specific Language
book (el mismo nombre que la clase). Este comportamiento puede modificarse a través del Lenguaje especÃfico del dominio (DSL por sus siglas en ingles) ORM
Now that you have a domain class you can define its properties as Java types. For example:
Ahora que tiene una clase de dominio usted puede definir sus propiedades como tipos de Java. Por ejemplo:package org.bookstoreclass 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
A cada propiedad se asigna una columna en la base de datos, la convención para nombrar las columnas es utilizar letras minúsculas separadas por guiones bajos. Por ejemplo 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.
releaseDate se asigna a una columna release_date. Los tipos de SQL se detectan de forma automática a partir de los tipos de Java, pero pueden ser modificados mediante el uso de Constraints o el ORM DSL.
5.2.1 Asociación en GORM
Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.
Las relaciones definen cómo interactúan entre sà las clases de dominio. A menos que de forma explÃcita se especifique en ambos lados, una relación existe solo en la dirección que es definida.
5.2.1.1 Varios-a-uno y uno-a-uno
A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain class. Consider this example:
Una relación de varios-a-uno es el tipo más simple, se define mediante una propiedad del tipo de otra clase de dominio. Considere este ejemplo:Example A
Ejemplo A
class Face {
Nose nose
}class Nose {
}
In this case we have a unidirectional many-to-one relationship from
En este caso tenemos una relación unidireccional varios-a-uno desde Face to Nose. To make this relationship bidirectional define the other side as follows:
Face hacia Nose. Para hacer esta relación bidireccional, es necesario definir el otro lado de la siguiente manera:Example B
Ejemplo B
class Face {
Nose nose
}class Nose {
static belongsTo = [face:Face]
}
In this case we use the
En este caso establecemos mediante 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:
belongsTo que Nose pertenece a Face. Como resultado de esto podemos crear Face, agregar una instancia de Nose y cuando guardemos o eliminemos la instancia de Face, GORM guardara o eliminara Nose. En otras palabras, la actualización y eliminación se realizaran en cascada desde Face hacia 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
En el ejemplo anterior ambos, face y nose serán guardados. Esto no funcionara de modo inverso y el resultado seria un error debido a un Face:
Face que es transitorio.new Nose(face:new Face()).save() // will cause an error
new Nose(face:new Face()).save() // Esto causara un error
Now if we delete the
Si borramos la instancia Face instance, the Nose will go too:
Face, Nose también sera eliminada:def f = Face.get(1) f.delete() // both Face and Nose deleted
def f = Face.get(1) f.delete() // Ambos Face y Nose serán eliminados
To make the relationship a true one-to-one, use the
Para hacer que la relación sea verdaderamente uno-a-uno, utilice la propiedad hasOne property on the owning side, e.g. Face:
hasOne en el lado que define la posesión, por ejemplo, Face:Example C
Ejemplo C
class Face {
static hasOne = [nose:Nose]
}class Nose {
Face face
}
Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the
Tenga en cuenta que al hacer uso de esta propiedad, la clave externa sera colocada en la tabla opuesta al ejemplo anterior, por lo que en este caso la columna de clave externa se almacena en la tabla nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships.
nose en una columna llamada face_id. Además, hasOne sólo funciona en las relaciones bidireccionales.
Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:
Por último, es conveniente añadir una restricción de unicidad en un lado de la relación uno-a-uno:class Face {
static hasOne = [nose:Nose] static constraints = {
nose unique: true
}
}class Nose {
Face face
}5.2.1.2 Uno-a-varios
A one-to-many relationship is when one class, example
Una relación uno-a-varios es cuando una clase, por ejemplo Author, has many instances of a another class, example Book. With Grails you define such a relationship with the hasMany setting:
Author, tiene varias instancias de otra clase, por ejemplo Book. En Grails se establece este tipo de relación utilizando hasMany:class Author {
static hasMany = [books: Book] String name
}class Book {
String title
}
In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
En este caso tenemos una relación unidireccional uno-a-varios. De manera predeterminada, Grails mapeara este tipo de relación mediante una tabla de unión.The ORM DSL allows mapping unidirectional relationships using a foreign key association insteadEl DSL ORM permite mapear relaciones unidireccionales mediante el uso de una clave externa.
Grails will automatically inject a property of type
Grails inyectara automáticamente una propiedad de tipo java.util.Set into the domain class based on the hasMany setting. This can be used to iterate over the collection:
java.util.Set en la clase de dominio basándose en hasMany. Esta propiedad puede ser usada para iterar sobre la colección: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.De manera predeterminada Grails utilizara una estrategia de recuperación "lazy", lo que significa que la colección sera inicializada hasta que se accede por primera vez. Esto puede provocar que se incurra en el problema n+1 si usted no es cuidadoso. Si necesita recuperación "eager" puede utilizar el DSL ORM o puede especificar la recuperación "eager" como parte de una consulta
The default cascading behaviour is to cascade saves and updates, but not deletes unless a
El comportamiento predeterminado de la cascada es guardar y actualizar, pero no eliminar a menos que también se especifique belongsTo is also specified:
belongsTo:class Author {
static hasMany = [books: Book] String name
}class Book {
static belongsTo = [author: Author]
String title
}
If you have two properties of the same type on the many side of a one-to-many you have to use
Si usted tiene dos propiedades del mismo tipo en el lado varios de uno-a-varios, deberá utilizar mappedBy to specify which the collection is mapped:
mappedBy para especificar la colección a mapear:class Airport {
static hasMany = [flights: Flight]
static mappedBy = [flights: "departureAirport"]
}class Flight {
Airport departureAirport
Airport destinationAirport
}
This is also true if you have multiple collections that map to different properties on the many side:
Esto también sera válido si tiene varias colecciones que mapean a diferentes propiedades en el lado varios:class Airport {
static hasMany = [outboundFlights: Flight, inboundFlights: Flight]
static mappedBy = [outboundFlights: "departureAirport",
inboundFlights: "destinationAirport"]
}class Flight {
Airport departureAirport
Airport destinationAirport
}5.2.1.3 Varios-a-varios
Grails supports many-to-many relationships by defining a
Grails tiene soporte para relaciones varios-a-varios mediante la inclusión de hasMany on both sides of the relationship and having a belongsTo on the owned side of the relationship:
hasMany en ambos lados de la relación y del lado que expresa ser la propiedad se incluye belongsTo:class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}class Author {
static hasMany = [books:Book]
String name
}
Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case
A nivel de la base de datos Grails mapea una relación varios-a-varios mediante una tabla de unión. El lado propietario de la relación, en este caso Author, takes responsibility for persisting the relationship and is the only side that can cascade saves across.
Author, asume la responsabilidad de la persistencia de la relación y es el único que puede propagar la actualización.
For example this will work and cascade saves:
Por ejemplo, esto propagarÃa la creación de manera correcta:new Author(name:"Stephen King") .addToBooks(new Book(title:"The Stand")) .addToBooks(new Book(title:"The Shining")) .save()
However this will only save the
Sin embargo, esto sólo guardarÃa a Book and not the authors!
Book y no a los autores!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.
Este es el comportamiento esperado, al igual que en Hibernate, sólo un lado de la relación varios-a-varios puede asumir la responsabilidad de la gestión.Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourselfActualmente el Scaffolding de Grails no es compatible con relaciones del tipo varios-a-varios, y por lo tanto, usted deberá escribir el código para manejar este tipo de relación.
5.2.1.4 Colecciones de tipos básicos
As well as associations between different domain classes, GORM also supports mapping of basic collection types.
For example, the following class creates a
Al igual que con las asociaciones entre diferentes tipos de clases de dominio, GORM también es compatible con el mapeo de colecciones de tipos básicos. Por ejemplo, la clase siguiente, crea una asociación de nicknames association that is a Set of String instances:
nicknames que es un Set de instancias String:class Person {
static hasMany = [nicknames: String]
}
GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the
GORM mapeara esta asociación utilizando una tabla de unión. Usted puede modificar varios aspectos del mapeo de la tabla de unión mediante el argumento joinTable argument:
joinTable: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:
Al ejemplo anterior corresponderá una tabla como la siguiente:
bunch_o_nicknames Table
Tabla bunch_o_nicknames
--------------------------------------------- | person_id | nickname | --------------------------------------------- | 1 | Fred | ---------------------------------------------
5.2.2 Composición en GORM
As well as association, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:
Además de la asociación, Grails también tiene soporte para la composición. En este caso, en lugar de mapear las clases en tablas separadas una clase puede ser "integrada" dentro de la tabla actual. Por ejemplo:class Person {
Address homeAddress
Address workAddress
static embedded = ['homeAddress', 'workAddress']
}class Address {
String number
String code
}
The resulting mapping would looking like this:
El mapeo resultante tendrÃa el siguiente aspecto:
If you define theSi la claseAddressclass in a separate Groovy file in thegrails-app/domaindirectory you will also get anaddresstable. If you don't want this to happen use Groovy's ability to define múltiple classes per file and include theAddressclass below thePersonclass in thegrails-app/domain/Person.groovyfileAddresses definida por separado en un archivo Groovy dentro del directoriograils-app/domain, la tablaaddresstambién sera generada. Si no desea que esto suceda, utilice la capacidad de Groovy para definir múltiples clases por archivo e incluya la claseAddressdebajo de la clasePersonen el archivograils-app/domain/Person.groovy.
5.2.3 Herencia en GORM
GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:
GORM soporta herencia de clases base abstractas y de entidades GORM persistentes concretas: Por ejemplo:class Content {
String author
}class BlogEntry extends Content {
URL url
}class Book extends Content { String ISBN }
class PodCast extends Content { byte[] audioStream }
In the above example we have a parent
En el ejemplo anterior tenemos una clase padre Content class and then various child classes with more specific behaviour.
Content y varias clases hijo con un comportamiento más especÃfico.Considerations
Consideraciones
At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called
A nivel de la base de datos, Grails mapeara una tabla-por-jerarquÃa e incluirá una columna discriminador llamada class so the parent class (Content) and its subclasses (BlogEntry, Book etc.), share the same table.
class, de esta forma la clase padre (Content) y las subclases (BlogEntry, Book etc.), comparten la misma tabla.
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
El mapeado de tabla-por-jerarquÃa tiene la desventaja de que no permite definir propiedades no nulas. Una alternativa es utilizar una tabla-por-subclase que puede habilitarse mediante el DSL ORM
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.
Sin embargo, el uso excesivo de herencia y de tabla-por-subclase, pueden dar lugar a un rendimiento deficiente de las consultas debido a la utilización de combinaciones externas en ellas. Nuestro consejo seria, si va a utilizar la herencia, no abusar de ella y no hacer la jerarquÃa de la herencia demasiado profunda.Polymorphic Queries
Consultas polimórficas
The upshot of inheritance is that you get the ability to polymorphically query. For example using the list method on the
Como resultado de la herencia se obtiene la capacidad de realizar una consulta polimórfica. Por ejemplo, al utilizar el método list de la super clase Content super class will return all subclasses of Content:
Content este devolverá todas las subclases de Content:def content = Content.list() // list all blog entries, books and podcasts
content = Content.findAllByAuthor('Joe Bloggs') // find all by authordef podCasts = PodCast.list() // list only podcastsdef content = Content.list() // lista todas las entradas de blog, books y podcasts
content = Content.findAllByAuthor('Joe Bloggs') // encontrar todo por authordef podCasts = PodCast.list() // lista únicamente los podcasts5.2.4 Conjuntos, Listas y Mapas
Sets of Objects
Conjuntos de objetos
By default when you define a relationship with GORM it is a
Al definir una relación con GORM, de manera predeterminada sera un java.util.Set which is an unordered collection that cannot contain duplicates. In other words when you have:
java.util.Set, una colección sin orden y que no puede contener duplicados. En otras palabras, cuando usted tiene:class Author {
static hasMany = [books: Book]
}
The books property that GORM injects is a
La propiedad books que GORM inyecta es un 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:
java.util.Set. El cual garantiza la unicidad de los elementos pero no el orden, lo cual puede no ser lo que usted quiere. Para personalizar el orden de los elementos establezca el conjunto como un SortedSet:class Author { SortedSet books static hasMany = [books: Book]
}
In this case a
En este caso, se hace uso de la implementación java.util.SortedSet implementation is used which means you must implement java.lang.Comparable in your Book class:
java.util.SortedSet, esto significa que la clase Book debe implementar java.lang.Comparable: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.
Como resultado de esta clase, las instancias Book en la colección books perteneciente a la clase Author, serán ordenadas por su fecha de publicación.
Lists of Objects
Listas de objetos
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
Para mantener los objetos en el orden que se han añadido y poder hacer referencia a ellos por medio del Ãndice como en un arreglo, se debe definir el tipo de colección como un List:
List:class Author { List books static hasMany = [books: Book]
}
In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:
En este caso, cuando se añaden nuevos elementos a la colección books, el orden se mantiene en una lista secuencial, son indexados desde 0 y es posible hacer lo siguiente:author.books[0] // get the first book
author.books[0] // obtener el primer book
The way this works at the database level is Hibernate creates a
A nivel de la base de datos, Hibernate crea una columna books_idx column where it saves the index of the elements in the collection to retain this order at the database level.
books_idx donde guarda el Ãndice de los elementos en la colección y de esta manera conserva el orden en la base de datos
When using a
Cuando se utiliza un 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):
List, los elementos se deben añadir a la colección antes de realizar el guardado, de lo contrario Hibernate arrojara una excepción (org.hibernate.HibernateException: null index column for collection):// This won't work!
def book = new Book(title: 'The Shining')
book.save()
author.addToBooks(book)// Esto no funcionara
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()
// Debe realizarse de esta forma.
def book = new Book(title: 'Misery')
author.addToBooks(book)
author.save()Bags of Objects
Bags de objetos
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.
Si el orden y la unicidad no son de importancia (o si usted realiza la gestión de manera explicita), entonces puede utilizar el tipo Bag de Hibernate para representar las colecciones mapeadas.
The only change required for this is to define the collection type as a
El único cambio requerido para esto, es definir el tipo de una colección utilizando Collection:
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
Debido a que la unicidad y el orden no son gestionados por Hibernate, añadir o eliminar elementos de una colección mapeada como Bag, no desencadenara la carga de las demás instancias desde la base de datos, por lo tanto, este método obtendrá un mejor desempeño y requiere un menor uso de memoria que cuando se usa un Set or a List.
Set o un List.Maps of Objects
Mapas de objetos
If you want a simple map of string/value pairs GORM can map this with the following:
Si lo que desea es un simple mapa de pares cadena-de-texto/valor, GORM puede realizar este mapeo de la siguiente manera:class Author {
Map books // map of ISBN:book names
}def a = new Author()
a.books = ["1590597583":"Grails Book"]
a.save()class Author {
Map books // mapa de ISBN:tÃtulo
}def a = new Author()
a.books = ["1590597583":"Grails Book"]
a.save()
In this case the key and value of the map MUST be strings.
En este caso, la clave y el valor del mapa DEBEN ser cadenas de texto.
If you want a Map of objects then you can do this:
Si lo que quiere es un mapa de objetos, entonces puede hacer lo siguiente: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
La propiedad estática hasMany property defines the type of the elements within the Map. The keys for the map must be strings.
hasMany define el tipo de elementos que contendrá el mapa. Las claves del mapa deben ser cadenas de texto.A Note on Collection Types and Performance
Acerca de los tipos de colecciones y el desempeño
The Java
El tipo Set type doesn't allow duplicates. To ensure uniqueness when adding an entry to a Set association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.
Set de Java no permite duplicados. Para garantizar la unicidad cuando se añade una entrada en una asociación Set, Hibernate debe cargar la asociación completa de la base de datos. Si la asociación contiene una gran cantidad de elementos, esto podrÃa resultar costoso en términos de rendimiento.
The same behavior is required for
El mismo funcionamiento aplica para el tipo List types, since Hibernate needs to load the entire association to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:
List debido a que para mantener el orden de los elementos, Hibernate necesita cargar la asociación entera. Por lo tanto, si espera una gran cantidad de registros en la asociación, es recomendable definirla de manera bidireccional, asà el enlace puede ser creado en el lado contrario:def book = new Book(title:"New Grails Book") def author = Author.get(1) book.author = author book.save()
In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an
En este ejemplo, se crea la asociación por el elemento hijo (Book) y por lo tanto, no es necesario operar directamente sobre la colección, el resultado es un menor numero de consultas y el código es más eficiente. Teniendo en cuenta un 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:
Author con una gran cantidad de instancias Book asociadas, si tuviera que escribir código como el siguiente notaria el resultado en el rendimiento:def book = new Book(title:"New Grails Book") def author = Author.get(1) author.addToBooks(book) author.save()
You could also model the collection as a Hibernate Bag as described above.
También podrÃa modelar la colección utilizando un Bag de Hibernate como se describió anteriormente.
5.3 Persistence Basics
A key thing to remember about Grails is that under the surface Grails is using Hibernate for persistence. If you are coming from a background of using ActiveRecord or iBatis Hibernate's "session" model may feel a little strange.Grails automatically binds a Hibernate session to the currently executing request. This lets you use the save and delete methods as well as other GORM methods transparently.Transactional Write-Behind
A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call save 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.5.3.1 Saving and Updating
An example of using the save method can be seen below:def p = Person.get(1) p.save()
def p = Person.get(1)
p.save(flush: true)def p = Person.get(1) try { p.save(flush: true) } catch (org.springframework.dao.DataIntegrityViolationException e) { // deal with exception }
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 }
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!
5.3.2 Deleting Objects
An example of the delete method can be seen below:def p = Person.get(1) p.delete()
flush argument:def p = Person.get(1)
p.delete(flush: true)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: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) }
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"])
5.3.3 Understanding Cascading Updates and Deletes
It is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is thebelongsTo setting which controls which class "owns" a relationship.Whether it is a one-to-one, one-to-many or many-to-many, defining belongsTo will result in updates cascading from the owning class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relationships deletes will also cascade.If you do not define belongsTo then no cascades will happen and you will have to manually save each object (except in the case of the one-to-many, in which case saves will cascade automatically if a new instance is in a hasMany collection).Here is an example:class Airport {
String name
static hasMany = [flights: Flight]
}class Flight {
String number
static belongsTo = [airport: Airport]
}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:new Airport(name: "Gatwick") .addToFlights(new Flight(number: "BA3430")) .addToFlights(new Flight(number: "EZ0938")) .save()
Airport all Flights associated with it will also be deleted:def airport = Airport.findByName("Gatwick")
airport.delete()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
class A { static hasMany = [bees: B] }class B { static belongsTo = [a: 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 A { static hasMany = [bees: B] }class B { }Bidirectional one-to-many, no belongsTo
class A { static hasMany = [bees: B] }class B { A 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 { }class B { static belongsTo = [a: 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.
5.3.4 Eager and Lazy Fetching
Associations in GORM are by default lazy. This is best explained by example:class Airport {
String name
static hasMany = [flights: Flight]
}class Flight {
String number
Location destination
static belongsTo = [airport: Airport]
}class Location {
String city
String country
}def airport = Airport.findByName("Gatwick") for (flight in airport.flights) { println flight.destination.city }
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).Configuring Eager Fetching
An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:class Airport {
String name
static hasMany = [flights: Flight]
static mapping = {
flights lazy: false
}
}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.Using Batch Fetching
Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. You can configure Hibernate to lazily fetch results in "batches". For example:class Airport {
String name
static hasMany = [flights: Flight]
static mapping = {
flights batchSize: 10
}
}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
}
}5.3.5 Pessimistic and Optimistic Locking
Optimistic Locking
By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a specialversion column in the database that is incremented after each update.The version column gets read into a version property that contains the current versioned state of persistent instance which you can access:def airport = Airport.get(10)println airport.version
def airport = Airport.get(10)try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }
The version will only be updated after flushing the session.
Pessimistic Locking
Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in 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()
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()
def airport = Airport.findByName("Heathrow", [lock: true])
def airport = Airport.createCriteria().get {
eq('name', 'Heathrow')
lock true
}5.3.6 Modification Checking
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: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 } }
5.4 Querying with GORM
GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL.Groovy's ability to manipulate collections with GPath and methods like sort, findAll and so on combined with GORM results in a powerful combination.However, let's start with the basics.Listing instances
Use the list method to obtain all instances of a given class:def books = Book.list()
def books = Book.list(offset:10, max:20)
def books = Book.list(sort:"title", order:"asc")
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.Retrieval by Database Identifier
The second basic form of retrieval is by database identifier using the get method:def book = Book.get(23)
def books = Book.getAll(23, 93, 81)
5.4.1 Dynamic Finders
GORM supports the concept of dynamic finders. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example theBook class:class Book {
String title
Date releaseDate
Author author
}class Author {
String name
}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:Book.findBy([Property][Comparator][Boolean Operator])?[Property][Comparator]def book = Book.findByTitle("The Stand")book = Book.findByTitleLike("Harry Pot%")
Like comparator, is equivalent to a SQL like expression.The possible comparators include:
InList- In the list of given valuesLessThan- less than a given valueLessThanEquals- less than or equal a give valueGreaterThan- greater than a given valueGreaterThanEquals- greater than or equal a given valueLike- Equivalent to a SQL like expressionIlike- Similar to aLike, except case insensitiveNotEqual- Negates equalityBetween- 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)
def now = new Date()
def lastWeek = now - 7
def book = Book.findByReleaseDateBetween(lastWeek, now)books = Book.findAllByReleaseDateIsNull()
books = Book.findAllByReleaseDateIsNotNull()Boolean logic (AND/OR)
Method expressions can also use a boolean operator to combine two or more criteria:def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan(
"%Java%", new Date() - 30)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)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) : []Author instance is not null we use it in a query to obtain all the Book instances for the given Author.Pagination and Sorting
The same pagination and sorting parameters available on the list method can also be used with dynamic finders by supplying a map as the final parameter:def books = Book.findAllByTitleLike("Harry Pot%", [max: 3, offset: 2, sort: "title", order: "desc"])
5.4.2 Criteria
Criteria is a type safe, 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 aStringBuffer.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")
}Account objects in a List matching the following criteria:
balanceis between 500 and 1000branchis 'London'holderFirstNamestarts with 'Fred' or 'Barney'
holderLastName.If no records are found with the above criteria, an empty List is returned.Conjunctions and Disjunctions
As demonstrated in the previous example you can group criteria in a logical OR using anor { } block:or {
between("balance", 500, 1000)
eq("branch", "London")
}and {
between("balance", 500, 1000)
eq("branch", "London")
}not {
between("balance", 500, 1000)
eq("branch", "London")
}Querying Associations
Associations can be queried by having a node that matches the property name. For example say theAccount class had many Transaction objects:class Account {
…
static hasMany = [transactions: Transaction]
…
}transaction as a builder node:def c = Account.createCriteria()
def now = new Date()
def results = c.list {
transactions {
between('date', now - 10, now)
}
}Account instances that have performed transactions within the last 10 days.
You can also nest such association queries within logical blocks:def c = Account.createCriteria()
def now = new Date()
def results = c.list {
or {
between('created', now - 10, now)
transactions {
between('date', now - 10, now)
}
}
}Querying with Projections
Projections may be used to customise the results. Define a "projections" node within the criteria builder tree to use projections. There are equivalent methods within the projections node to the methods found in the Hibernate Projections class:def c = Account.createCriteria()def numberOfBranches = c.get {
projections {
countDistinct('branch')
}
}Using SQL Restrictions
You can access Hibernate's SQL Restrictions capabilities.def c = Person.createCriteria()def peopleWithShortFirstNames = c.list {
sqlRestriction "char_length(first_name) <= 4"
}Note that the parameter there is SQL. Thefirst_nameattribute referenced in the example refers to the persistence model, not the object model like in HQL queries. ThePersonproperty namedfirstNameis mapped to thefirst_namecolumn in the database and you must refer to that in thesqlRestrictionstring.Also note that the SQL used here is not necessarily portable across databases.
Using Scrollable Results
You can use Hibernate's ScrollableResults feature by calling the scroll method:def results = crit.scroll {
maxResults(10)
}
def f = results.first()
def l = results.last()
def n = results.next()
def p = results.previous()def future = results.scroll(10)
def accountNumber = results.getLong('number')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.
Setting properties in the Criteria instance
If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. This allows full access to all the properties in this class. This example callssetMaxResults and setFirstResult on the Criteria instance:import org.hibernate.FetchMode as FM … def results = c.list { maxResults(10) firstResult(50) fetchMode("aRelationship", FM.JOIN) }
Querying with Eager Fetching
In the section on Eager and Lazy Fetching we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:def criteria = Task.createCriteria()
def tasks = criteria.list{
eq "assignee.id", task.assignee.id
join 'assignee'
join 'project'
order 'priority', 'asc'
}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:
import org.hibernate.FetchMode as FM … def results = Airport.withCriteria { eq "region", "EMEA" fetchMode "flights", FM.SELECT }
flights association, you will get reliable results - even with the maxResults option.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:fetchModeandjoinare 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.
def results = Airport.withCriteria {
eq "region", "EMEA"
flights {
like "number", "BA%"
}
}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 { … }c.list { … }| Method | Description |
|---|---|
| list | This is the default method. It returns all matching rows. |
| get | 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. |
| scroll | Returns a scrollable result set. |
| listDistinct | If subqueries or associations are used, one may end up with the same row multiple times in 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. |
5.4.3 Hibernate Query Language (HQL)
GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found in the Hibernate documentation of the Hibernate documentation.GORM provides a number of methods that work with HQL including find, findAll and executeQuery. An example of a query can be seen below:def results =
Book.findAll("from Book as b where b.title like 'Lord of the%'")Positional and Named Parameters
In this case the value passed to the query is hard coded, however you can equally use positional parameters:def results =
Book.findAll("from Book as b where b.title like ?", ["The Shi%"])def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = ?", [author])
def results =
Book.findAll("from Book as b " +
"where b.title like :search or b.author like :search",
[search: "The Shi%"])def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = :author", [author: author])
Multiline Queries
Use the line continuation character to separate the query across multiple lines:def results = Book.findAll("\
from Book as b, \
Author as a \
where b.author = a and a.surname = ?", ['Smith'])Triple-quoted Groovy multiline Strings will NOT work with HQL queries.
Pagination and Sorting
You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a Map at the end of the method call and include an "ORDER BY" clause in the HQL:def results =
Book.findAll("from Book as b where " +
"b.title like 'Lord of the%' " +
"order by b.title asc",
[max: 10, offset: 20])5.5 Advanced GORM Features
The following sections cover more advanced usages of GORM including caching, custom mapping and events.5.5.1 Events and Auto Timestamping
GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:beforeInsert- Executed before an object is initially persisted to the databasebeforeUpdate- Executed before an object is updatedbeforeDelete- Executed before an object is deletedbeforeValidate- Executed before an object is validatedafterInsert- Executed after an object is persisted to the databaseafterUpdate- Executed after an object has been updatedafterDelete- Executed after an object has been deletedonLoad- Executed when an object is loaded from the database
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 databaseclass Person {
Date dateCreated def beforeInsert() {
dateCreated = new Date()
}
}The beforeUpdate event
Fired before an existing object is updatedclass Person {
Date dateCreated
Date lastUpdated def beforeInsert() {
dateCreated = new Date()
}
def beforeUpdate() {
lastUpdated = new Date()
}
}The beforeDelete event
Fired before an object is deleted.class Person {
String name
Date dateCreated
Date lastUpdated def beforeDelete() {
ActivityTrace.withNewSession {
new ActivityTrace(eventName:"Person Deleted",data:name).save()
}
}
}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.The beforeValidate event
Fired before an object is validated.class Person {
String name static constraints = {
name size: 5..45
} def beforeValidate() {
name = name?.trim()
}
}beforeValidate method is run before any validators are run.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 whenEither or both versions ofvalidateis triggered indirectly because of a call to thesavemethod that thevalidatemethod is being invoked with no arguments, not aListthat includes all of the property names.
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.The onLoad/beforeLoad event
Fired immediately before an object is loaded from the database:class Person {
String name
Date dateCreated
Date lastUpdated def onLoad() {
log.debug "Loading ${id}"
}
}beforeLoad() is effectively a synonym for onLoad(), so only declare one or the other.The afterLoad event
Fired immediately after an object is loaded from the database:class Person {
String name
Date dateCreated
Date lastUpdated def afterLoad() {
name = "I'm loaded"
}
}Custom Event Listeners
You can also register event handler classes in an application'sgrails-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: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]
}
}def doWithSpring = { auditListener(AuditEventListener) hibernateEventListeners(HibernateEventListeners) {
listenerMap = ['post-insert': auditListener,
'post-update': auditListener,
'post-delete': auditListener]
}
}Automatic timestamping
The examples above demonstrated using events to update alastUpdated 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 putnullable: falseconstraints on eitherdateCreatedorlastUpdated, your domain instances will fail validation - probably not what you want. Leave constraints off these properties unless you have disabled automatic timestamping.
5.5.2 Custom ORM Mapping
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 cachingCustom mappings are defined using a a static
mapping block defined within your domain class:class Person {
…
static mapping = { }
}grails.gorm.default.mapping = { version false autoTimestamp false }
5.5.2.1 Table and Column Names
Table names
The database table name which the class maps to can be customized using thetable method:class Person {
…
static mapping = {
table 'people'
}
}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'
}
}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.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 aPostCodeType you could use it as follows:class Address { String number
String postCode static mapping = {
postCode type: PostCodeType
}
}class Address { String number
String postCode static mapping = {
postCode type: 'text'
}
}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'
}
}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 betweenPerson 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'
}
}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]
}class Person {
…
static belongsTo = Group
static hasMany = [groups: Group]
}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'
}
}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'
}
}5.5.2.2 Caching Strategy
Setting up caching
Hibernate features a second-level cache with a customizable cache provider. This needs to be configured in thegrails-app/conf/DataSource.groovy file as follows:hibernate {
cache.use_second_level_cache=true
cache.use_query_cache=true
cache.provider_class='org.hibernate.cache.EhCacheProvider'
}For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate documentation on the subject.
Caching instances
Call thecache method in your mapping block to enable caching with the default settings:class Person {
…
static mapping = {
table 'people'
cache true
}
}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
}
}class Address {
String number
String postCode
}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 thecache 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, anonstrict-read-writecache might be appropriate.transactional- Thetransactionalcache 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 specifyhibernate.transaction.manager_lookup_classin thegrails-app/conf/DataSource.groovyfile'shibernateconfig.
5.5.2.3 Inheritance Strategies
By default GORM classes usetable-per-hierarchy inheritance mapping. This has the disadvantage that columns cannot have a NOT-NULL constraint applied to them at the database level. If you would prefer to use a table-per-subclass inheritance strategy you can do so as follows:class Payment {
Integer amount static mapping = {
tablePerHierarchy false
}
}class CreditCardPayment extends Payment {
String cardNumber
}Payment class specifies that it will not be using table-per-hierarchy mapping for all child classes.
5.5.2.4 Custom Database Identity
You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:class Person {
…
static mapping = {
table 'people'
version false
id generator: 'hilo',
params: [table: 'hi_value',
column: 'next_value',
max_lo: 100]
}
}For more information on the different Hibernate generators refer to the Hibernate reference documentationAlthough 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'
}
}5.5.2.5 Composite Primary Keys
GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:import org.apache.commons.lang.builder.HashCodeBuilderclass Person implements Serializable { String firstName String lastName boolean equals(other) { if (!(other instanceof Person)) { return false } other.firstName == firstName && other.lastName == lastName } int hashCode() { def builder = new HashCodeBuilder() builder.append firstName builder.append lastName builder.toHashCode() } static mapping = { id composite: ['firstName', 'lastName'] } }
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
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
}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:class Address {
Person person
static mapping = {
person {
column: "FirstName"
column: "LastName"
}
}
}5.5.2.6 Database Indices
To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns are used in which indexes:class Person {
String firstName
String address
static mapping = {
table 'people'
version false
id column: 'person_id'
firstName column: 'First_Name', index: 'Name_Idx'
address column: 'Address', index: 'Name_Idx,Address_Index'
}
}index attribute; in this example index:'Name_Idx, Address_Index' will cause an error.
5.5.2.7 Optimistic Locking and Versioning
As discussed in the section on Optimistic and Pessimistic Locking, by default GORM uses optimistic locking and automatically injects aversion property into every class which is in turn mapped to a version column at the database level.If you're mapping to a legacy schema that doesn't have version columns (or there's some other reason why you don't want/need this feature) you can disable this with the version method:class Person {
…
static mapping = {
table 'people'
version false
}
}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
Version columns types
By default Grails maps theversion property as a Long that gets incremented by one each time an instance is updated. But Hibernate also supports using a Timestamp, for example:import java.sql.Timestampclass Person { … Timestamp version static mapping = { table 'people' } }
Timestamp instead of a Long is that you combine the optimistic locking and last-updated semantics into a single column.
5.5.2.8 Eager and Lazy Fetching
Lazy Collections
As discussed in the section on Eager and Lazy fetching, GORM collections are lazily loaded by default but you can change this behaviour with the ORM DSL. There are several options available to you, but the most common ones are:- lazy: false
- fetch: 'join'
class Person { String firstName
Pet pet static hasMany = [addresses: Address] static mapping = {
addresses lazy: false
pet fetch: 'join'
}
}class Address {
String street
String postCode
}class Pet {
String name
}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:
- batchSize: N
- lazy: false, batchSize: N
Person:class Person { String firstName
Pet pet static mapping = {
pet batchSize: 5
}
}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.Lazy Single-Ended Associations
In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows significantly!Use the same technique as for lazy collections to make a one-to-one or many-to-one association non-lazy/eager:class Person {
String firstName
}class Address { String street
String postCode static belongsTo = [person: Person] static mapping = {
person lazy: false
}
}Person instance (through the person property) whenever an Address is loaded.Lazy Single-Ended Associations and Proxies
Hibernate uses runtime-generated proxies to facilitate single-ended lazy associations; Hibernate dynamically subclasses the entity class to create the proxy.Consider the previous example but with a lazily-loadedperson association: Hibernate will set the person property to a proxy that is a subclass of Person. When you call any of the getters (except for the id property) or setters on that proxy, Hibernate will load the entity from the database.Unfortunately this technique can produce surprising results. Consider the following example classes:class Pet {
String name
}class Dog extends Pet {
}class Person {
String name
Pet pet
}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
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.list()[0] instanceof Dog
assert Pet.list()[0] instanceof DogPerson 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)
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]
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.
5.5.2.9 Custom Cascade Behaviour
As described in the section on cascading updates, the primary mechanism to control the way updates and deletes cascade from one association to another is the static belongsTo property.However, the ORM DSL gives you complete access to Hibernate's transitive persistence capabilities using thecascade attribute.Valid settings for the cascade attribute include:
merge- merges the state of a detached associationsave-update- cascades only saves and updates to an associationdelete- cascades only deletes to an associationlock- useful if a pessimistic lock should be cascaded to its associationsrefresh- cascades refreshes to an associationevict- cascades evictions (equivalent todiscard()in GORM) to associations if setall- cascade all operations to associationsall-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 usageTo 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"
}
}class Address {
String street
String postCode
}5.5.2.10 Custom Hibernate Types
You saw in an earlier section that you can use composition (with theembedded property) to break a table into multiple objects. You can achieve a similar effect with Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes. Each of these types also has a corresponding "meta-type" class that implements org.hibernate.usertype.UserType.The Hibernate reference manual has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:class Book { String title
String author
Rating rating static mapping = {
rating type: RatingUserType
}
}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
}
}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
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: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"
}
}5.5.2.11 Derived Properties
A derived property is one that takes its value from a SQL expression, often but not necessarily based on the value of one or more other persistent properties. Consider a Product class like this:class Product {
Float price
Float taxRate
Float tax
}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'
}
}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: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=?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)
Product.withCriteria {
gt 'tax', 21.12f
}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.
5.5.2.12 Custom Naming Strategy
By default Grails uses Hibernate'sImprovedNamingStrategy 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
}package com.myco.myprojimport org.hibernate.cfg.ImprovedNamingStrategy import org.hibernate.util.StringHelperclass CustomNamingStrategy extends ImprovedNamingStrategy { String classToTableName(String className) { "table_" + StringHelper.unqualify(className) } String propertyToColumnName(String propertyName) { "col_" + StringHelper.unqualify(propertyName) } }
5.5.3 Default Sort Order
You can sort objects using query arguments such as those found in the list method:def airports = Airport.list(sort:'name')
class Airport {
…
static mapping = {
sort "name"
}
}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"
}
}class Airport {
…
static hasMany = [flights: Flight] static mapping = {
flights sort: 'number', order: 'desc'
}
}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.
5.6 Programmatic Transactions
Grails is built on Spring and uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this simpler with the withTransaction method. This method has a single parameter, a Closure, which has a single parameter which is a Spring TransactionStatus instance.Here's an example of usingwithTransaction in a controller methods:def transferFunds() {
Account.withTransaction { status ->
def source = Account.get(params.from)
def dest = Account.get(params.to) def amount = params.amount.toInteger()
if (source.active) {
if (dest.active) {
source.balance -= amount
dest.amount += amount
}
else {
status.setRollbackOnly()
}
}
}
}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.
5.7 GORM and Constraints
Although constraints are covered in the Validation section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.Consider the following example. Suppose we have a domain model with the following properties:String name String description
| Column | Data Type |
|---|---|
| name | varchar(255) |
| description | varchar(255) |
| Column | Data Type |
|---|---|
| description | TEXT |
static constraints = {
description maxSize: 1000
}Constraints Affecting String Properties
If either themaxSize or the size constraint is defined, Grails sets the maximum column length based on the constraint value.In general, it's not advisable to use both constraints on the same domain class property. However, if both the maxSize constraint and the size constraint are defined, then Grails sets the column length to the minimum of the maxSize constraint and the upper bound of the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)If the inList constraint is defined (and the maxSize and the size constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values. For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").Constraints Affecting Numeric Properties
If themax, min, or range constraint is defined, Grails attempts to set the column precision based on the constraint value. (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)In general, it's not advisable to combine the pair min/max and range constraints together on the same domain class property. However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints. (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.)
If the scale constraint is defined, then Grails attempts to set the column scale based on the constraint value. This rule only applies to floating point numbers (i.e., java.lang.Float, java.Lang.Double, java.lang.BigDecimal, or subclasses of java.lang.BigDecimal). The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of min/max constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless the specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example:someFloatValue max: 1000000, scale: 3
someFloatValue DECIMAL(19, 3) // precision is defaultsomeFloatValue max: 12345678901234567890, scale: 5
someFloatValue DECIMAL(25, 5) // precision = digits in max + scale
someFloatValue max: 100, min: -100000
someFloatValue DECIMAL(8, 2) // precision = digits in min + default scale6 The Web Layer
6.1 Controllers
A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends withController in the grails-app/controllers directory (in a subdirectory if it's in a package).The default URL Mapping configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI.
6.1.1 Understanding Controllers and Actions
Creating a controller
Controllers can be created with the create-controller or generate-controller command. For example try running the following command from the root of a Grails project:grails create-controller book
grails-app/controllers/myapp/BookController.groovy:package myappclass BookController { def index() { }
}BookController by default maps to the /book URI (relative to your application root).Thecreate-controllerandgenerate-controllercommands 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:class BookController { def list() { // do controller logic
// create model return model
}
}/book/list URI by default thanks to the property being named list.Public Methods as Actions
In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferred approach is to use methods.Leveraging methods instead of Closure properties has some advantages:- Memory efficient
- Allow use of stateless controllers (
singletonscope) - You can override actions from subclasses and call the overridden superclass method with
super.actionName() - Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.
grails.compile.artefacts.closures.convert property to true in BuildConfig.groovy:
grails.compile.artefacts.closures.convert = trueThe Default Action
A controller has the concept of a default URI that maps to the root URI of the controller, for example/book for BookController. The action that is called when the default URI is requested is dictated by the following rules:
- If there is only one action, it's the default
- If you have an action named
index, it's the default - Alternatively you can set it explicitly with the
defaultActionproperty:
static defaultAction = "list"
6.1.2 Controllers and Scopes
Available Scopes
Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:- servletContext - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of ServletContext
- session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession
- request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest
- params - Mutable map of incoming request query string or POST parameters
- flash - See below
Accessing Scopes
Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even 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"]
}
}class BookController {
def find() {
def findBy = params.findBy
def appContext = request.foo
def loggedUser = session.logged_user
}
}Using Flash Scope
Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:def delete() {
def b = Book.get(params.id)
if (!b) {
flash.message = "User not found for id ${params.id}"
redirect(action:list)
}
… // remaining code
}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 isprototype 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 sessionsingleton- Only one instance of the controller ever exists (recommended for actions as methods)
scope property to your class with one of the valid scope values listed above, for examplestatic scope = "singleton"
Config.groovy with the grails.controllers.defaultScope key, for example:grails.controllers.defaultScope = "singleton"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 thanprototypemay also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope isprototype.
6.1.3 Models and Views
Returning the Model
A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:def show() {
[book: Book.get(params.id)]
}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:import org.springframework.web.servlet.ModelAndViewdef 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 ]) }
attributesapplication
Selecting the View
In both of the previous two examples there was no code that specified which view to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the locationgrails-app/views/book/show.gsp for this list action:class BookController {
def show() {
[book: Book.get(params.id)]
}
}def show() {
def map = [book: Book.get(params.id)]
render(view: "display", model: map)
}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)
}grails-app/views/shared/display.gsp.Grails also supports JSPs as views, so if a GSP isn't found in the expected location but a JSP is, it will be used 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 flexiblerender method can be used:render "Hello World!"// write some markup
render {
for (b in books) {
div(id: b.id, b.title)
}
}// render a specific view render(view: 'show')
// render a template for each item in a collection
render(template: 'book_template', collection: Book.list())// render some text with encoding and content type render(text: "<xml>some xml</xml>", contentType: "text/xml", encoding: "UTF-8")
MarkupBuilder to generate HTML for use with the render method be careful of naming clashes between HTML elements and Grails tags, for example:import groovy.xml.MarkupBuilder … def login() { def writer = new StringWriter() def builder = new MarkupBuilder(writer) builder.html { head { title 'Log in' } body { h1 'Hello' form { } } } def html = writer.toString() render html }
MarkupBuilder). To correctly output a <form> element, use the following:def login() {
// …
body {
h1 'Hello'
builder.form {
}
}
// …
}6.1.4 Redirects and Chaining
Redirects
Actions can be redirected using the redirect controller method:class OverviewController { def login() {} def find() {
if (!session.user)
redirect(action: 'login')
return
}
…
}
}sendRedirect method.The redirect method expects one of:
- Another closure within the same controller class:
// Call the login action within the same class redirect(action: login)
- The name of an action (and controller name if the redirect isn't to an action in the current controller):
// Also redirects to the index action in the home controller redirect(controller: 'home', action: 'index')
- A URI for a resource relative the application context path:
// Redirect to an explicit URI
redirect(uri: "/login.html")- Or a full URL:
// Redirect to a URL
redirect(url: "http://grails.org")params argument of the method:redirect(action: 'myaction', params: [myparam: "myvalue"])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)redirect(controller: "test", action: "show", fragment: "profile")
Chaining
Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling thefirst 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])
}
}[one: 1, two: 2, three: 3]
chainModel map. This dynamic property only exists in actions following the call to the chain method:class ChainController { def nextInChain() {
def model = chainModel.myModel
…
}
}redirect method you can also pass parameters to the chain method:chain(action: "action1", model: [one: 1], params: [myparam: "param1"])
6.1.5 Controller Interceptors
Often it is useful to intercept processing based on either request, session or application state. This can be achieved with action interceptors. There are currently two types of interceptors: before and after.If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic of each controller
Before Interception
ThebeforeInterceptor 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}"
}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 }
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 theafterInterceptor property to define an interceptor that is executed after an action:def afterInterceptor = { model ->
println "Tracing action ${actionUri}"
}def afterInterceptor = { model, modelAndView ->
println "Current view is ${modelAndView.viewName}"
if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview"
println "View is now ${modelAndView.viewName}"
}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']def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]def beforeInterceptor = [action: this.&auth, only: ['secure']]6.1.6 Data Binding
Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.Grails uses Spring's underlying data binding capability to perform data binding.Binding Request Data to the Model
There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:def save() {
def b = new Book(params)
b.save()
}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
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()
}Data binding and Single-ended Associations
If you have aone-to-one or many-to-one association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:/book/save?author.id=20
.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)null by passing the literal String "null". For example:/book/save?author.id=nullData Binding and Many-ended Associations
If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.If you have aSet based association (the default for a hasMany) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <g:select> below:<g:select name="books"
from="${Book.list()}"
size="5" multiple="yes" optionKey="id"
value="${author?.books}" />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:<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" />
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" />
<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" />
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}" />
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': '']"/>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': '']"/>Map property images under a key of "cover".Data binding with Multiple domain classes
It is possible to bind data to multiple domain objects from the params object.For example so you have an incoming request to:/book/save?book.title=The%20Stand&author.name=Stephen%20King
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)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)Data Binding and Action Arguments
Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action arguments. The first category is command objects. Complex types are treated as command objects. See the Command Objects section of the user guide for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding type wrappers and java.lang.String. The default behavior is to map request parameters to action arguments by name:class AccountingController { // accountNumber will be initialized with the value of params.accountNumber
// accountType will be initialized with params.accountType
def displayInvoice(String accountNumber, int accountType) {
// …
}
}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
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.RequestParameterclass 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) { // … } }
Data binding and type conversion errors
Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. This results in a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class. For example:class Book {
…
URL publisherURL
}Book that uses the java.net.URL class to represent URLs. Given an incoming request such as:/book/save?publisherURL=a-bad-url
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!" }
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 URLtypeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL
Data Binding and Security concerns
When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes and be persisted in the database. You can limit what properties are bound to a given domain class using the subscript operator:def p = Person.get(1)p.properties['firstName','lastName'] = params
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)bindData method also lets you exclude certain parameters that you don't want updated:def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName]])
Note that if an empty List is provided as a value for the include parameter then all fields will be subject to binding if they are not explicitly excluded.
6.1.7 XML and JSON Responses
Using the render method to output XML
Grails supports a few different ways to produce XML and JSON responses. The first is the render method.Therender method can be passed a block of code to do mark-up building in XML:def list() { def results = Book.list() render(contentType: "text/xml") {
books {
for (b in results) {
book(title: b.title)
}
}
}
}<books> <book title="The Stand" /> <book title="The Shining" /> </books>
def list() { def books = Book.list() // naming conflict here render(contentType: "text/xml") {
books {
for (b in results) {
book(title: b.title)
}
}
}
}books which Groovy attempts to invoke as a method.Using the render method to output JSON
Therender method can also be used to output JSON:def list() { def results = Book.list() render(contentType: "text/json") {
books = array {
for (b in results) {
book title: b.title
}
}
}
}[
{title:"The Stand"},
{title:"The Shining"}
]Automatic XML Marshalling
Grails also supports automatic marshalling of domain classes to XML using special converters.To start off with, import thegrails.converters package into your controller:import grails.converters.*render Book.list() as XML
<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>
def xml = Book.list().encodeAsXML() render xml
Automatic JSON Marshalling
Grails also supports automatic marshalling to JSON using the same mechanism. Simply substituteXML with JSON:render Book.list() as JSON
[
{"id":1,
"class":"Book",
"author":"Stephen King",
"title":"The Stand"},
{"id":2,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]encodeAsJSON to achieve the same effect.
6.1.8 More on JSONBuilder
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.JSONBuilder and Grails versions
JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 the deprecated grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilderFor backwards compatibility the oldJSONBuilder class is used with the render method for older applications; to use the newer/better JSONBuilder class set the following in Config.groovy:grails.json.legacy.builder = falseRendering Simple Objects
To render a simple JSON object just set properties within the context of the Closure:render(contentType: "text/json") { hello = "world" }
{"hello":"world"}Rendering JSON Arrays
To render a list of objects simple assign a list:render(contentType: "text/json") {
categories = ['a', 'b', 'c']
}{"categories":["a","b","c"]}render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }
{"categories":[ {"a":"A"} , {"b":"B"}] }element method to return a list as the root:render(contentType: "text/json") {
element 1
element 2
element 3
}[1,2,3]
Rendering Complex Objects
Rendering complex objects can be done with Closures. For example:render(contentType: "text/json") { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }
{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}Arrays of Complex Objects
As mentioned previously you can nest complex objects within arrays using Closures:render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }
array method to build them up dynamically:def results = Book.list() render(contentType: "text/json") { books = array { for (b in results) { book title: b.title } } }
Direct JSONBuilder API Access
If you don't have access to therender method, but still want to produce JSON you can use the API directly:def builder = new JSONBuilder()def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }// prints the JSON text println result.toString()def sw = new StringWriter() result.render sw
6.1.9 Uploading Files
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uploading is to create a multipart form like this:Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>
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: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')
}InputStream and so on with the MultipartFile interface.File Uploads through Data Binding
File uploads can also be performed using data binding. Consider thisImage domain class:class Image {
byte[] myFile static constraints = {
// Limit upload file size to 2MB
myFile maxSize: 1024 * 1024 * 2
}
}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)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
}6.1.10 Command Objects
Grails controllers support the concept of command objects. A command object is similar to a form bean in a framework like Struts, and they are useful for populating a subset of the properties needed to update a domain class. Or where there is no domain class required for the interaction, but you need features such as data binding and validation.Declaring Command Objects
Command objects are typically declared in the same source file as a controller, directly below the controller class definition. For example:class UserController {
…
}class LoginCommand {
String username
String password static constraints = {
username(blank: false, minSize: 6)
password(blank: false, minSize: 6)
}
}Using Command Objects
To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create, populate and validate.Before the controller action is executed Grails will automatically create an instance of the command object class, populate its properties with by binding the request parameters, and validate the command object. For example:class LoginController { def login = { LoginCommand cmd ->
if (cmd.hasErrors()) {
redirect(action: 'loginForm')
return
} // work with the command object data
}
}class LoginController {
def login(LoginCommand cmd) {
if (cmd.hasErrors()) {
redirect(action: 'loginForm')
return
} // work with the command object data
}
}Command Objects and Dependency Injection
Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic uses Grails services:class LoginCommand { def loginService String username
String password static constraints = {
username validator: { val, obj ->
obj.loginService.canLogin(obj.username, obj.password)
}
}
}loginService bean which is injected by name from the Spring ApplicationContext.
6.1.11 Handling Duplicate Form Submissions
Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you define a token on the form tag:<g:form useToken="true" ...>withForm {
// good request
}.invalidToken {
// bad request
}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.
6.1.12 Simple Type Converters
Type Conversion Methods
If you prefer to avoid the overhead of Data Binding and simply want to convert incoming parameters (typically Strings) into another more appropriate type the params object has a number of convenience methods for each type:def total = params.int('total')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)attrs parameter of GSP tags.Handling Multi Parameters
A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as?name=Bob&name=Judy.In this case dealing with one parameter and dealing with many has different semantics since Groovy's iteration mechanics for String iterate over each character. To avoid this problem the params object provides a list method that always returns a list:for (name in params.list('name')) {
println name
}6.1.13 Asynchronous Request Processing
Grails support asynchronous request processing as provided by the Servlet 3.0 specification. To enable the async features you need to set your servlet target version to 3.0 in BuildConfig.groovy:grails.servlet.version = "3.0"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 thestartAsync 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()
}
}complete() method to terminate the connection.Resuming an Async Request
You resume processing of an async request (for example to delegate to view rendering) by using thedispatch method of the AsyncContext class:def index() {
def ctx = startAsync()
ctx.start {
// do working
…
// render view
ctx.dispatch()
}
}6.2 Groovy Server Pages
Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.GSPs live in thegrails-app/views directory and are typically rendered automatically (by convention) or with the render method such as:render(view: "index")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)]
}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}6.2.1 GSP Basics
In the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover some basic syntax that users of JSP and ASP should be familiar with.GSP supports the usage of<% %> scriptlet blocks to embed Groovy code (again this is discouraged):<html> <body> <% out << "Hello GSP!" %> </body> </html>
<%= %> syntax to output values:<html> <body> <%="Hello GSP!" %> </body> </html>
<html> <body> <%-- This is my comment --%> <%="Hello GSP!" %> </body> </html>
6.2.1.1 Variables and Scopes
Within the<% %> brackets you can declare variables:<% now = new Date() %><%=now%>application- The javax.servlet.ServletContext instanceapplicationContextThe Spring ApplicationContext instanceflash- The flash objectgrailsApplication- The GrailsApplication instanceout- The response writer for writing to the output streamparams- The params object for retrieving request parametersrequest- The HttpServletRequest instanceresponse- The HttpServletResponse instancesession- The HttpSession instancewebRequest- The GrailsWebRequest instance
6.2.1.2 Logic and Iteration
Using the<% %> syntax you can embed loops and so on using this syntax:<html> <body> <% [1,2,3,4].each { num -> %> <p><%="Hello ${num}!" %></p> <%}%> </body> </html>
<html> <body> <% if (params.hello == 'true')%> <%="Hello!"%> <% else %> <%="Goodbye!"%> </body> </html>
6.2.1.3 Page Directives
GSP also supports a few JSP-style page directives.The import directive lets you import classes into the page. However, it is rarely needed due to Groovy's default imports and GSP Tags:<%@ page import="java.awt.*" %><%@ page contentType="text/json" %>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>
${..} 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'6.2.2 GSP Tags
Now that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, which are the preferred way to define GSP pages.The section on Tag Libraries covers how to add your own custom tag libraries.All built-in GSP tags start with the prefix
g:. Unlike JSP, you don't specify any tag library imports. If a tag starts with g: it is automatically assumed to be a GSP tag. An example GSP tag would look like:<g:example /><g:example> Hello world </g:example>
<g:example attr="${new Date()}"> Hello world </g:example>
<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]"> Hello world </g:example>
<g:example attr="${new Date()}" attr2="[one:'one', two:'two']"> Hello world </g:example>
6.2.2.1 Variables and Scopes
Variables can be defined within a GSP using the set tag:<g:set var="now" value="${new Date()}" />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>
page- Scoped to the current page (default)request- Scoped to the current requestflash- Placed within flash scope and hence available for the next requestsession- Scoped for the user sessionapplication- Application-wide scope.
scope attribute:<g:set var="now" value="${new Date()}" scope="request" />6.2.2.2 Logic and Iteration
GSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif tags for use with branching:<g:if test="${session.role == 'admin'}"> <%-- show administrative functions --%> </g:if> <g:else> <%-- show basic functions --%> </g:else>
<g:each in="${[1,2,3]}" var="num"> <p>Number ${num}</p> </g:each><g:set var="num" value="${1}" /> <g:while test="${num < 5 }"> <p>Number ${num++}</p> </g:while>
6.2.2.3 Search and Filtering
If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tasks:Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>
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>
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>
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!
6.2.2.4 Links and Resources
GSP also features tags to help you manage linking to controllers and actions. The link tag lets you specify controller and action name pairing and it will automatically work out the link based on the URL Mappings, even if you change them! For example:<g:link action="show" id="1">Book 1</g:link><g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link><g:link controller="book">Book Home</g:link><g:link controller="book" action="list">Book List</g:link><g:link url="[action: 'list', controller: 'book']">Book List</g:link><g:link params="[sort: 'title', order: 'asc', author: currentBook.author]" action="list">Book List</g:link>
6.2.2.5 Forms and Fields
Form Basics
GSP supports many different tags for working with HTML forms and fields, the most basic of which is the form tag. This is a controller/action aware version of the regular HTML form tag. Theurl attribute lets you specify which controller and action to map to:<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>
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
<g:textField name="myField" value="${myValue}" />Multiple Submit Buttons
The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the actionSubmit tag. It is just like a regular submit, but lets you specify an alternative action to submit to:<g:actionSubmit value="Some update label" action="update" />6.2.2.6 Tags as Method Calls
One major different between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from controllers, tag libraries or GSP views.Tags as method calls from GSPs
Tags return their results as a String-like object (aStreamCharBuffer 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")}<img src="${createLinkTo(dir: 'images', file: 'logo.jpg')}" /><img src="<g:createLinkTo dir="images" file="logo.jpg" />" />Tags as method calls from Controllers and Tag Libraries
You can also invoke tags from controllers and tag libraries. Tags within the defaultg: namespace can be invoked without the prefix and a StreamCharBuffer result is returned:def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()
def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()
def editor = fckeditor.editor(name: "text", width: "100%", height: "400")
6.2.3 Views and Templates
Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with Layouts provide a highly re-usable mechanism for structured views.Template Basics
Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example, you might have a template that renders Books located atgrails-app/views/book/_bookTemplate.gsp:<div class="book" id="${book?.id}"> <div>Title: ${book?.title}</div> <div>Author: ${book?.author?.name}</div> </div>
grails-app/views/book:<g:render template="bookTemplate" model="[book: myBook]" />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 theBookController 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" /><g:render template="/book/bookTemplate" model="[book: myBook]" />The Template Namespace
Since templates are used so frequently there is template namespace, calledtmpl, available that makes using templates easier. Consider for example the following usage pattern:<g:render template="bookTemplate" model="[book:myBook]" />tmpl namespace as follows:<tmpl:bookTemplate book="${myBook}" />Templates in Controllers and Tag Libraries
You can also render templates from controllers using the render controller method. This is useful for Ajax applications where you generate small HTML or data responses to partially update the current page instead of performing new request:def bookData() {
def b = Book.get(params.id)
render(template:"bookTemplate", model:[book:b])
}def bookData() {
def b = Book.get(params.id)
String content = g.render(template:"bookTemplate", model:[book:b])
render content
}g namespace which tells Grails we want to use the tag as method call instead of the render method.
6.2.4 Layouts with Sitemesh
Creating Layouts
Grails leverages Sitemesh, a decorator engine, to support view layouts. Layouts are located in thegrails-app/views/layouts directory. A typical layout can be seen below:<html> <head> <title><g:layoutTitle default="An example decorator" /></title> <g:layoutHead /> </head> <body onload="${pageProperty(name:'body.onload')}"> <div class="menu"><!--my common menu goes here--></menu> <div class="body"> <g:layoutBody /> </div> </div> </body> </html>
layoutTitle- outputs the target page's titlelayoutHead- outputs the target page's head tag contentslayoutBody- outputs the target page's body tag contents
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>
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>
Specifying A Layout In A Controller
Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:class BookController {
static layout = 'customer' def list() { … }
}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:class BookController {
static layout = 'custom/customer' def list() { … }
}grails-app/views/layouts/custom/customer.gsp template.Layout by Convention
Another way to associate layouts is to use "layout by convention". For example, if you have this controller:class BookController {
def list() { … }
}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'grails-app/views/layouts/myLayoutName.gsp.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:<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" /><g:applyLayout name="myLayout"> <g:include controller="book" action="list" /> </g:applyLayout>
def content = include(controller:"book", action:"list")
6.2.5 Static Resources
Grails 2.0 integrates with the Resources plugin to provide sophisticated static resource management. This plugin is installed by default in new Grails applications.The basic way to include a link to a static resource in your application is to use the resource tag. This simple approach creates a URI pointing to the file.However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.The issues that the Resources framework tackles are:- Web application performance tuning is difficult
- Correct ordering of resources, and deferred inclusion of JavaScript
- Resources that depend on others that must be loaded first
- The need for a standard way to expose static resources in plugins and applications
- The need for an extensible processing chain to optimize resources
- Preventing multiple inclusion of the same resource
6.2.5.1 Including resources using the resource tags
Pulling in resources with r:require
To use resources, your GSP page must indicate which resource modules it requires. For example with the jQuery plugin, which exposes a "jquery" resource module, to use jQuery in any page on your site you simply add:<html> <head> <r:require module="jquery"/> <r:layoutResources/> </head> <body> … <r:layoutResources/> </body> </html>
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>
Rendering the links to resources with r:layoutResources
When you have declared the resource modules that your GSP page requires, the framework needs to render the 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>
Adding page-specific JavaScript code with r:script
Grails has the javascript tag which is adapted to defer to Resources plugin if installed, but it is recommended that you callr:script directly when you need to include fragments of JavaScript code.This lets you write some "inline" JavaScript which is actually not rendered inline, but either in the <head> or at the end of the body, based on the disposition.Given a Sitemesh layout like this:<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>
<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>
Linking to images with r:img
This tag is used to render<img> markup, using the Resources framework to process the resource on the fly (if configured to do so - e.g. make it eternally cacheable).This includes any extra attributes on the <img> tag if the resource has been previously declared in a module.With this mechanism you can specify the width, height and any other attributes in the resource declaration in the module, and they will be pulled in as necessary.Example:<html> <head> <title>Testing r:img</title> </head> <body> <r:img uri="/images/logo.png"/> </body> </html>
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.
6.2.5.2 Other resource tags
r:resource
This is equivalent to the Grails resource tag, returning a link to the processed static resource. Grails' owng: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.6.2.5.3 Declaring resources
A DSL is provided for declaring resources and modules. This can go either in yourConfig.groovy in the case of application-specific resources, or more commonly in a resources artefact in grails-app/conf.Note that you do not need to declare all your static resources, especially images. However you must to establish dependencies or other resources-specific attributes. Any resource that is not declared is called "ad-hoc" and will still be processed using defaults for that resource type.Consider this example resource configuration file, grails-app/conf/MyAppResources.groovy:modules = {
core {
dependsOn 'jquery, utils' resource url: '/js/core.js', disposition: 'head'
resource url: '/js/ui.js'
resource url: '/css/main.css',
resource url: '/css/branding.css'
resource url: '/css/print.css', attrs: [media: 'print']
} utils {
dependsOn 'jquery' resource url: '/js/utils.js'
} forms {
dependsOn 'core,utils' resource url: '/css/forms.css'
resource url: '/js/forms.js'
}
}bundle:'someOtherName' on each resource, or call defaultBundle on the module (see resources plugin documentation).It declares dependencies between them using dependsOn, which controls the load order of the resources.When you include an <r:require module="forms"/> in your GSP, it will pull in all the resources from '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.
6.2.5.4 Overriding plugin resources
Because a resource module can define the bundle groupings and other attributes of resources, you may find that the settings provided are not correct for your application.For example, you may wish to bundle jQuery and some other libraries all together in one file. There is a load-time and caching trade-off here, but often it is the case that you'd like to override some of these settings.To do this, the DSL supports an "overrides" clause, within which you can change thedefaultBundle setting for a module, or attributes of individual resources that have been declared with a unique id: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'
}
}
}6.2.5.5 Optimizing your resources
The Resources framework uses "mappers" to mutate the resources into the final format served to the user.The resource mappers are applied to each static resource once, in a specific order. You can create your own resource mappers, and several plugins provide some already for zipping, caching and minifying.Out of the box, the Resources plugin provides bundling of resources into fewer files, which is achieved with a few mappers that also perform CSS re-writing to handle when your CSS files are moved into a bundle.Bundling multiple resources into fewer files
The 'bundle' mapper operates by default on any resource with a "bundle" defined - or inherited from adefaultBundle clause on the module. Modules have an implicit default bundle name the same as the name of the module.Files of the same kind will be aggregated into this bundle file. Bundles operate across module boundaries: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'
}
}Making resources cache "eternally" in the client browser
Caching resources "eternally" in the client is only viable if the resource has a unique name that changes whenever the contents change, and requires caching headers to be set on the response.The cached-resources plugin provides a mapper that achieves this by hashing your files and renaming them based on this hash. It also sets the caching headers on every response for those resources. To use, simply install the cached-resources plugin.Note that the caching headers can only be set if your resources are being served by your application. If you have another server serving the static content from your app (e.g. Apache HTTPD), configure it to send caching headers. Alternatively you can configure it to request and proxy the resources from your container.Zipping resources
Returning gzipped resources is another way to reduce page load times and reduce bandwidth.The zipped-resources plugin provides a mapper that automatically compresses your content, excluding by 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.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.Adding the debug flag
If you add a query parameter _debugResources=y to your URL and request the page, Resources will bypass any processing so that you can see your original source files.This also adds a unique timestamp to all your resource URLs, to defeat any caching that browsers may use. This means that you should always see your very latest code when you reload the page.Turning on debug all the time
You can turn on the aforementioned debug mechanism without requiring a query parameter, but turning it on in Config.groovy:grails.resources.debug = true6.2.5.7 Preventing processing of resources
Sometimes you do not want a resource to be processed in a particular way, or even at all. Occasionally you may also want to disable all resource mapping.Preventing the application of a specific mapper to an individual resource
All resource declarations support a convention of noXXXX:true where XXXX is a mapper name.So for example to prevent the "hashandcache" mapper from being applied to a resource (which renames and moves it, potentially breaking relative links written in JavaScript code), you would do this:modules = {
forms {
resource url: '/css/forms.css', nohashandcache: true
resource url: '/js/forms.js', nohashandcache: true
}
}Excluding/including paths and file types from specific mappers
Mappers have includes/excludes Ant patterns to control whether they apply to a given resource. Mappers set sensible defaults for these based on their activity, for example the zipped-resources plugin's "zip" mapper is set to exclude images by default.You can configure this in yourConfig.groovy using the mapper name e.g:// We wouldn't link to .exe files using Resources but for the sake of example: grails.resources.zip.excludes = ['**/*.zip', '**/*.exe']// Perhaps for some reason we want to prevent bundling on "less" CSS files: grails.resources.bundle.excludes = ['**/*.less']
Controlling what is treated as an "ad-hoc" (legacy) resource
Ad-hoc resources are those undeclared, but linked to directly in your application without using the Grails or Resources linking tags (resource, img or external).These may occur with some legacy plugins or code with hardcoded paths in.There is a Config.groovy setting grails.resources.adhoc.patterns which defines a list of Servlet API compliant filter URI mappings, which the Resources filter will use to detect such "ad-hoc resource" requests.By default this is set to:grails.resources.adhoc.patterns = ['images/*', '*.js', '*.css']
6.2.5.8 Other Resources-aware plugins
At the time of writing, the following plugins include support for the Resources framework:6.2.6 Sitemesh Content Blocks
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>
<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>
6.2.7 Making Changes to a Deployed Application
One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires that you redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: thegrails.gsp.view.dir configuration setting.How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep them unpacked in a /var/www/grails/my-app directory. We add these two lines to grails-app/conf/Config.groovy :
grails.gsp.enable.reload = true grails.gsp.view.dir = "/var/www/grails/my-app/"
The 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
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 | Description | Default |
|---|---|---|
| grails.gsp.enable.reload | altervative system property for enabling the GSP reload mode without changing Config.groovy | |
| grails.gsp.reload.interval | interval between checking the lastmodified time of the gsp source file, unit is milliseconds | 5000 |
| grails.gsp.reload.granularity | the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times | 1000 |
6.2.8 GSP Debugging
Viewing the generated source code
- 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).
Debugging GSP code with a debugger
Viewing information about templates used to render a single url
GSP templates are reused in large web applications by using theg:render taglib. Several small templates can be used to render a single page.
It might be hard to find out what GSP template actually renders the html seen in the result.
The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the result in your browser.
"debugTemplates" is restricted to development mode. It won't work in production.Here is an example of comments added by debugTemplates :
<!-- GSP #2 START template: /home/.../views/_carousel.gsp
precompiled: false lastmodified: … -->
.
.
.
<!-- GSP #2 END template: /home/.../views/_carousel.gsp
rendering time: 115 ms -->6.3 Tag Libraries
Like Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, elegant and completely reloadable at runtime.
Como Java Server Pages (JSP), GSP soporta el concepto de librerias de etiquetas personalizadas. No como JSP, el mecanismo de la libreria de etiquetas de Grails es simple, elegante y completamente recargable en tiempo de ejecucion.
Quite simply, to create a tag library create a Groovy class that ends with the convention
Simplemente, para crear una libreria de etiquetas, crea una clase de Groovy que termine con la convencion TagLib and place it within the grails-app/taglib directory:
TagLib y coloquela dentro del directorio grails-app/taglib:class SimpleTagLib {}
Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:
Ahora para crear una etiqueta, crea un Closure de propiedad que tome dos argumentos: los atributos de la etiqueta y el contenido del cuerpo:class SimpleTagLib {
def simple = { attrs, body -> }
}
The
El argumento 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:
attrs es un Map de los atributos de la etiqueta, mientras que el argumento body es un Closure que regresa el contenido del cuerpo cuando es invocado:class SimpleTagLib {
def emoticon = { attrs, body ->
out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")
}
}
As demonstrated above there is an implicit
Como se demostro arriba, existe una variable implicita 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:
out que se refiere al output Writer el cual puede usar para agregar contenido a la respuesta. Entonces puede referenciar la etiqueta dentro de su GSP; no son necesarios los imports:<g:emoticon happy="true">Hi John</g:emoticon>
To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures withPara ayudar a los IDEs como SpringSource Tool Suite (STS) y otros para autocompletar los atributos de la etiqueta, deberia de agregar comentarios Javadoc a los closures de su etiqueta con las descripciones@attrdescriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.@attr. Desde que las taglibs usan codigo de Groovy puede ser dificil detectar de forma viable todos los atributos usables.For example:Por ejemplo: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.y cualquier atributo mandatorio debe de incluir la palabra reservada REQUIRED, por ejemplo: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) } }
6.3.1 Variables and Scopes
Within the scope of a tag library there are a number of pre-defined variables including:
Dentro del alcance de la libreria de etiquetas hay un numero de variables predefinidas incluidas:actionName- The currently executing action namecontrollerName- The currently executing controller nameflash- The flash objectgrailsApplication- The GrailsApplication instanceout- The response writer for writing to the output streampageScope- A reference to the pageScope object used for GSP rendering (i.e. the binding)params- The params object for retrieving request parameterspluginContextPath- The context path to the plugin that contains the tag libraryrequest- The HttpServletRequest instanceresponse- The HttpServletResponse instanceservletContext- The javax.servlet.ServletContext instancesession- The HttpSession instance
actionName- El nombre de la accion en ejecucion actualmentecontrollerName- El nombre del controlador en ejecucion actualmenteflash- El objeto flashgrailsApplication- La instancia GrailsApplicationout- El response writer para escribir hacia el output streampageScope- La referenica al objeto pageScope usado para el rendereo del GSP (ej. el binding)params- El objeto params para obtener los parametros de la peticionpluginContextPath- La ruta del contexto para el plugin que contiene la libreria de etiquetasrequest- La instancia HttpServletRequestresponse- La instancia HttpServletResponseservletContext- La instancia javax.servlet.ServletContextsession- La instancia HttpSession
6.3.2 Simple Tags
As demonstrated it the previous example it is easy to write simple tags that have no body and just output content. Another example is a
Como se demostro en el ejemplo anterior es facil de escribir etiquetas simples que no tengan cuerpo y solo contenido de salida. Otro ejemplo es la etiqueta de estilo dateFormat style tag:
dateFormat:def dateFormat = { attrs, body ->
out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}
The above uses Java's
El codigo de arriba usa la clase de Java SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a GSP as follows:
SimpleDateFormat para dar el formato a una fecha y entonces escribirla en la respuesta. La etiqueta puede entonces ser usada dentro del GSP como sigue:<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:
Con las etiquetas simples a veces necesitara escribir HTML mark-up en la respuesta. Una propuesta podria ser embeber el contenido directamente: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:
A pesar que este propuesta pueda ser tentativa, no es muy limpia. Una propuesta mejor seria el reusar la etiqueta render:def formatBook = { attrs, body ->
out << render(template: "bookTemplate", model: [book: attrs.book])
}
And then have a separate GSP template that does the actual rendering.
Y entonces tener una plantilla de GSP separada que haga el rendering actual.
6.3.3 Logical Tags
You can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:
Puede tambien crear etiquetas logicas donde el cuerpo de la etiqueta es solo salida una vez que un conjunto de condiciones hallan sido cumplidas. Un ejemplo de esto pueden ser un conjunto de etiquetas de seguridad:def isAdmin = { attrs, body ->
def user = attrs.user
if (user && checkUserPrivs(user)) {
out << body()
}
}
The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:
La etiqueta de arriba checa si el usario es un administrador y solo muestra el contenido del cuerpo si el/ella tiene el conjunto correcto de privilegios de acceso:<g:isAdmin user="${myUser}"> // some restricted content </g:isAdmin>
6.3.4 Iterative Tags
Iterative tags are easy too, since you can invoke the body multiple times:
Las etiquetas iterativas son tambien sencillas, pues puedes invocar el cuerpo multiples veces:def repeat = { attrs, body ->
attrs.times?.toInteger()?.times { num ->
out << body(num)
}
}
In this example we check for a
En este ejemplo podemos buscar el atributo times attribute and if it exists convert it to a number, then use Groovy's times method to iterate the specified number of times:
times y si existe convertirlo en un numero, entonces usar el metodo times de Groovy para iterar en un numero especifico de veces:<g:repeat times="3"> <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>
Notice how in this example we use the implicit
Note como en este ejemplo usamos la variable implicita 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:
it para referirnos al numero actual. Esto funciona porque cuando invocamos el cuerpo le pasamos el valor actual dentro de la iteracion:out << body(num)
That value is then passed as the default variable
Ese valor es pasado entonces como la 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:
it por defecto hacia la etiqueta. Sin embargo, si has anidado etiquetas esto puede ocasionar conflictos, asi que en ves deberia de nombrar las variables que el cuerpo usa: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
Aqui checamos si hay un atributo var attribute and if there is use that as the name to pass into the body invocation on this line:
var y si lo hay lo usamos como el nombre para pasarlo dentro de la invocacion del cuerpo en esta linea: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.
Note el uso del parentesis alrededor del nombre de la variable. Si usted omite esto Grovvy asume que esta usando una llave String y no se esta refiriendo a la variable.
Now we can change the usage of the tag as follows:
Ahora podemos cambiar el uso de la etiqueta como sigue:<g:repeat times="3" var="j"> <p>Repeat this 3 times! Current repeat = ${j}</p> </g:repeat>
Notice how we use the
Note como usamos el atributo 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.
var para definir el nombre de la variable j y entonces somos capaces de referenciar la variable dentro del cuerpo de la etiqueta.
6.3.5 Tag Namespaces
By default, tags are added to the default Grails namespace and are used with the
Por defecto, las etiquetas son añadidas en el espacio de nombres de Grails y son usadas con el prefijo g: prefix in GSP pages. However, you can specify a different namespace by adding a static property to your TagLib class:
g: en las paginas GSP. Sin embargo, puede especificar un espacio de nombres diferente añadiendo una propiedad estatica a su clase TagLib:class SimpleTagLib {
static namespace = "my" def example = { attrs ->
…
}
}
Here we have specified a
Aqui hemos especificado un namespace of my and hence the tags in this tag lib must then be referenced from GSP pages like this:
namespace de my y por lo tanto las etiquetas en esta libreria deben entonces ser referenciadas desde las paginas GSP asi:<my:example name="..." />
where the prefix is the same as the value of the static
Donde el prefijo es igual al valor de la propiedad estatica namespace property. Namespaces are particularly useful for plugins.
namespace. Los espacios de nombres son particularmente utiles para los plugins.
Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:
Las etiquetas dentro de los espacios de nombres pueden ser invocadas como metodos usando el espacio de nombre como prefijo para la llamada del metodo:out << my.example(name:"foo")
This works from GSP, controllers or tag libraries
Esto funciona desde GSP, controlladores o librerias de etiquetas.
6.3.6 Using JSP Tag Libraries
In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP to use with the
En adicion al mecanismo simplificado de librerias de etiquetas proveido por GSP, usted tambien puede usar etiquetas de JSP desde GSP. Para hacerlo simplemente declare el JSP que usara con la directiva taglib directive:
taglib:<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Then you can use it like any other tag:
Entonces podra usarla como cualquier otra etiqueta:<fmt:formatNumber value="${10}" pattern=".00"/>
With the added bonus that you can invoke JSP tags like methods:
Con el extra añadido que puede invocar etiquetas de JSP como metodos:${fmt.formatNumber(value:10, pattern:".00")}6.3.7 Tag return value
Since Grails 1.2, a tag library call returns an instance of
Desde Grails 1.2, una llamada a la libreria de etiquetas regresa una instancia de la clase org.codehaus.groovy.grails.web.util.StreamCharBuffer class by default.
This change improves performance by reducing object creation and optimizing buffering during request processing.
In earlier Grails versions, a java.lang.String instance was returned.
org.codehaus.groovy.grails.web.util.StreamCharBuffer por defecto.
Este cambio mejora el desempeño reduciendo la creacion de objetos y optimizando la carga durante el proceso de peticion.
En versiones anteriores de Grails, una instancia de java.lang.String era devuelta.
Tag libraries can also return direct object values to the caller since Grails 1.2..
Object returning tag names are listed in a static
Las librerias de etiquetas tambien pueden regresar valores directos de un objeto al que hace la peticion, desde Grails 1.2..
Nombres de etiquetas que regresan objetos son listados con la propiedad estatica returnObjectForTags property in the tag library class.
returnObjectForTags en la clase de la libreria de etiquetas.
Example:
Ejemplo:class ObjectReturningTagLib {
static namespace = "cms"
static returnObjectForTags = ['content'] def content = { attrs, body ->
CmsContent.findByCode(attrs.code)?.content
}
}6.4 URL Mappings
Throughout the documentation so far the convention used for URLs has been the default of
Hasta ahora a travez de la documentacion la convencion usada para las URLs ha sido for defecto /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.
/controller/action/id. Sin embargo, esta convencion no esta fuertemente ligada dentro de Grails y de hecho es controlada por la clase URL Mappings localizada en grails-app/conf/UrlMappings.groovy.
The
La clase UrlMappings class contains a single property called mappings that has been assigned a block of code:
UrlMappings contiene una unica propiedad llamada mappings que ha sido asignada a un bloque de codigo:class UrlMappings {
static mappings = {
}
}6.4.1 Mapping to Controllers and Actions
To create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:
Para crear un mapeo simple, simplemente use una URL relativa como el nombre del metodo y especifique los parametros nombrados para el controlador y la accion a mapear:"/product"(controller: "product", action: "list")
In this case we've mapped the URL
En este caso hemos mapeado la URL /product to the list action of the ProductController. Omit the action definition to map to the default action of the controller:
/product hacia la accion list del ProductController. Omitiendo la definicion de la accion a mapear hacia la accion por defecto del controllador:"/product"(controller: "product")
An alternative syntax is to assign the controller and action to use within a block passed to the method:
Una sintaxis alternativa es asignar el controlador y la accion a usar dentro del bloque pasado al metodo:"/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:
Cual sintaxis usar es enormemente dependiente en su preferencia personal. Para reescribir una URI en otra URI explicita (en vez del par controlador/accion) haga algo asi:"/hello"(uri: "/hello.dispatch")
Rewriting specific URIs is often useful when integrating with other frameworks
Reescribir URIs especificas es comunmente util cuando se integran con otros frameworks.
6.4.2 Embedded Variables
Simple Variables
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") }
id. For example given the URL /product/MacBook, the following code will render "MacBook" to the response:class ProductController {
def index() { render params.id }
}static mappings = { "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show") }
/graemerocher/2007/01/10/my_funky_blog_entry
year, month, day, id and so on.Dynamic Controller and Action Names
Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:static mappings = { "/$controller/$action?/$id?"() }
controller, action and id embedded within the URL.You can also resolve the controller name and action name to execute dynamically using a closure:static mappings = { "/$controller" { action = { params.goHere } } }
Optional Variables
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") }
/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/2007/01/10
/graemerocher/2007/01
/graemerocher/2007
/graemerocherArbitrary 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 }
Dynamically Resolved Variables
The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:"/holiday/win" { id = { params.id } isEligible = { session.user != null } // must be logged in }
6.4.3 Mapping to Views
You can resolve a URL to a view without a controller or action involved. For example to map the root URL
Puede resolver una URL hacia una vista sin un controlador o una accion involucrada. Por ejemplo para mapear la URL raiz / to a GSP at the location grails-app/views/index.gsp you could use:
/ hacia un GSP en la ruta grails-app/views/index.gsp podria usar:static mappings = { "/"(view: "/index") // map the root URL }
Alternatively if you need a view that is specific to a given controller you could use:
Alternativamente si necesita una vista que sea especifica a un controlador dado podria usar:static mappings = { "/help"(controller: "site", view: "help") // to a view for a controller }
6.4.4 Mapping to Response Codes
Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that matches the response code you are interested in:
Grails tambien le permite mapear codigos de respuesta HTTP hacia los controllers, actions o vistas. Solo use un nombre de metodo que empate el codigo de respuesta en el cual esta interesado:static mappings = { "403"(controller: "errors", action: "forbidden") "404"(controller: "errors", action: "notFound") "500"(controller: "errors", action: "serverError") }
Or you can specify custom error pages:
O puede especificar paginas de error personalizadas:static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(view: "/errors/serverError") }
Declarative Error Handling
Manejo Declarativo de Errores
In addition you can configure handlers for individual exceptions:
Ademas puede configurar los manejadores para excepciones individuales: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
Con esta configuracion, una 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.
IllegalArgumentException sera manejada por la accion illegalArgument en ErrorsController, una NullPointerException sera manejada por la accion nullPointer, y MyException sera manejada por la accion customException. Otras excepciones seran manejadas por la regla catch-all y usa la vista /errors/serverError.
You can access the exception from your custom error handing view or controller action using the request's
Puede acceder a la excepcion desde su vista de error personalizada o la accion del controlador usando el atributo exception attribute like so:
exception de la peticion de esta manera: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 aSi su accion del manejador de errores del controller arroja una excepcion tambien, terminara con unaStackOverflowException.StackOverflowException.
6.4.5 Mapping to HTTP methods
URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very useful for RESTful APIs and for restricting mappings based on HTTP method.
Los mapeos de URL tambien puede ser configurados para mapear basado en el metodo deh HTTP (GET, POST, PUT or DELETE). Esto es muy util para APIs de RESTful y para restringir mapeos basados en el metodo de HTTP.
As an example the following mappings provide a RESTful API URL mappings for the
Como ejemplo los siguientes mapeos proveen una RESTful API para mapeos de URL para el ProductController:
ProductController:static mappings = { "/product/$id"(controller:"product") { action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] } }
6.4.6 Mapping Wildcards
Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:
El mecanismo de mapeo de URL de Grails tambien soporta el mapeo de wildcards. Por ejemplo considere el siguiente mapeo:static mappings = { "/images/*.jpg"(controller: "image") }
This mapping will match all paths to images such as
Este mapeo empatara todas las rutas de imagenes tales como /image/logo.jpg. Of course you can achieve the same effect with a variable:
/image/logo.jpg. Por supuesto puede obtener el mismo efecto con la variable:static mappings = { "/images/$name.jpg"(controller: "image") }
However, you can also use double wildcards to match more than one level below:
Sin embargo, puede tambien usar dobles wildcards para empatar mas de un solo nivel abajo:static mappings = { "/images/**.jpg"(controller: "image") }
In this cases the mapping will match
En este caso el mapeo empatara /image/logo.jpg as well as /image/other/logo.jpg. Even better you can use a double wildcard variable:
/image/logo.jpg asi como /image/other/logo.jpg. Aun mejor puede usar la variable de doble wildcard: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
En este caso sera almacenada la ruta que empate con el wildcard dentro del parametro name parameter obtainable from the params object:
name obtenible desde el objeto params: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
Si usa el wildcard del mapeo de URL entonces querra excluir ciertas URIs del proceso de mapeo de URL de Grails. Para hacer esto puede proveer una setting excludes setting inside the UrlMappings.groovy class:
excludes dentro de la clase UrlMappings.groovy:class UrlMappings {
static excludes = ["/images/*", "/css/*"]
static mappings = {
…
}
}
In this case Grails won't attempt to match any URIs that start with
En este caso Grails no intentara de empatar ninguna URI que comience con /images or /css.
/images o /css.
6.4.7 Automatic Link Re-Writing
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.
Otra gran mejora del mapeo de URL es que se puede personalizar automaticamente el comportamiento de la etiqueta link asi que cambiar los mapeos no requiere de ir y cambiar todos sus enlaces.
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:
Esto es hecho a travez de la tecnica de reescritura de la URL que hace ingenieria inversa a los links de los mapeos de URL. Asi que dado un mapeo tal como el blog de la seccion anterior:static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
If you use the link tag as follows:
Si usted usa la etiqueta de enlance como sigue:<g:link controller="blog" action="show" params="[blog:'fred', year:2007]"> My Blog </g:link><g:link controller="blog" action="show" params="[blog:'fred', year:2007, month:10]"> My Blog - October 2007 Posts </g:link>
Grails will automatically re-write the URL in the correct format:
Grails automaticamente reescribira la URL en el formato correcto:<a href="/fred/2007">My Blog</a> <a href="/fred/2007/10">My Blog - October 2007 Posts</a>
6.4.8 Applying Constraints
URL Mappings also support Grails' unified validation constraints mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:
Los mapeos de URL tambien soportan el mecanismo unificado de Grails validation constraints, el cual permite ademas "restringir" como una URL es empatada. Por ejemplo: si volvemos al codigo de ejemplo del blog, el mapeo actualmente se ve asi:static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
This allows URLs such as:
Esto permite URLs tales como:/graemerocher/2007/01/10/my_funky_blog_entry
However, it would also allow:
Sin embargo, esto permitiria tambien:/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry
This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:
Esto es problematico por que lo obliga a hacer algun parseo inteligente en el codigo del controlador. Afortunadamente, los mapeos de URL pueden ser restringidos para ademas validar los tokens de la URL:"/$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
En este caso las restricciones se aseguran de que los parametros year, month and day parameters match a particular valid pattern thus relieving you of that burden later on.
year, month y day empaten con un patron particular valido asi relevandolo a usted de esa carga despues.
6.4.9 Named URL Mappings
URL Mappings also support named mappings, that is are mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.The syntax for defining a named mapping is as follows:static mappings = {
name <mapping name>: <url pattern> {
// …
}
}static mappings = { name personList: "/showPeople" { controller = 'person' action = 'list' } name accountDetails: "/details/$acctNumber" { controller = 'product' action = 'accountDetails' } }
<g:link mapping="personList">List People</g:link>
<a href="/showPeople">List People</a>
<g:link mapping="accountDetails" params="[acctNumber:'8675309']"> Show Account </g:link>
<a href="/details/8675309">Show Account</a>
<link:personList>List People</link:personList>
<a href="/showPeople">List People</a>
<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>
<a href="/details/8675309">Show Account</a>
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>
<a href="/details/8675309" class="fancy">Show Account</a>
6.5 Web Flow
Overview
Grails supports the creation of web flows built on the Spring Web Flow project. A web flow is a conversation that spans multiple requests and retains state for the scope of the flow. A web flow also has a defined start and end state.Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then restored using a flow execution key that Grails passes around as a request parameter. This makes flows far more scalable than other forms of stateful application that use the HttpSession and its inherit memory and clustering concerns.Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the 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 conventionFlow. For example:class BookController { def index() {
redirect(action: "shoppingCart")
} def shoppingCartFlow = {
…
}
}Flow suffix. In other words the name of the action of the above flow is shoppingCart.
6.5.1 Start and End States
As mentioned before a flow has a defined start and end state. A start state is the state which is entered when a user first initiates a conversation (or flow). The start state of a Grails flow is the first method call that takes a block. For example:
Como lo mencionamos antes, un flujo tiene definido un estado de inicio y final. Un estado de inicio es el estado en el cual se entra cuando un usuario primero inicia una conversacion (o un flujo). El estado de inicio de un flujo de Grails es la primera llamada al metodo que toma un bloque. Por ejemplo:class BookController {
…
def shoppingCartFlow ={
showCart {
on("checkout").to "enterPersonalDetails"
on("continueShopping").to "displayCatalogue"
}
…
displayCatalogue {
redirect(controller: "catalogue", action: "show")
}
displayInvoice()
}
}
Here the
Aqui el nodo 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.
showCart es el estado inicial del flujo. Desde que el estado showCart no define una accion o un redirect se asume que es un view state que, por convencion, se refiera a la vista grails-app/views/book/shoppingCart/showCart.gsp.
Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow:
Note que no como las acciones de un controller regular, las vistas son almacenadas dentro del directorio que empata con el nombre del flujo: grails-app/views/book/shoppingCart.
grails-app/views/book/shoppingCart.
The
El flujo 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.
shoppingCart tambien tiene dos estados finales posibles. El primero es displayCatalogue el cual se encarga de un redirect externo hacia otro controller y action, asi sale del flujo. El segundo es displayInvoice el cual es un estado final que no tiene ningun evento y simplemente desplegara una vista llamada grails-app/views/book/shoppingCart/displayInvoice.gsp miestras que termina el flujo al mismo tiempo.
Once a flow has ended it can only be resumed from the start state, in this case
Una vez que el flujo ha terminado, solo puede ser reanudado desde un estado de inicio, en este caso showCart, and not from any other state.
showCart, y no desde ningun otro estado.
6.5.2 Action States and View States
View states
A view state is a one that doesn't define anaction or a redirect. So for example this is a view state:enterPersonalDetails {
on("submit").to "enterShipping"
on("return").to "showCart"
}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"
}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"
}grails-app/views/shared/enterDetailsView.gspAction 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 theaction method and passing it a block of code to be executed:listBooks {
action {
[bookList: Book.list()]
}
on("success").to "showCatalogue"
on(Exception).to "handleError"
}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"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"
}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:enterPersonalDetails {
on("submit") {
log.trace "Going to enter shipping"
}.to "enterShipping"
on("return").to "showCart"
}submit event that simply logs the transition. Transition states are very useful for data binding and validation, which is covered in a later section.
6.5.3 Flow Execution Events
In order to transition execution of a flow from one state to the next you need some way of trigger an event that indicates what the flow should do next. Events can be triggered from either view states or action states.Triggering Events from a View State
As discussed previously the start state of the flow in a previous code listing deals with two possible events. Acheckout event and a continueShopping event:def shoppingCartFlow = {
showCart {
on("checkout").to "enterPersonalDetails"
on("continueShopping").to "displayCatalogue"
}
…
}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 action="shoppingCart"> <g:submitButton name="continueShopping" value="Continue Shopping" /> <g:submitButton name="checkout" value="Checkout" /> </g:form>
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 action="shoppingCart" event="checkout" />Triggering Events from an Action
To trigger an event from anaction you invoke a method. For example there is the built in error() and success() methods. The example below triggers the error() event on validation failure in a transition action:enterPersonalDetails {
on("submit") {
def p = new Person(params)
flow.person = p
if (!p.validate()) return error()
}.to "enterShipping"
on("return").to "showCart"
}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"
}6.5.4 Flow Scopes
Scope Basics
You'll notice from previous examples that we used a special object calledflow to store objects within "flow scope". Grails flows have five different scopes you can utilize:
request- Stores an object for the scope of the current requestflash- Stores the object for the current and next request onlyflow- Stores objects for the scope of the flow, removing them when the flow reaches an end stateconversation- Stores objects for the scope of the conversation including the root flow and nested subflowssession- Stores objects in the user's session
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"
}- Moves objects from flash scope to request scope upon transition between states;
- 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).
Flow Scopes and Serialization
When placing objects inflash, flow or conversation scope they must implement java.io.Serializable or an exception will be thrown. This has an impact on domain classes in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:class Book {
String title
}Book class in a flow scope you will need to modify it as follows:class Book implements Serializable { String title }
class Book implements Serializable { String title Author author }
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" } }
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" } }
class Book implements Serializable { String title def onLoad() { println "I'm loading" } }
6.5.5 Data Binding and Validation
In the section on start and end states, the start state in the first example triggered a transition to the
En la seccion de start and end states, el estado de inicio en el primer ejemplo dispara un transicion hacia el estado enterPersonalDetails state. This state renders a view and waits for the user to enter the required information:
enterPersonalDetails. Este estado renderea la vista y espera a que el usuario introduzca la informacion requerida:enterPersonalDetails {
on("submit").to "enterShipping"
on("return").to "showCart"
}
The view contains a form with two submit buttons that either trigger the submit event or the return event:
La vista contiene una forma con dos botones de enviar que cualquiera de los dos dispara el evento de enviar o el evento de retorno:
<g:form action="shoppingCart"> <!-- 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 to capture the form info we can use a flow transition action:
Sin embargo, ¿que hay de capturar la informacion enviada por la forma? Para obtener la informacion de la forma podemos usar una accion de flujo de transaccion: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
Note como se desarrolla el data binding desde los parametros de la peticion y coloca la instancia 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.
Person dentro del alcance flow. Tambien es interesante que desarrollamos validation e invocamos el metodo error() si la validacion falla. Esto avisa al flujo que la transicion debe ser detenida y regresar a la vista enterPersonalDetails y asi entradas validas pueden ser introducidas por el usuario, de otra manera la transicion debe continuar e ir al estado enterShipping.
Like regular actions, flow actions also support the notion of Command Objects by defining the first argument of the closure:
Como las acciones regulares, las acciones de flujo soportan la nocion de Command Objects definiendo el primer agurmento del closure:enterPersonalDetails {
on("submit") { PersonDetailsCommand cmd ->
flow.personDetails = cmd
!flow.personDetails.validate() ? error() : success()
}.to "enterShipping"
on("return").to "showCart"
}6.5.6 Subflows and Conversations
Grails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this search flow: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()
}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 likeThe subflow is another flow entirely:subflow(extendedSearchFlow), with the requirement that the name of the subflow state be the same as the called subflow (minusFlow). This way of calling a subflow is deprecated and only supported for backward compatibility.
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()
}extendedResults in conversation scope. This scope differs to flow scope as it lets you share state that spans the whole conversation not just the flow. Also notice that the end state (either moreResults or noResults of the subflow triggers the events in the main flow:extendedSearch {
// Extended search subflow
subflow(controller: "searchExtensions", action: "extendedSearch")
on("moreResults").to "displayMoreResults"
on("noResults").to "displayNoMoreResults"
}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.6.6.1 Applying Filters
To create a filter create a class that ends with the conventionFilters in the grails-app/conf directory. Within this class define a code block called filters that contains the filter definitions:class ExampleFilters {
def filters = {
// your filters here
}
}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
}- A controller and/or action name pairing with optional wildcards
- A URI, with Ant path matching syntax
controller- controller matching pattern, by default * is replaced with .* and a regex is compiledcontrollerExclude- controller exclusion pattern, by default * is replaced with .* and a regex is compiledaction- action matching pattern, by default * is replaced with .* and a regex is compiledactionExclude- action exclusion pattern, by default * is replaced with .* and a regex is compiledregex(true/false) - use regex syntax (don't replace '*' with '.*')uri- a uri to match, expressed with as Ant style path (e.g. /book/**)uriExclude- a uri pattern to exclude, expressed with as Ant style path (e.g. /book/**)find(true/false) - rule matches with partial match (seejava.util.regex.Matcher.find())invert(true/false) - invert the rule (NOT rule)
- All controllers and actions
all(controller: '*', action: '*') {}- Only for the
BookController
justBook(controller: 'book', action: '*') {}- All controllers except the
BookController
notBook(controller: 'book', invert: true) {}- All actions containing 'save' in the action name
saveInActionName(action: '*save*', find: true) {}- All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'
actionBeginningWithBButNotBad(action: 'b*', actionExclude: 'bad*', find: true) {}- Applied to a URI space
someURIs(uri: '/book/**') {}- Applied to all URIs
allURIs(uri: '/**') {}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.
6.6.2 Filter Types
Within the body of the filter you can then define one or several of the following interceptor types for the filter:before- Executed before the action. Returnfalseto indicate that the response has been handled that that all future filters and the action should not executeafter- Executed after an action. Takes a first argument as the view model to allow modification of the model before rendering the viewafterView- Executed after view rendering. Takes an Exception as an argument which will be non-nullif an exception occurs during processing. Note: this Closure is called before the layout is applied.
class SecurityFilters {
def filters = {
loginCheck(controller: '*', action: '*') {
before = {
if (!session.user && !actionName.equals('login')) {
redirect(action: 'login')
return false
}
}
}
}
}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.
6.6.3 Variables and Scopes
Filters support all the common properties available to controllers and tag libraries, plus the application context:- request - The HttpServletRequest object
- response - The HttpServletResponse object
- session - The HttpSession object
- servletContext - The ServletContext object
- flash - The flash object
- params - The request parameters object
- actionName - The action name that is being dispatched to
- controllerName - The controller name that is being dispatched to
- grailsApplication - The Grails application currently running
- applicationContext - The ApplicationContext object
6.6.4 Filter Dependencies
In aFilters class, you can specify any other Filters classes that should first be executed using the dependsOn property. This is used when a Filters class depends on the behavior of another Filters class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of Filters classes.Take the following example Filters classes:class MyFilters {
def dependsOn = [MyOtherFilters] def filters = {
checkAwesome(uri: "/*") {
before = {
if (request.isAwesome) { // do something awesome }
}
} checkAwesome2(uri: "/*") {
before = {
if (request.isAwesome) { // do something else awesome }
}
}
}
}class MyOtherFilters {
def filters = {
makeAwesome(uri: "/*") {
before = {
request.isAwesome = true
}
}
doNothing(uri: "/*") {
before = {
// do nothing
}
}
}
}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
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
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.6.7.1 Ajax Support
By default Grails ships with the jQuery library, but through the Plugin system provides support for other frameworks such as Prototype, Dojo:http://dojotoolkit.org/, Yahoo UI:http://developer.yahoo.com/yui/ and the Google Web Toolkit.This section covers Grails' support for Ajax in general. To get started, add this line to the<head> tag of your page:<g:javascript library="jquery" />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
6.7.1.1 Remoting Linking
Remote content can be loaded in a number of ways, the most commons way is through the remoteLink tag. This tag allows the creation of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The simplest way to create a remote link is as follows:<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>
delete action of the current controller with an id of 1.
6.7.1.2 Updating Content
This is great, but usually you provide feedback to the user about what happened:def delete() {
def b = Book.get(params.id)
b.delete()
render "Book ${b.id} was deleted"
}<div id="message"></div> <g:remoteLink action="delete" id="1" update="message"> Delete Book </g:remoteLink>
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>
error div will be updated if the request failed.
6.7.1.3 Remote Form Submission
An HTML form can also be submitted asynchronously in one of two ways. Firstly using the formRemote tag which expects similar attributes to those for the remoteLink tag:<g:formRemote url="[controller: 'book', action: 'delete']" update="[success: 'message', failure: 'error']"> <input type="hidden" name="id" value="1" /> <input type="submit" value="Delete Book!" /> </g:formRemote >
<form action="delete"> <input type="hidden" name="id" value="1" /> <g:submitToRemote action="delete" update="[success: 'message', failure: 'error']" /> </form>
6.7.1.4 Ajax Events
Specific JavaScript can be called if certain events occur, all the events start with the "on" prefix and let you give feedback to the user where appropriate, or take other action:<g:remoteLink action="show" id="1" update="success" onLoading="showProgress()" onComplete="hideProgress()">Show Book 1</g:remoteLink>
onSuccess- The JavaScript function to call if successfulonFailure- The JavaScript function to call if the call failedon_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 initialiseonLoading- The JavaScript function to call when the remote function is loading the responseonLoaded- The JavaScript function to call when the remote function is completed loading the responseonComplete- The JavaScript function to call when the remote function is complete, including any updates
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>
6.7.2 Ajax with Prototype
Grails features an external plugin to add Prototype support to Grails. To install the plugin type the following command from the root of your project in a terminal window:grails install-plugin prototype
<g:javascript library="prototype" /><g:javascript library="scriptaculous" />6.7.3 Ajax with Dojo
Grails features an external plugin to add Dojo support to Grails. To install the plugin type the following command from the root of your project in a terminal window:grails install-plugin dojo
<g:javascript library="dojo" />6.7.4 Ajax with GWT
Grails also features support for the Google Web Toolkit through a plugin. There is comprehensive documentation available on the Grails wiki.6.7.5 Ajax on the Server
There are a number of different ways to implement Ajax which are typically broken down into:- Content Centric Ajax - Where you just use the HTML result of a remote call to update the page
- Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page
- Script Centric Ajax - Where the server sends down a stream of JavaScript to be evaluated on the fly
Content Centric Ajax
Just to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by rendering a template with the render method:def showBook() {
def b = Book.get(params.id) render(template: "bookTemplate", model: [book: b])
}<g:remoteLink action="showBook" id="${book.id}" update="book${book.id}">Update Book</g:remoteLink><div id="book${book.id}"> <!--existing book mark-up --> </div>
Data Centric Ajax with JSON
Data Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a JSON response with Grails you would typically use Grails' JSON marshalling capability:import grails.converters.JSONdef showBook() {
def b = Book.get(params.id) render b as JSON
}<g:javascript> function updateBook(e) { var book = eval("("+e.responseText+")") // evaluate the JSON $("book" + book.id + "_title").innerHTML = book.title } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
Data Centric Ajax with XML
On the server side using XML is equally simple:import grails.converters.XMLdef showBook() {
def b = Book.get(params.id) render b as XML
}<g:javascript> function updateBook(e) { var xml = e.responseXML var id = xml.getElementsByTagName("book").getAttribute("id") $("book" + id + "_title") = xml.getElementsByTagName("title")[0].textContent } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
Script Centric Ajax with JavaScript
Script centric Ajax involves actually sending JavaScript back that gets evaluated on the client. An example of this can be seen below:def showBook() {
def b = Book.get(params.id) response.contentType = "text/javascript"
String title = b.title.encodeAsJavascript()
render "$('book${b.id}_title')='${title}'"
}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.Responding to both Ajax and non-Ajax requests
It's straightforward to have the same Grails controller action handle both Ajax and non-Ajax requests. Grails adds theisXhr() method to HttpServletRequest which can be used to identify Ajax requests. For example you could render a page fragment using a template for Ajax requests or the full page for regular HTTP requests:def listBooks() {
def books = Book.list(params)
if (request.xhr) {
render template: "bookTable", model: [books: books]
} else {
render view: "list", model: [books: books]
}
}6.8 Content Negotiation
Grails has built in support for Content negotiation using either the HTTPAccept header, an explicit format request parameter or the extension of a mapped URI.Configuring Mime Types
Before you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types withingrails-app/conf/Config.groovy using the grails.mime.types setting:grails.mime.types = [ xml: ['text/xml', 'application/xml'],
text: 'text-plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: 'text/json',
html: ['text/html','application/xhtml+xml']
]Content Negotiation using the Accept header
Every incoming HTTP request has a special Accept header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:*/*
Accept header):text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5
property to the response object that outlines the preferred response format. For the above example the following assertion would pass:assert 'html' == response.format
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
import grails.converters.XMLclass BookController { def list() { def books = Book.list() withFormat { html bookList: books js { render "alert('hello')" } xml { render books as XML } } } }
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.
Request format vs. Response format
As of Grails 2.0, there is a separate notion of the request format and the response format. The request format is dictated by theCONTENT_TYPE header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.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
}
}Content Negotiation with the format Request Parameter
If fiddling with request headers if not your favorite activity you can override the format used by specifying aformat request parameter:/book/list?format=xml
"/book/list"(controller:"book", action:"list") { format = "xml" }
Content Negotiation with URI Extensions
Grails also supports content negotiation using URI extensions. For example given the following URI:/book/list.xml
/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 = falseTesting Content Negotiation
To test content negotiation in a unit or integration test (see the section on Testing) you can either manipulate the incoming request headers:void testJavascriptOutput() {
def controller = new TestController()
controller.request.addHeader "Accept",
"text/javascript, text/html, application/xml, text/xml, */*" controller.testAction()
assertEquals "alert('hello')", controller.response.contentAsString
}void testJavascriptOutput() {
def controller = new TestController()
controller.params.format = 'js' controller.testAction()
assertEquals "alert('hello')", controller.response.contentAsString
}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.
La capacidad de validacion de Grails esta integrada en Spring's Validator API y en las capacidades de data binding. Sin embargo Grails lleva esto mas alla y provee una forma unificada para definir la validacion de "restricciones" con su propio mecanismo de restricciones.
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.
Las restricciones en Grails son una forma de especificar reglas de validacion declarativamente. Comunmente son aplicadas a domain classes, sin embargo URL Mappings y Command Objects tambien soportan restricciones.
7.1 Declaring Constraints
Within a domain class constraints are defined with the constraints property that is assigned a code block:class User {
String login
String password
String email
Integer age static constraints = {
…
}
}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
}
}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). The same is not true for command object properties, which are nullable by default.
A complete reference for the available constraints can be found in the Quick Reference section under the Constraints heading.A word of warning - referencing domain class properties from constraints
It's very easy to attempt to reference instance variables from the static constraints block, but this isn't legal in Groovy (or Java). If you do so, you will get aMissingPropertyException for your trouble. For example, you may try
class Response {
Survey survey
Answer answer static constraints = {
survey blank: false
answer blank: false, inList: survey.answers
}
}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 }
}
}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.
7.2 Validating Constraints
Validation Basics
Basicos de Validacion
Call the validate method to validate a domain class instance:
Llame al metodo validate para validar la instancia de una clase de dominio:def user = new User(params)if (user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }
The
La propiedad 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.
errors en las clases de dominio es una instancia de la interfaz Errors de Spring. La interfaz Errors provee metodos para navegar por los errores de validacion y tambien obtener los valores originales.Validation Phases
Fases de Validacion
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:
Dentro de Grails existen dos fases de validacion, la primera siendo data binding la cual ocurre cuando se ligan los parametros de la peticion dentro de una instancia tal como:def user = new User(params)
At this point you may already have errors in the
En este punto puede ya haber errores en la propiedad 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:
errors por el tipo de conversion (tal como convertir cadenas en fechas). Puede checar estos y obtener el valor original que se introdujo usando la API de Errors: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
La segunda fase de validacion ocurre cuando se llama a validate o save. Aqui es cuando Grails validara los valores obligados contra las constraints que usted definio. Por ejemplo, por defecto el metodo save llama a validate before executing, allowing you to write code like:
validate antes de ejecutarlo, permitiendole escribir codigo como:if (user.save()) { return user } else { user.errors.allErrors.each { println it } }
7.3 Validation on the Client
Displaying Errors
Typically if you get a validation error you redirect back to the view for rendering. Once there you need some way 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}" /><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>
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.Retrieving Input Values
Each error is actually an instance of the FieldError class in Spring, which retains the original input value within it. This is useful as you can use the error object to restore the value input by the user using the fieldValue tag:<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>FieldError in the User bean and if there is obtain the originally input value for the login field.
7.4 Validation and Internationalization
Another important thing to note about errors in Grails is that error messages are not hard coded anywhere. The FieldError class in Spring resolves messages from message bundles using Grails' i18n support.Constraints and Message Codes
The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:package com.mycompany.myappclass 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 } }
[Class Name].[Property Name].[Constraint Code]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!
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>
error argument to read the message for the given error.
7.5 Validation Non Domain and Command Object Classes
Domain classes and command objects support validation by default. Other classes may be made validateable by defining the staticconstraints 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.The Validateable Annotation
Classes which define the staticconstraints property and are annotated with @Validateable can be made validateable by the framework. Consider this example:// src/groovy/com/mycompany/myapp/User.groovy package com.mycompany.myappimport grails.validation.Validateable@Validateable class User { ... static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }
Registering Validateable Classes
If a class is not marked withValidateable, it may still be made validateable by the framework. The steps required to do this are to define the static constraints property in the class (as described above) and then telling the framework about the class by assigning a value to the grails.validateable.classes property in Config.groovy@:grails.validateable.classes = [com.mycompany.myapp.User, com.mycompany.dto.Account]
8 The Service Layer
Grails defines the notion of a service layer. The Grails team discourages the embedding of core application logic inside controllers, as it does not promote reuse and a clean separation of concerns.Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.Creating a Service
You can create a Grails service by running the create-service command from the root of your project in a terminal 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 helloworldclass SimpleService {
}8.1 Declarative Transactions
Default Declarative Transactions
Services are typically involved with coordinating logic between domain classes, and hence often involved with persistence that spans large operations. Given the nature of services, they frequently require transactional behaviour. You can use programmatic transactions with the withTransaction method, however this is repetitive and doesn't fully leverage the power of Spring's underlying transaction abstraction.Services enable transaction demarcation, which is a declarative way of defining which methods are to be made transactional. All services are transactional by default. To disable this set thetransactional property to false:class CountryService {
static transactional = false
}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 theThe 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 extendsnewoperator such asnew BookService()
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.
Custom Transaction Configuration
Grails also fully supports Spring'sTransactional annotation for cases where you need more fine-grained control over transactions at a per-method level or need specify an alternative propagation level.Annotating a service method withIn this exampleTransactionaldisables the default Grails transactional behavior for that service (in the same way that addingtransactional=falsedoes) so if you use any annotations you must annotate all methods that require transactions.
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.Transactionalclass BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } @Transactional def updateBook() { // … } def deleteBook() { // … } }
transactional=true):import org.springframework.transaction.annotation.Transactional@Transactional
class BookService { def listBooks() {
Book.list()
} def updateBook() {
// …
} def deleteBook() {
// …
}
}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() { // … } }
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.
8.1.1 Transactions Rollback and the Session
Understanding Transactions and the Hibernate Session
When using transactions there are important considerations you must take into account with regards to how the underlying persistence session is handled by Hibernate. When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any objects within the session become detached and accessing uninitialized lazy-loaded collections will lead toLazyInitializationExceptions.To understand why it is important that the Hibernate session is cleared. Consider the following example:class Author {
String name
Integer age static hasMany = [books: Book]
}Author.withTransaction { status ->
new Author(name: "Stephen King", age: 40).save()
status.setRollbackOnly()
}Author.withTransaction { status ->
new Author(name: "Stephen King", age: 40).save()
}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}"
}
}
}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"]])
...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
}
}
}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}"
}
}
}Validation Errors and Rollback
A common use case is to rollback a transaction if there are validation errors. For example consider this service:import grails.validation.ValidationExceptionclass AuthorService { void updateAge(id, int age) { def author = Author.get(id) author.age = age if (!author.validate()) { throw new ValidationException("Author is not valid", author.errors) } } }
import grails.validation.ValidationExceptionclass 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] } } }
8.2 Scoped Services
By default, access to service methods is not synchronised, so nothing prevents concurrent execution of those methods. In fact, because the service is a singleton and may be used concurrently, you should be very careful about storing state in a service. Or take the easy (and better) road and never store state in a service.You can change this behaviour by placing a service in a particular scope. The supported scopes are:prototype- A new service is created every time it is injected into another classrequest- A new service will be created per requestflash- A new service will be created for the current and next request onlyflow- In web flows the service will exist for the scope of the flowconversation- In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flowssession- A service is created for the scope of a user sessionsingleton(default) - Only one instance of the service ever exists
If your service isTo enable one of the scopes, add a static scope property to your class whose value is one of the above, for exampleflash,floworconversationscoped it must implementjava.io.Serializableand can only be used in the context of a Web Flow
static scope = "flow"
8.3 Dependency Injection and Services
Dependency Injection Basics
A key aspect of Grails services is the ability to use Spring Framework's dependency injection features. Grails supports "dependency injection by convention". In other words, you can use the property name representation of the class name of a service to automatically inject them into controllers, tag libraries, and so on.As an example, given a service calledBookService, if you define a property called bookService in a controller as follows:class BookController {
def bookService
…
}class AuthorService {
BookService bookService
}NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of theBookServiceclass would map to a property namedbookService.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 theJDBCHelperServiceclass would beJDBCHelperService, notjDBCHelperServiceorjdbcHelperService.See section 8.8 of the JavaBean specification for more information on de-capitalization rules.
Dependency Injection and Services
You can inject services in other services with the same technique. If you had anAuthorService that needed to use the BookService, declaring the AuthorService as follows would allow that:class AuthorService {
def bookService
}Dependency Injection and Domain Classes / Tag Libraries
You can even inject services into domain classes and tag libraries, which can aid in the development of rich domain models and views:class Book {
…
def bookService def buyBook() {
bookService.buyBook(this)
}
}8.4 Using Services from Java
One of the powerful things about services is that since they encapsulate re-usable logic, you can use them from other classes, including Java classes. There are a couple of ways you can reuse a service from Java. The simplest way is to move your service into a package within thegrails-app/services directory. The reason this is important is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the BookService below cannot be used from Java as it stands:class BookService {
void buyBook(Book book) {
// logic
}
}grails-app/services/bookstore and then modifying the package declaration:package bookstoreclass BookService {
void buyBook(Book book) {
// logic
}
}package bookstoreinterface BookStore { void buyBook(Book book) }
class BookService implements bookstore.BookStore {
void buyBook(Book b) {
// logic
}
}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; } … }
grails-app/conf/spring/resources.xml (for more information see the section on Grails and Spring):<bean id="bookConsumer" class="bookstore.BookConsumer"> <property name="bookStore" ref="bookService" /> </bean>
grails-app/conf/spring/resources.groovy:import bookstore.BookConsumerbeans = { bookConsumer(BookConsumer) { bookStore = ref("bookService") } }
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-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 isTestsbut as of Grails 1.2.2, the suffix ofTestis also supported.
Running Tests
Test are run with the test-app command:grails test-app
grails … test-app
test-app command will produce output such as:------------------------------------------------------- Running Unit Tests… Running test FooTests...FAILURE Unit Tests Completed in 464ms … -------------------------------------------------------Tests failed: 0 errors, 1 failures
target/test-reports directory.You can force a clean before running tests by passing-cleanto thetest-appcommand.
Targeting Tests
You can selectively target the test(s) to be run in different ways. To run all tests for a controller namedSimpleController you would run:grails test-app SimpleController
SimpleController. Wildcards can be used...grails test-app *Controller
Controller. Package names can optionally be specified...grails test-app some.org.*Controller
grails test-app some.org.*
grails test-app some.org.**.*
grails test-app SimpleController.testLogin
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
Targeting Test Types and/or Phases
In addition to targeting certain tests, you can also target test types and/or phases by using thephase:type syntax.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 (To execute the JUnitunit,integration,functionalandother) and JUnit test types for theunitandintegrationphases. 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.
integration tests you can run:grails test-app integration:integration
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:
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
functional phase you would run...grails test-app functional:spock
grails test-app unit:spock integration:spock
Targeting Tests in Types and/or Phases
Test and type/phase targetting can be applied at the same time:grails test-app integration: unit: some.org.**.*
integration and unit phases that are in the package some.org or a subpackage.
9.1 Unit Testing
Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without consideration for surrounding infrastructure. Unit tests are typically run without the presence of physical resources that involve I/O such databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important.Since Grails 2.0, a collection of unit testing mixins is provided by Grails that lets you enhance the behavior of a typical JUnit 3, JUnit 4 or Spock test. The following sections cover the usage of these mixins.
The previous JUnit 3-style GrailsUnitTestCase class hierarchy is still present in Grails for backwards compatibility, but is now deprecated. The previous documentation on the subject can be found in the Grails 1.3.x documentation
9.1.1 Unit Testing Controllers
The Basics
You use thegrails.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() { }
}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"
}
}void testHello() {
controller.hello() assert response.text == 'hello'
}response object is an instance of org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletResponse which extends Spring's org.springframework.mock.web.MockHttpServletResponse and has a number of useful methods for inspecting the state of the response.For example to test a redirect you can use the redirectUrl property:// Test class
class SimpleController {
def index() {
redirect action: 'hello'
}
…
}void testIndex() {
controller.index() assert response.redirectedUrl == '/simple/hello'
}Testing View Rendering
To test view rendering you can inspect the state of the controller'smodelAndView property (an instance of org.springframework.web.servlet.ModelAndView) or you can use the view and model properties provided by the mixin:// Test class
class SimpleController {
def home() {
render view: "homePage", model: [title: "Hello World"]
}
…
}void testIndex() {
controller.home() assert view == "/simple/homePage"
assert model.title == "Hello World"
}Testing Template Rendering
Unlike view rendering, template rendering will actually attempt to write the template directly to the response rather than returning aModelAndView hence it requires a different approach to testing.Consider the following controller action:class SimpleController {
def display() {
render template:"snippet"
}
}grails-app/views/simple/_snippet.gsp. You can test this as follows:void testDisplay() {
controller.display()
assert response.text == 'contents of template'
}void testDisplay() {
views['/simple/_snippet.gsp'] = 'mock contents'
controller.display()
assert response.text == 'mock contents'
}Testing XML and JSON Responses
XML and JSON response are also written directly to the response. Grails' mocking capabilities provide some conveniences for testing XML and JSON response. For example consider the following action:def renderXml() {
render(contentType:"text/xml") {
book(title:"Great")
}
}xml property of the response:void testRenderXml() {
controller.renderXml()
assert "<book title='Great'/>" == response.text
assert "Great" == response.xml.@title.text()
}xml property is a parsed result from Groovy's XmlSlurper class which is very convenient for parsing XML.Testing JSON responses is pretty similar, instead you use the json property:// controller action
def renderJson() {
render(contentType:"text/json") {
book = "Great"
}
}// test
void testRenderJson() { controller.renderJson() assert '{"book":"Great"}' == response.text
assert "Great" == response.json.book
}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.Testing XML and JSON Requests
Grails provides various convenient ways to automatically parse incoming XML and JSON packets. For example you can bind incoming JSON or XML requests using Grails' data binding:def consumeBook() {
def b = new Book(params['book']) render b.title
}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'
}void testConsumeBookXml() {
request.xml = new Book(title:"The Shining")
controller.consumeBook() assert response.text == 'The Shining'
}void testConsumeBookJson() {
request.json = new Book(title:"The Shining")
controller.consumeBook() assert response.text == 'The Shining'
}def consume() {
request.withFormat {
xml {
render request.XML.@title
}
json {
render request.JSON.title
}
}
}void testConsumeXml() {
request.xml = '<book title="The Stand" />' controller.consume() assert response.text == 'The Stand'
}void testConsumeJson() {
request.json = '{title:"The Stand"}'
controller.consume() assert response.text == 'The Stand'
}Testing Spring Beans
When usingTestFor only a subset of the Spring beans available to a running Grails application are available. If you wish to make additional beans available you can do so with the defineBeans method of GrailsUnitTestMixin:class SimpleController {
SimpleService simpleService
def hello() {
render simpleService.sayHello()
}
}void testBeanWiring() {
defineBeans {
simpleService(SimpleService)
} controller.hello() assert response.text == "Hello World"
}void testAutowiringViaNew() {
defineBeans {
simpleService(SimpleService)
} def controller1 = new SimpleController()
def controller2 = new SimpleController() assert controller1.simpleService != null
assert controller2.simpleService != null
}Testing Mime Type Handling
You can test mime type handling and thewithFormat method quite simply by setting the response's format attribute:// controller action
def sayHello() {
def data = [Hello:"World"]
withFormat {
xml { render data as XML }
html data
}
}// test
void testSayHello() {
response.format = 'xml'
controller.sayHello() String expected = '<?xml version="1.0" encoding="UTF-8"?>' +
'<map><entry key="Hello">World</entry></map>' assert expected == response.text
}Testing Duplicate Form Submissions
Testing duplicate form submissions is a little bit more involved. For example if you have an action that handles a form such as:def handleForm() {
withForm {
render "Good"
}.invalidToken {
render "Bad"
}
}void testDuplicateFormSubmission() {
controller.handleForm()
assert "Bad" == response.text
}SynchronizerToken:import org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerToken ...void testValidFormSubmission() { def token = SynchronizerToken.store(session) params[SynchronizerToken.KEY] = token.currentToken.toString() controller.handleForm() assert "Good" == response.text }
controller.handleForm() // first execution … response.reset() … controller.handleForm() // second execution
Testing File Upload
You use theGrailsMockMultipartFile class to test file uploads. For example consider the following controller action:def uploadFile() {
MultipartFile file = request.getFile("myFile")
file.transferTo(new File("/local/disk/myFile"))
}GrailsMockMultipartFile with the request:void testFileUpload() {
final file = new GrailsMockMultipartFile("myFile", "foo".bytes)
request.addFile(file)
controller.uploadFile() assert file.targetFileLocation.path == "/local/disk/myFile"
}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.Testing Command Objects
Special support exists for testing command object handling with themockCommandObject method. For example consider the following action:def handleCommand(SimpleCommand simple) {
if (simple.hasErrors()) {
render "Bad"
}
else {
render "Good"
}
}void testInvalidCommand() {
def cmd = mockCommandObject(SimpleCommand)
cmd.name = '' // doesn't allow blank names cmd.validate()
controller.handleCommand(cmd) assert response.text == 'Bad'
}Testing Calling Tag Libraries
You can test calling tag libraries usingControllerUnitTestMixin, although the mechanism for testing the tag called varies from tag to tag. For example to test a call to the message tag, add a message to the messageSource. Consider the following action:def showMessage() {
render g.message(code: "foo.bar")
}void testRenderBasicTemplateWithTags() {
messageSource.addMessage("foo.bar", request.locale, "Hello World") controller.showMessage() assert response.text == "Hello World"
}9.1.2 Unit Testing Tag Libraries
The Basics
Tag libraries and GSP pages can be tested with thegrails.test.mixin.web.GroovyPageUnitTestMixin mixin. To use the mixin declare which tag library is under test with the TestFor annotation:@TestFor(SimpleTagLib)
class SimpleTagLibTests {}ControllerUnitTestMixin and the GroovyPageUnitTestMixin using the Mock annotation:@TestFor(SimpleController)
@Mock(SimpleTagLib)
class GroovyPageUnitTestMixinTests {}Testing Custom Tags
The core Grails tags don't need to be enabled during testing, however custom tag libraries do. TheGroovyPageUnitTestMixin class provides a mockTagLib() method that you can use to mock a custom tag library. For example consider the following tag library:class SimpleTagLib { static namespace = 's' def hello = { attrs, body ->
out << "Hello ${attrs.name ?: 'World'}"
}
}TestFor and supplying the name of the tag library:@TestFor(SimpleTagLib)
class SimpleTagLibTests {
void testHelloTag() {
assert applyTemplate('<s:hello />') == 'Hello World'
assert applyTemplate('<s:hello name="Fred" />') == 'Hello Fred'
}
}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) …
}
}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" />')
}
}Testing View and Template Rendering
You can test rendering of views and templates ingrails-app/views via the render(Map) method provided by GroovyPageUnitTestMixin :def result = render(template: "/simple/hello") assert result == "Hello World"
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.
9.1.3 Unit Testing Domains
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
DomainClassUnitTestMixin including:
- Simple persistence methods like
save(),delete()etc. - Dynamic Finders
- Named Queries
- Query-by-example
- GORM Events
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 {}SimpleController class and mocks the behavior of the Simple domain class as well. For example consider a typical scaffolded save controller action:class BookController {
def save() {
def book = new Book(params)
if (book.save(flush: true)) {
flash.message = message(
code: 'default.created.message',
args: [message(code: 'book.label',
default: 'Book'), book.id])}"
redirect(action: "show", id: book.id)
}
else {
render(view: "create", model: [bookInstance: book])
}
}
}import grails.test.mixin.*@TestFor(BookController) @Mock(Book) class BookControllerTests { void testSaveInvalidBook() { controller.save() assert model.bookInstance != null assert view == '/book/create' } void testSaveValidBook() { params.title = "The Stand" params.pages = "500" controller.save() assert response.redirectedUrl == '/book/show/1' assert flash.message != null assert Book.count() == 1 } }
Mock annotation also supports a list of mock collaborators if you have more than one domain to mock:@TestFor(BookController)
@Mock([Book, Author])
class BookControllerTests {
…
}DomainClassUnitTestMixin directly with the TestMixin annotation:@TestFor(BookController)
@TestMixin(DomainClassUnitTestMixin)
class BookControllerTests {
…
}mockDomain method to mock domains during your test:void testSave() {
mockDomain(Author)
mockDomain(Book)
}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 defaultsave() 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
}
}@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()
}
}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.
9.1.4 Unit Testing Filters
Unit testing filters is typically a matter of testing a controller where a filter is a mock collaborator. For example consider the following filters class:class CancellingFilters {
def filters = {
all(controller:"simple", action:"list") {
before = {
redirect(controller:"book")
return false
}
}
}
}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 {}withFilters method to wrap the call to an action in filter execution:void testInvocationOfListActionIsFiltered() {
withFilters(action:"list") {
controller.list()
}
assert response.redirectedUrl == '/book'
}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() }
9.1.5 Unit Testing URL Mappings
The Basics
Testing URL mappings can be done with theTestFor annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following:@TestFor(UrlMappings)
class UrlMappingsTests {}
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:
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 actionassertUrlMapping- Asserts a URL mapping is valid for the given URL. This combines theassertForwardUrlMappingandassertReverseUrlMappingassertions
Asserting Forward URL Mappings
You useassertForwardUrlMapping to assert that a given URL maps to a given controller. For example, consider the following URL mappings:static mappings = { "/action1"(controller: "simple", action: "action1") "/action2"(controller: "simple", action: "action2") }
void testUrlMappings() { assertForwardUrlMapping("/action1", controller: 'simple',
action: "action1") assertForwardUrlMapping("/action2", controller: 'simple',
action: "action2") shouldFail {
assertForwardUrlMapping("/action2", controller: 'simple',
action: "action1")
}
}Assert Reverse URL Mappings
You useassertReverseUrlMapping to check that correct links are produced for your URL mapping when using the link tag in GSP views. An example test is largely identical to the previous listing except you use assertReverseUrlMapping instead of assertForwardUrlMapping. Note that you can combine these 2 assertions with assertUrlMapping.Simulating Controller Mapping
In addition to the assertions to check the validity of URL mappings you can also simulate mapping to a controller by using yourUrlMappings as a mock collaborator and the mapURI method. For example:@TestFor(SimpleController)
@Mock(UrlMappings)
class SimpleControllerTests { void testControllerMapping() { SimpleController controller = mapURI('/simple/list')
assert controller != null def model = controller.list()
assert model != null
}
}9.1.6 Mocking Collaborators
Beyond the specific targeted mocking APIs there is also an all-purposemockFor() method that is available when using the TestFor annotation. The signature of mockFor is:mockFor(class, loose = false)def strictControl = mockFor(MyService)
strictControl.demand.someMethod(0..2) { String arg1, int arg2 -> … }
strictControl.demand.static.aStaticMethod {-> … }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)9.2 Integration Testing
Integration tests differ from unit tests in that you have full access to the Grails environment within the test. Grails uses an in-memory H2 database for integration tests and clears out all the data from the database between tests.One thing to bear in mind is that logging is enabled for your application classes, but it is different from logging in tests. So if you have something like this:class MyServiceTests extends GroovyTestCase { void testSomething() { log.info "Starting tests" … } }
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 atransactional property to your test class to check transactional behaviour:class MyServiceTests extends GroovyTestCase { static transactional = false void testMyTransactionalServiceMethod() { … } }
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:class FooController { def text() {
render "bar"
} def someRedirect() {
redirect(action:"bar")
}
}class FooControllerTests extends GroovyTestCase { void testText() { def fc = new FooController() fc.text() assertEquals "bar", fc.response.contentAsString } void testSomeRedirect() { def fc = new FooController() fc.someRedirect() assertEquals "/foo/bar", fc.response.redirectedUrl } }
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.Testing Controllers with Services
If your controller references a service (or other Spring beans), you have to explicitly initialise the service from your test.Given a controller using a service:class FilmStarsController {
def popularityService def update() {
// do something with popularityService
}
}class FilmStarsTests extends GroovyTestCase { def popularityService void testInjectedServiceInController () { def fsc = new FilmStarsController() fsc.popularityService = popularityService fsc.update() } }
Testing Controller Command Objects
With command objects you just supply parameters to the request and it will automatically do the command object work for you when you call your action with no parameters:Given a controller using a command object:class AuthenticationController {
def signup(SignupForm form) {
…
}
}def controller = new AuthenticationController() controller.params.login = "marcpalmer" controller.params.password = "secret" controller.params.passwordConfirm = "secret" controller.signup()
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.Testing Controllers and the render Method
The render method lets you render a custom view at any point within the body of an action. For instance, consider the example below:def save() {
def book = Book(params)
if (book.save()) {
// handle
}
else {
render(view:"create", model:[book:book])
}
}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.bookSimulating Request Data
You can use the Spring MockHttpServletRequest to test an action that requires request data, for example a REST web service. For example consider this action which performs data binding from an incoming request:def create() {
[book: new Book(params.book)]
}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
}void testCreateWithJSON() { def controller = new BookController() controller.request.contentType = "text/json"
controller.request.content =
'{"id":1,"class":"Book","title":"The Stand"}'.getBytes() def model = controller.create()
assert model.book
assertEquals "The Stand", model.book.title
}With JSON don't forget theFor more information on the subject of REST web services see the section on REST.classproperty 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.
Testing Web Flows
Testing Web Flows requires a special test harness calledgrails.test.WebFlowTestCase which subclasses Spring Web Flow's AbstractFlowExecutionTests class.
Subclasses of WebFlowTestCase must be integration tests
For example given this simple flow:class ExampleController { def exampleFlow() {
start {
on("go") {
flow.hello = "world"
}.to "next"
}
next {
on("back").to "start"
on("go").to "subber"
}
subber {
subflow(action: "sub")
on("end").to("end")
}
end()
} def subFlow() {
subSubflowState {
subflow(controller: "other", action: "otherSub")
on("next").to("next")
}
…
}
}getFlow
method:import grails.test.WebFlowTestCaseclass ExampleFlowTests extends WebFlowTestCase { def getFlow() { new ExampleController().exampleFlow } … }
getFlowId method, otherwise the default is test:
import grails.test.WebFlowTestCaseclass ExampleFlowTests extends WebFlowTestCase { String getFlowId() { "example" } … }
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) }
startFlow method:void testExampleFlow() {
def viewSelection = startFlow()
…
}signalEvent method to trigger an event:void testExampleFlow() {
…
signalEvent("go")
assert "next" == flowExecution.activeSession.state.id
assert "world" == flowScope.hello
}hello variable into the flow scope.Testing Tag Libraries
Testing tag libraries is simple because when a tag is invoked as a method it returns its result as a string (technically aStreamCharBuffer but this class implements all of the methods of String). So for example if you have a tag library like this:class FooTagLib { def bar = { attrs, body ->
out << "<p>Hello World!</p>"
} def bodyTag = { attrs, body ->
out << "<${attrs.name}>"
out << body()
out << "</${attrs.name}>"
}
}class FooTagLibTests extends GroovyTestCase { void testBarTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bar(null, null).toString() } void testBodyTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bodyTag(name: "p") { "Hello World!" }.toString() } }
testBodyTag, we pass a block that returns the body of the tag. This is convenient to representing the body as a String.Testing Tag Libraries with GroovyPagesTestCase
In addition to doing simple testing of tag libraries like in the above examples, you can also use thegrails.test.GroovyPagesTestCase class to test tag libraries with integration tests.The GroovyPagesTestCase class is a subclass of the standard GroovyTestCase class and adds utility methods for testing the output of GSP rendering.
GroovyPagesTestCase can only be used in an integration test.
For example, consider this date formatting tag library:import java.text.SimpleDateFormatclass FormatTagLib { def dateFormat = { attrs, body -> out << new SimpleDateFormat(attrs.format) << attrs.date } }
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]) } }
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 } }
Testing Domain Classes
Testing domain classes is typically a simple matter of using the GORM API, but there are a few things to be aware of. Firstly, when testing queries you often need to "flush" to ensure the correct state has been persisted to the database. For example take the following example:void testQuery() {
def books = [
new Book(title: "The Stand"),
new Book(title: "The Shining")]
books*.save() assertEquals 2, Book.list().size()
}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()
}flush with a value of true the updates will be persisted immediately and hence will be available to the query later on.
9.3 Functional Testing
Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. Grails does not ship with any support for writing functional tests directly, but there are several plugins available for this.Canoo Webtest- http://grails.org/plugin/webtestG-Func- http://grails.org/plugin/functional-testGeb- http://grails.org/plugin/gebSelenium-RC- http://grails.org/plugin/selenium-rcWebDriver- http://grails.org/plugin/webdriver
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 setwar
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
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
-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
-baseUrl option is specified.baseUrl
ThebaseUrl option allows the base url for tests to be specified.grails test-app functional: -baseUrl=http://mycompany.com/grailsapp
-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.
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.
10.1 Understanding Message Bundles
Now that you have an idea of locales, to use them in Grails you create message bundle file containing the different languages that you wish to render. Message bundles in Grails are located inside thegrails-app/i18n directory and are simple Java properties files.Each bundle starts with the name messages by convention and ends with the locale. Grails ships with several message bundles for a whole range of languages within the grails-app/i18n directory. For example:messages.properties messages_da.properties messages_de.properties messages_es.properties messages_fr.properties ...
messages.properties for messages unless the user has specified a locale. You can create your own message bundle by simply creating a new properties file that ends with the locale you are interested. For example messages_en_GB.properties for British English.
10.2 Changing Locales
By default the user locale is detected from the incomingAccept-Language header. However, you can provide users the capability to switch locales by simply passing a parameter called lang to Grails as a request parameter:/book/list?lang=es
10.3 Reading Messages
Reading Messages in the View
The most common place that you need messages is inside the view. Use the message tag for this:<g:message code="my.localized.content" />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.
<g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />my.localized.content=Hola, Me llamo {0}. Hoy es {1}.Reading Messages in Controllers and Tag Libraries
It's simple to read messages in a controller since you can invoke tags as methods:def show() {
def msg = message(code: "my.localized.content", args: ['Juan', 'lunes'])
}g.:def myTag = { attrs, body ->
def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes'])
}10.4 Scaffolding and i18n
Grails scaffolding templates for controllers and views are fully i18n-aware. The GSPs use the message tag for labels, buttons etc. and controllerflash messages use i18n to resolve locale-specific messages.
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.What Grails Automatically Does
Grails has a few built in safety mechanisms by default.- All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injection attacks
- The default scaffolding templates HTML escape all data fields when displayed
- Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping mechanisms to prevent code injection
- Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.
11.1 Securing Against Attacks
SQL injection
Hibernate, which is the technology underlying GORM domain classes, automatically escapes data when committing to database so this is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameters. For example doing the following is vulnerable to HQL injection attacks:def vulnerable() {
def books = Book.find("from Book as b where b.title ='" + params.title + "'")
}def vulnerable() {
def books = Book.find("from Book as b where b.title ='${params.title}'")
}def safe() {
def books = Book.find("from Book as b where b.title = ?",
[params.title])
}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.XSS - cross-site scripting injection
It is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. Ticketing and page flow systems can help this and Grails' support for Spring Web Flow includes security like this by default.It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must call encodeAsHTML on every object to ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others. Grails supplies several Dynamic Encoding Methods for this purpose and if your output escaping format is not supported you can easily write your own codec.You must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use asuccessURL parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JavaScript code to then exploit the logged-in account on the site.Cross-site request forgery
CSRF involves unauthorized commands being transmitted from a user that a website trusts. A typical example would be another website embedding a link to perform an action on your website if the user is still authenticated.The best way to decrease risk against these types of attacks is to use theuseToken attribute on your forms. See Handling Duplicate Form Submissions for more information on how to use it. An additional measure would be to not use remember-me cookies.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.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.11.2 Encoding and Decoding Objects
Grails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails. Grails also supports a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.Codec Classes
A Grails codec class is one that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails framework dynamically loads codecs from thegrails-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.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()}value.decodeHTML() syntax.Standard Codecs
HTMLCodecThis 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.URLCodecURL 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>Your registration code is: ${user.registrationCode.encodeAsBase64()}Element.update('${elementId}',
'${render(template: "/common/message").encodeAsJavaScript()}')Selected colour: #${[255,127,255].encodeAsHex()}Your API Key: ${user.uniqueID.encodeAsMD5()}byte[] passwordHash = params.password.encodeAsMD5Bytes()Your API Key: ${user.uniqueID.encodeAsSHA1()}byte[] passwordHash = params.password.encodeAsSHA1Bytes()Your API Key: ${user.uniqueID.encodeAsSHA256()}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 thegrails-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
}
}${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 calledgrails-app/conf/SecurityFilters.groovy by running:grails create-filters security
class SecurityFilters {
def filters = {
loginCheck(controller: '*', action: '*') {
before = {
if (!session.user && actionName != "login") {
redirect(controller: "user", action: "login")
return false
}
}
}
}
}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"])
}
}11.4 Security Plugins
If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you should consider using one of the available security plugins.11.4.1 Spring Security
The Spring Security plugins are built on the Spring Security project which provides a flexible, extensible framework for building all sorts of authentication and authorization schemes. The plugins are modular so you can install just the functionality that you need for your application. The Spring Security plugins are the official security plugins for Grails and are actively maintained and supported.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 calledJsecAuthBase 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' ]) } … }
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.
Grails es ante todo un framework para el desarrollo aplicaciones web, pero también es una plataforma. A través de una serie de puntos de extensión que permiten extender cualquier funcionalidad desde la interfaz de lÃnea de comandos hasta los mecanismos de configuración en rutime, Grails se pueden personalizar para adaptarse a casi cualquier necesidad. Para extender esta plataforma, todo lo que necesita hacer es crear un 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.
Extender la plataforma puede sonar complicado, pero se pueden construir una gran variedad de plugins, desde los más sencillos hasta plugins increiblemente potentes. Si conoces como construir aplicaciones con grails, ya eres capaz de construir plugins para compartir el modelo de datos o recursos estáticos.
12.1 Creando e Instalando Plugins
Creating Plugins
Creating a Grails plugin is a simple matter of running the command:Creación de Plugins
Un plugin de Grails se crea simplemente ejecutando el siguiente comando:grails create-plugin [PLUGIN NAME]
This will create a plugin project for the name you specify. For example running
Esto creara un proyecto de plugin con el nombre especificado. Por ejemplo, ejecutando 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 create-plugin example se creará un nuevo proyecto de plugin llamado exampleLa estructura de un plugin de Grails es muy parecida a la de un proyecto de aplicación excepto porque en el directorio raiz del plugin se encuentra un fichero llamado "plugin descriptor"El hecho de ser un proyecto de Grails estandar tiene muchas ventajas incluido que puedes testear tu plugin desde el primer momento simplemente ejecutando el comando:grails run-app
The plugin descriptor name ends with the convention
El nombre del fichero descriptor del plugin tiene el sufijo GrailsPlugin and is found in the root of the plugin project. For example:
GrailsPlugin y se encuentra en la raiz del proyecto de plugin. Por ejemplo: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:
Todos los plugins deben tener esta clase en la raiz de su estructura de directorios. La clase del plugin define la versión del plugin asi como otros metadasos, y opcionalmente varios "hooks" en los puntos de extensión de plugins (lo veremos en detalle muy pronto).Es posible añadir información adicional sobre el plugin usando algunas propiedades especiales:
title- short one-sentence description of your pluginversion- 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 nameauthorEmail- plugin author's contact e-maildescription- full multi-line description of plugin's featuresdocumentation- URL of the plugin's documentation
title- Descripción corta (de una linea) del pluginversion- La versión del plugin. entre los valores válidos están por ejemplo "0.1", "0.2-SNAPSHOT", "1.1.4" etc.grailsVersion- La versión o el rango de versiones de Grails que soporta el plugin. Ej "1.2 > *" (indica 1.2 o superior)author- Nombre del autor del pluginauthorEmail- Dirección de correo del autor del plugindescription- Descripción completa (varias lineas) de las caracterÃsticas del plugindocumentation- URL de la documentación del plugin
class QuartzGrailsPlugin {
def version = "0.1"
def grailsVersion = "1.1 > *"
def author = "Sergey Nebolsin"
def authorEmail = "nebolsin@gmail.com"
def title = "Quartz Plugin"
def description = '''\
The Quartz plugin allows your Grails application to schedule jobs\
to be executed using a specified interval or cron expression. The\
underlying system uses the Quartz Enterprise Job Scheduler configured\
via Spring, but is made simpler by the coding by convention paradigm.\
'''
def documentation = "http://grails.org/plugin/quartz" …
}Installing and Distributing Plugins
To distribute a plugin you navigate to its root directory in a console and run:Instalando y distribuyendo Plugins
Para distribuir un plugin hay que ir al directorio raÃz del mismo y ejecutar:grails package-plugin
This will create a zip file of the plugin starting with
Esto creará un fichero zip del plugin con el nombre que empieza por 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- seguido del nombre del plugin y de la versión. Por ejemplo, para el plugin example creado anteriormente este nombre será grails-example-0.1.zip. El comando package-plugin también genera un fichero con nombre plugin.xml que contiene información con información sobre el nombre del plugin, versión, autor etc..
grails install-plugin /path/to/grails-example-0.1.zip
If the plugin is hosted on an HTTP server you can install it with:
Si el plugin está alojado en un servidor HTTP, se puede instalar con el comando:grails install-plugin http://myserver.com/plugins/grails-example-0.1.zip
Notes on excluded Artefacts
Although the create-plugin command creates certain files for you so that the plugin can be run as a Grails application, not all of these files are included when packaging a plugin. The following is a list of artefacts created, but not included by package-plugin:grails-app/conf/BootStrap.groovygrails-app/conf/BuildConfig.groovy(although it is used to generatedependencies.groovy)grails-app/conf/Config.groovygrails-app/conf/DataSource.groovy(and any other*DataSource.groovy)grails-app/conf/UrlMappings.groovygrails-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/**
WEB-INF it is recommended you use the _Install.groovy script (covered later), which is executed when a plugin is installed, to provide such artefacts. In addition, although UrlMappings.groovy is excluded you are allowed to include a UrlMappings definition with a different name, such as MyPluginUrlMappings.groovy.
Notas sobre artefactos excluidos
Aunque el comando create-plugin crea ciertos ficheros por nosotros de manera que el plugin puede ser ejecutado como una aplicación Grails normal, no todos esos ficheros son incluidos cuando empaquetamos un plugin. La siguiente lista muestra los artefactos que son creados pero no incluidos por package-plugingrails-app/conf/BootStrap.groovygrails-app/conf/BuildConfig.groovy(Aunque es usado para generardependencies.groovy)grails-app/conf/Config.groovygrails-app/conf/DataSource.groovy(y cualquier otro*DataSource.groovy)grails-app/conf/UrlMappings.groovygrails-app/conf/spring/resources.groovy- Todo lo que hay en
/web-app/WEB-INF - Todo lo que hay en
/web-app/plugins/** - Todo lo que hay en
/test/** - Ficheros de configuración del SCM
**/.svn/**and**/CVS/**
WEB-INF se recomienda usar el script _Install.groovy (se verá más tarde), que es ejecutaqdo cuando un plugin va a ser instalado para crear los artefactos. Además, aunque el fichero UrlMappings.groovy es escluido es posible incluir una definición UrlMappings con un nombre diferente, como por ejemplo MyPluginUrlMappings.groovy.Specifying Plugin Locations
An application can load plugins from anywhere on the file system, even if they have not been installed. Specify the location of the (unpacked) plugin in the application'sgrails-app/conf/BuildConfig.groovy file:
Especificación de la localicación de los plugins
Una aplicación puede cargar plugins de cualquier lugar dentro del sistema de ficheros, incluso aunque no hayan sido intalados. La especificación e la localización de los plugins (desempaquetados) se realiza en el ficherograils-app/conf/BuildConfig.groovy// Useful to test plugins you are developing.
grails.plugin.location.shiro =
"/home/dilbert/dev/plugins/grails-shiro"// Useful for modular applications where all plugins and
// applications are in the same directory.
grails.plugin.location.'grails-ui' = "../grails-grails-ui"
This is particularly useful in two cases:
Esto es particularmente útil en dos casos:
- 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.
- En situaciones donde se esta desarrollando un plugin y se quiere testear en una aplicación sin empaquetarlo e instalarlo previamente.
- Se se ha dividido una aplicación en un conjunto de plugins y una aplicación, todo dentro de un mismo "directorio global de proyecto"
Global plugins
Plugins can also be installed globally for all applications for a particular version of Grails using the-global flag, for example:
Plugins globales
Es posible instalar los plugins de manera global para todas las aplicaciónes de una versión concreata de grails usando el flag-global, como por ejemplograils install-plugin webtest -global
The default location is $USER_HOME/.grails/<grailsVersion>/global-plugins but this can be customized with the
La localización por defecto es $USER_HOME/.grails/<grailsVersion>/global-plugins pero puede ser modificada con la propiedad grails.global.plugins.dir setting in BuildConfig.groovy.
grails.global.plugins.dir dentro de BuildConfig.groovy.
12.2 Repositorios de Plugins
Distributing Plugins in the Grails Central Plugins Repository
The preferred way to distribute plugin is to publish to the official Grails Plugins Repository. This will make your plugin visible to the list-plugins command:grails list-plugins
grails plugin-info [plugin-name]
If you have created a Grails plugin and want it to be hosted in the central repository take a look at this wiki page which details how release your plugin.When you have access to the Grails Plugin repository, execute the release-plugin command to release your plugin:
grails release-plugin
Configuring Additional Repositories
The process for configuring repositories in Grails differs between versions. For version of Grails 1.2 and earlier please refer to the Grails 1.2 documentation on the subject. The following sections cover Grails 1.3 and above.Grails 1.3 and above use Ivy under the hood to resolve plugin dependencies. The mechanism for defining additional plugin repositories is largely the same as defining repositories for JAR dependencies. For example you can define a remote Maven repository that contains Grails plugins using the following syntax ingrails-app/conf/BuildConfig.groovy:repositories {
mavenRepo "http://repository.codehaus.org"
}grailsRepo method:repositories {
grailsRepo "http://myserver/mygrailsrepo"
}repositories {
grailsCentral()
}repositories {
grailsRepo "http://myserver/mygrailsrepo"
grailsCentral()
}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)
Publishing to Maven Compatible Repositories
In general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plugins. The benefits of doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven repository. In addition Maven compatible repositories are not tied to SVN as Grails repositories are.You use the Maven publisher plugin to publish a plugin to a Maven repository. Please refer to the section of the Maven deployment user guide on the subject.Publishing to Grails Compatible Repositories
Specify thegrails.plugin.repos.distribution.myRepository setting within the grails-app/conf/BuildConfig.groovy file to publish a Grails plugin to a Grails-compatible repository:grails.plugin.repos.distribution.myRepository =
"https://svn.codehaus.org/grails/trunk/grails-test-plugin-repo"repository argument of the release-plugin command to specify the repository to release the plugin into:grails release-plugin -repository = myRepository
12.3 Entendiendo la Estructura de un Plugin
As as mentioned previously, a plugin is basically a regular Grails application with a plugin descriptor. However when installed, the structure of a plugin differs slightly. For example, take a look at this plugin directory structure:+ grails-app
+ controllers
+ domain
+ taglib
etc.
+ lib
+ src
+ java
+ groovy
+ web-app
+ js
+ cssgrails-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" />/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 applicationJava 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.
12.4 Creando Artefactos Básicos
Adding a new Script
A plugin can add a new script simply by providing the relevant Gant script in its scripts directory:+ MyPlugin.groovy
+ scripts <-- additional scripts here
+ grails-app
+ controllers
+ services
+ etc.
+ libAdding a new grails-app artifact (Controller, Tag Library, Service, etc.)
A plugin can add new artifacts by creating the relevant file within thegrails-app tree. Note that the plugin is loaded from where it is installed and not copied into the main application tree.+ ExamplePlugin.groovy
+ scripts
+ grails-app
+ controllers <-- additional controllers here
+ services <-- additional services here
+ etc. <-- additional XXX here
+ libProviding Views, Templates and View resolution
When a plugin provides a controller it may also provide default views to be rendered. This is an excellent way to modularize your application through plugins. Grails' view resolution mechanism will first look for the view in the application it is installed into and if that fails will attempt to look for the view within the plugin. This means that you can override views provided by a plugin by creating corresponding GSPs in the application'sgrails-app/views directory.For example, consider a controller called BookController that's provided by an 'amazon' plugin. If the action being executed is list, Grails will first look for a view called grails-app/views/book/list.gsp then if that fails it will look for the same view relative to the plugin.However if the view uses templates that are also provided by the plugin then the following syntax may be necessary:<g:render template="fooTemplate" plugin="amazon"/>
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:grails-app/conf/BootStrap.groovygrails-app/conf/BuildConfig.groovy(although it is used to generatedependencies.groovy)grails-app/conf/Config.groovygrails-app/conf/DataSource.groovy(and any other*DataSource.groovy)grails-app/conf/UrlMappings.groovygrails-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/**
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"
]12.5 Evaluating Conventions
Before looking at providing runtime configuration based on conventions you first need to understand how to evaluate those conventions from a plugin. Every plugin has an implicit
Como se ha comentado anteriormente, Grails se basa en el paradigma de "Convención sobre la Configuración". Antes de examinar como preparar nuestros plugins para fúncionar usando este paradigma tenemos que entender cómo se evaluan las convenciones dentro plugin. Todos los plugins tienen una variable implicita llamada application variable which is an instance of the GrailsApplication interface.The GrailsApplication interface provides methods to evaluate the conventions within the project and internally stores references to all artifact classes within your application.Artifacts implement the GrailsClass interface, which represents a Grails resource such as a controller or a tag library. For example to get all GrailsClass instances you can do:
application que es una instancia de la interfaz GrailsApplicationLa interfaz GrailsApplication provee métodos para evaluar las convenciones en el proyecto y que almacena internamente referencias a todos los artefactos de la aplicaciónLos artefactos implementen la interfaz GrailsClass que representa un recurso de Grails, como un controlador o una librerÃa de tags. Por ejemplo, para obtener todas las instancias de GrailsClass podemos hacer:
for (grailsClass in application.allClasses) {
println grailsClass.name
}GrailsApplication has a few "magic" properties to narrow the type of artefact you are interested in. For example to access controllers you can use:
GrailsApplication tienne algunas propiedades "mágicas" que permiten restringirse al tipo de artefactos en los que se esta interesado. Por ejmplo, para acceder a los controladores se puede usar:for (controllerClass in application.controllerClasses) {
println controllerClass.name
}
The dynamic method conventions are as follows:
Las convenciones sobre los métodos dinámicos son las siguientes:
*Classes- Retrieves all the classes for a particular artefact name. For exampleapplication.controllerClasses.get*Class- Retrieves a named class for a particular artefact. For exampleapplication.getControllerClass("PersonController")is*Class- Returnstrueif the given class is of the given artefact type. For exampleapplication.isControllerClass(PersonController)
*Classes- Devuelve todas las clases con el nombre de artefacto indicado. Un ejemplo esapplication.controllerClasses.get*Class- Devuelve la clase con el nombre y tipo de artefacto indicado. Un ejemplo esapplication.getControllerClass("PersonController")is*Class- Devuelvetruesi la clase es del tipo de artefacto indicado. Un ejemplo esapplication.isControllerClass(PersonController)
The
La interfaz 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 classhasProperty- Returnstrueif the class has the specified propertynewInstance- Creates a new instance of this class.getName- Returns the logical name of the class in the application without the trailing convention part if applicablegetShortName- Returns the short name of the class without package prefixgetFullName- Returns the full name of the class in the application with the trailing convention part and with the package namegetPropertyName- Returns the name of the class as a property namegetLogicalPropertyName- Returns the logical property name of the class in the application without the trailing convention part if applicablegetNaturalName- Returns the name of the property in natural terms (eg. 'lastName' becomes 'Last Name')getPackageName- Returns the package name
GrailsClass tiene una serie de métodos que permiten evaluar y trabajar conlas convenciones. Entre estos se incluyen:
getPropertyValue- Obtiene el valor inicial de la propiedad en la clase.hasProperty- Devuelvetruesi la clase tiene la propiedad especificada.newInstance- Crea una nueva instancia de la clase.getName- Devuelve el nombre lógico de una clase en la aplicación pero sin el sufijo de la convención (si es que lo tiene).getShortName- Devuelve el nombre corto de la clase sin prefijarla con el paquete.getFullName- Devuelve el nombre completo de la clase en la aplicación con el sufijo de la convención y prefijandola con el nombre del paquete.getPropertyName- Devuelve el nombre de la clase como nombre de propiedadgetLogicalPropertyName- Devuelve el nombre lógico de la pripiedad de la clase en la aplicación sin el sufijo de la convención (si es que lo tiene).getNaturalName- Devuelve el nombre de la propiedad en "lenguage naturales", esto es, 'lastName' se convierte en 'Last Name'getPackageName- Devuelve el nombre del paquete
12.6 Hooking into Build Events
Post-Install Configuration and Participating in Upgrades
Configuración en la Post-instalación y participación en los upgrades
Grails plugins can do post-install configuration and participate in application upgrade process (the upgrade command). This is achieved using two specially named scripts under the
Los plugins de grails pueden hacer configuración en la post-instalación y participar en el proceso de upgrade de una aplicación (el comando upgrade). Esto se realiza usando dos scripts con nombres especiales en la carpeta scripts directory of the plugin - _Install.groovy and _Upgrade.groovy._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:
scripts del plugin - _Install.groovy y _Upgrade.groovy.El script _Install.groovy es ejecutado despues de quue el plugin haya sido instalado y el script _Upgrade.groovy es ejecutado cada vez que el usuario haga un upgrade de la aplicación (pero no del plugin) con el comando upgrade.Estos scripts son scripts de Gant, por lo que se tiene a disposición toda la potencia e Gant. Además de las variables estandar de Gant, dentro del script esta disponible también una variable pluginBasedir que apunta al directorio base de instalación del plugin.Como ejemplo, este script _Install.groovy creará un nuevo tipo de directorio dentro del directorio grails-app e instalará una plantilla de configuración.
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.
Ejecutando scripts en eventos
Es posible inyectar acciones durante los eventos que se produce al lanzar scripts en la linea de comandos. Estos son eventos lanzados durante la ejecución de targets de Grais y scripts de plugins.Por ejemplo, es posible inyectar en la salida de updateo de estado (i.e. "Test passed", "Server running") y en la creación de ficheros o artefactos.Un plugin solo necesita un script_Events.groovy para ser notificado de los eventos que necesite. Para más información visitar la página Hooking into Events
12.7 Hooking into Runtime Configuration
Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.
Grails ofrece una serie de puntos de extensión donde inyectar código para aprovechar las diferentes partes del sistema y realizar configuración por convención en tiempo de ejecución.Hooking into the Grails Spring configuration
First, you can hook in Grails runtime configuration by providing a property calleddoWithSpring which is assigned a block of code. For example the following snippet is from one of the core Grails plugins that provides i18n support:
Puntos de extensión en la configuración de Spring de Grails.
En primer lugar, se puede inyectar funcionalidad en la configuración de tiempo de ejecución de Grails usando una propiedad llamadadoWithSpring a la que se le asigna un bloque de código. Por ejemplo el siguiente fragmento es de uno de los plugins del núcleo Grails que ofrece soporte para i18n:
import org.springframework.web.servlet.i18n.CookieLocaleResolver import org.springframework.web.servlet.i18n.LocaleChangeInterceptor import org.springframework.context.support.ReloadableResourceBundleMessageSourceclass I18nGrailsPlugin { def version = "0.1" def doWithSpring = { messageSource(ReloadableResourceBundleMessageSource) { basename = "WEB-INF/grails-app/i18n/messages" } localeChangeInterceptor(LocaleChangeInterceptor) { paramName = "lang" } localeResolver(CookieLocaleResolver) } }
This plugin configures the Grails Add
Consider this example from the
Este plugin configura el bean de 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.Participating in web.xml Generation
Grails generates theWEB-INF/web.xml file at load time, and although plugins cannot change this file directly, they can participate in the generation of the file. A plugin can provide a doWithWebDescriptor property that is assigned a block of code that gets passed the web.xml as an XmlSlurper GPathResult.Add servlet and servlet-mapping
Consider this example from the ControllersPlugin:
messageSource asi como un par de otros beans para gestionar la resolución y el cambio del Locale. Utiliza la sintaxis Spring Bean Builder para hacer esto.Participar en la generación del fichero web.xml
Grails genera el ficheroWEB-INF/web.xml en tiempo de carga, y aunque los plugins no pueden cambiar este fichero directamente, pueden participar en su generación. Un plugin puede contener de una propiedad doWithWebDescriptor que contiene un bloque de código que es pasado al web.xml como un XmlSlurper GPathResult.Añadir un servlet y un servlet-mapping
Considere este ejemplo perteneciente al ControllersPluginsdef doWithWebDescriptor = { webXml -> def mappingElement = webXml.'servlet-mapping' def lastMapping = mappingElement[mappingElement.size() - 1]
lastMapping + {
'servlet-mapping' {
'servlet-name'("grails")
'url-pattern'("*.dispatch")
}
}
}
Here the plugin gets a reference to the last Add
Adding a filter with its mapping works a little differently. The location of the
En este caso, el plugin obtiene una referencia al último elemento <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:
<servlet-mapping> y añade el servlet de Grails despues de él usando la habilidad de XmlSlurper para modificar XML usando closures y bloques.añadir filter y filter-mappings
Este ejemplo para añadir un filtro y su mapeo funciona de manera un poco diferente. El lugar del elemento <filter> no importa dado que el orden no es importante, por lo que es más sencillo insertar nuestra definición de filtro personalizada inmediatamente despues del último elemento <context-param>. Por el contrario el orden si que es importante para los mapeos, pero la aproximación usual es añadir el mapeo inmediatamente despues del último elmento <filter> de esta manera: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'('/*')
}
}
}
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:
En algúnos casos es necesarkio asegurar que nuestro filtro se inserta despues de uno de los filtros estandar de Grails, como por ejemplo el filtro "character encoding" de Spring o el filtro de SiteMesh. Afortunadamente es posible insertar el mapeo del filtro inmediatamente despues de los estandar (más exactamente, despues de cualquiera definido en la plantilla del web.xml) de esta manera:def doWithWebDescriptor = { webXml ->
... // Insert the Spring Security filter after the Spring
// character encoding filter.
def filter = webXml.'filter-mapping'.find {
it.'filter-name'.text() == "charEncodingFilter"
} filter + {
'filter-mapping'{
'filter-name'('springSecurityFilterChain')
'url-pattern'('/*')
}
}
}Doing Post Initialisation Configuration
Sometimes it is useful to be able do some runtime configuration after the Spring ApplicationContext has been built. In this case you can define adoWithApplicationContext closure property.
Haciendo configuración en la Post Instalación
En determinadas ocasiones es útil ser capaz de realizar configuración en runtime despues de que el ApplicationContext de Spring haya sido construido. En este caso, es posible definir una propidad closuredoWithApplicationContextclass SimplePlugin { def name = "simple"
def version = "1.1" def doWithApplicationContext = { appCtx ->
def sessionFactory = appCtx.sessionFactory
// do something here with session factory
}
}12.8 Adding Dynamic Methods at Runtime
The Basics
Introducción
Grails plugins let you register dynamic methods with any Grails-managed or other class at runtime. This work is done in a
Los plugins de grails permiten registrar dinámicamente métodos en clases gestionadas por Grails o cualquier otra clase en tiempo de ejecución. Esto se consigue a través de la closure doWithDynamicMethods closure.
doWithDynamicMethods
For Grails-managed classes like controllers, tag libraries and so forth you can add methods, constructors etc. using the ExpandoMetaClass mechanism by accessing each controller's MetaClass:
Para las clases gestionadas por grails, como los controladores, librerÃas de tags y otras, es posible añadir métodos, constructures etc. usando el mecanismo ExpandoMetaClass accediendo al MetaClass de cada controlador.class ExamplePlugin {
def doWithDynamicMethods = { applicationContext ->
for (controllerClass in application.controllerClasses) {
controllerClass.metaClass.myNewMethod = {-> println "hello world" }
}
}
}
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
En este caso, usamos el objeto implicito "application" para obtener una referencia a al atributo "metaClass" de las clases controladoras, y añadir un nuevo método llamado myNewMethod to each controller. If you know beforehand the class you wish the add a method to you can simply reference its metaClass property.
myNewMethod a cada controlador. Conociendo de antemano la clase a la que se desea añadir el método, esto se puede hacer de manera más sencilla accediendo directamente su atributo metaClass
For example we can add a new method
Por ejemplo, podrÃamos añadir un nuevo método swapCase to java.lang.String:
swapCase a java.lang.String:class ExamplePlugin { def doWithDynamicMethods = { applicationContext ->
String.metaClass.swapCase = {->
def sb = new StringBuilder()
delegate.each {
sb << (Character.isUpperCase(it as char) ?
Character.toLowerCase(it as char) :
Character.toUpperCase(it as char))
}
sb.toString()
} assert "UpAndDown" == "uPaNDdOWN".swapCase()
}
}Interacting with the ApplicationContext
Interaccionando con el ApplicationContext
The
La closure doWithDynamicMethods closure gets passed the Spring ApplicationContext instance. This is useful as it lets you interact with objects within it. For example if you were implementing a method to interact with Hibernate you could use the SessionFactory instance in combination with a HibernateTemplate:
doWithDynamicMethods recibe como parámetro la intancia del ApplicationContext de Spring. Esto es muy útil porque permite interactuar con los objetos que contiene. Por ejemplo, si se está implementando un método para interacturar con Hibernate se podrÃa usar la instancia del SessionFactory en combinación con un HibernateTemplateimport org.springframework.orm.hibernate3.HibernateTemplateclass ExampleHibernatePlugin { def doWithDynamicMethods = { applicationContext -> for (domainClass in application.domainClasses) { domainClass.metaClass.static.load = { Long id-> def sf = applicationContext.sessionFactory def template = new HibernateTemplate(sf) template.load(delegate, id) } } } }
Also because of the autowiring and dependency injection capability of the Spring container you can implement more powerful dynamic constructors that use the application context to wire dependencies into your object at runtime:
También es importante destacar que gracias a las capacidades de autowiring e inyección de dependencias de Spring, es posible implementar potentes constructores usando el application context para enlazar dependencias en tus objetos en tiempo de ejecución.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!
En el ejemplo de hecho se está remplazando el constructor por defecto por otro que devuelve un objeto definido en Spring tipo "prototype" en lugar de crear una clase nueva.
12.9 Participating in Auto Reload Events
Monitoring Resources for Changes
Often it is valuable to monitor resources for changes and perform some action when they occur. This is how Grails implements advanced reloading of application state at runtime. For example, consider this simplified snippet from the GrailsServicesPlugin:class ServicesGrailsPlugin {
…
def watchedResources = "file:./grails-app/services/*Service.groovy" …
def onChange = { event ->
if (event.source) {
def serviceClass = application.addServiceClass(event.source)
def serviceName = "${serviceClass.propertyName}"
def beans = beans {
"$serviceName"(serviceClass.getClazz()) { bean ->
bean.autowire = true
}
}
if (event.ctx) {
event.ctx.registerBeanDefinition(
serviceName,
beans.getBeanDefinition(serviceName))
}
}
}
}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 reloadedClassor a SpringResourceevent.ctx- The SpringApplicationContextinstanceevent.plugin- The plugin object that manages the resource (usuallythis)event.application- TheGrailsApplicationinstanceevent.manager- TheGrailsPluginManagerinstance
ApplicationContext when one of the service classes changes.Influencing Other Plugins
In addition to reacting to changes, sometimes a plugin needs to "influence" another.Take for example the Services and Controllers plugins. When a service is reloaded, unless you reload the controllers too, problems will occur when you try to auto-wire the reloaded service into an older controller Class.To get around this, you can specify which plugins another plugin "influences". This means that when one plugin detects a change, it will reload itself and then reload its influenced plugins. For example consider this snippet from theServicesGrailsPlugin:def influences = ['controllers']
Observing other plugins
If there is a particular plugin that you would like to observe for changes but not necessary watch the resources that it monitors you can use the "observe" property:def observe = ["controllers"]def observe = ["*"]log property back to any artefact that changes while the application is running.
12.10 Understanding Plugin Load Order
Controlling Plugin Dependencies
Plugins often depend on the presence of other plugins and can adapt depending on the presence of others. This is implemented with two properties. The first is calleddependsOn. For example, take a look at this snippet from the Hibernate plugin:class HibernateGrailsPlugin { def version = "1.0" def dependsOn = [dataSource: "1.0",
domainClass: "1.0",
i18n: "1.0",
core: "1.0"]
}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 > *"]
- 1.1
- 1.0
- 1.0.1
- 1.0.3-SNAPSHOT
- 1.1-BETA2
Controlling Load Order
UsingdependsOn establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won't load. It is possible though to have a weaker dependency using the loadAfter property:def loadAfter = ['controllers']
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:if (manager?.hasGrailsPlugin("controllers")) { openSessionInViewInterceptor(OpenSessionInViewInterceptor) { flushMode = HibernateAccessor.FLUSH_MANUAL sessionFactory = sessionFactory } grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor }
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.
Scopes and Environments
It's not only plugin load order that you can control. You can also specify which environments your plugin should be loaded in and which scopes (stages of a build). Simply declare one or both of these properties in your plugin descriptor:def environments = ['development', 'test', 'myCustomEnv'] def scopes = [excludes:'war']
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 testsfunctional-test- when running functional testsrun- for run-app and run-warwar- when packaging the application as a WAR fileall- plugin applies to all scopes (default)
- 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
def environments = "test"def environments = ["development", "test"]
def environments = [includes: ["development", "test"]]
12.11 The Artefact API
You should by now understand that Grails has the concept of artefacts: special types of classes that it knows about and can treat differently from normal Groovy and Java classes, for example by enhancing them with extra properties and methods. Examples of artefacts include domain classes and controllers. What you may not be aware of is that Grails allows application and plugin developers access to the underlying infrastructure for artefacts, which means you can find out what artefacts are available and even enhance them yourself. You can even provide your own custom artefact types.
Con lo visto hasta ahora ya deberÃa entender el concepto de artefacto en Grails: un tipo especial de clases conocidas que se tratan de manera diferente a las clases de Groovy y Java usuales, por ejemplo mediante la inyección en ellas de propiedades adicionales y métodos. Son ejemplos de artefactos las clases de dominio y los controladores. De lo que es posible que no se haya percatado es de que Grails permite a los desarrolladores de aplicaciones y plugins acceder a la infraestructura subyacente de los artefactos, lo que significa que es posible conocer que artefactos hay disponibles e inyectar caracteristicas a los mismos. También es posible crear tipos de artefactos personalizados.
12.11.1 Asking About Available Artefacts
As a plugin developer, it can be important for you to find out about what domain classes, controllers, or other types of artefact are available in an application. For example, the Searchable plugin needs to know what domain classes exist so it can check them for anysearchable properties and index the appropriate ones. So how does it do it? The answer lies with the grailsApplication object, and instance of GrailsApplication that's available automatically in controllers and GSPs and can be injected everywhere else.The grailsApplication object has several important properties and methods for querying artefacts. Probably the most common is the one that gives you all the classes of a particular artefact type:for (cls in grailsApplication.<artefactType>Classes) {
…
}artefactType is the property name form of the artefact type. With core Grails you have:
- domain
- controller
- tagLib
- service
- codec
- bootstrap
- urlMappings
for (cls in grailsApplication.domainClasses) {
…
}for (cls in grailsApplication.urlMappingsClasses) {
…
}Class:
shortName- the class name of the artefact without the package (equivalent ofClass.simpleName).logicalPropertyName- the artefact name in property form without the 'type' suffix. SoMyGreatControllerbecomes '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.
- get<type>Class(String name)
- is<type>Class(Class clazz)
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.
12.11.2 Adding Your Own Artefact Types
Plugins can easily provide their own artefacts so that they can easily find out what implementations are available and take part in reloading. All you need to do is create anArtefactHandler implementation and register it in your main plugin class:class MyGrailsPlugin {
def artefacts = [ org.somewhere.MyArtefactHandler ]
…
}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:
Another example is the Shiro plugin which adds a realm artefact.
12.12 Binary Plugins
Regular Grails plugins are packaged as zip files containing the full source of the plugin. This has some advantages in terms of being an open distribution system (anyone can see the source), in addition to avoiding problems with the source compatibility level used for compilation.
Normalmente los plugins de Grails se empaquetan como ficheros zip junto con el código fuente de los mismos. Esto tiene varias ventajas en lo referente a la distribución libre (cualquiera puede ver el código), además de evitar problemas con en nivel de compatibilidad de código usado para compilar.
As of Grails 2.0 you can pre-compile Grails plugins into regular JAR files known as "binary plugins". This has several advantages (and some disadvantages as discussed in the advantages of source plugins above) including:
En Grails 2.0 es posible pre-compilar los plugins en un fichero JAR estandar conocido como "plugin binarios". Esto tiene varias ventajas (y algúnas desventajas como hemos visto con los plugins empaquetados junto al código fuente) como por ejemplo:
- Binary plugins can be published as standard JAR files to a Maven repository
- Binary plugins can be declared like any other JAR dependency
- Commercial plugins are more viable since the source isn't published
- IDEs have a better understanding since binary plugins are regular JAR files containing classes
- Los plugins binarios pueden ser publicados como jars estandar en un repositorio Maven
- Los plugins binarios pueden ser declarados como cualquier otra dependencia a otro jar
- Los plugins comerciales son más viables dado que el código fuente no se publica.
- Los IDEs de desarrollo los gestionan mejor dado que los plugins binarios son ficheros JARs normales que contienen clases
Packaging
To package a plugin in binary form you can use the package-plugin command and the--binary flag:
Empaquetamiento
Para empaquetar un plugin en forma binaria se usa el comando package-plugin command y el flag--binary:
grails package-plugin --binary
Supported artefacts include:
Entre los artefactos soportados se incluyen:
- Grails artifact classes such as controllers, domain classes and so on
- I18n Message bundles
- GSP Views, layouts and templates
- Los artefactos de Grails como los controladores, las clases de dominio y otros
- I18n Message bundles
- Vistas GSP Views, layouts y plantillas
def packaging = "binary"
in which case the packaging will default to binary.
en este caso el empaquetamiento por defecto será binarioUsing Binary Plugins
The packaging process creates a JAR file in thetarget directory of the plugin, for example target/foo-plugin-0.1.jar. There are two ways to incorporate a binary plugin into an application.One is simply placing the plugin JAR file in your application's lib directory. The other is to publish the plugin JAR to a compatible Maven repository and declare it as a dependency in grails-app/conf/BuildConfig.groovy:
Usando los plugins binarios
El proceso de empaquetamiento crea un fichero JAR en el directoriotarget del plugin, por ejemplo target/foo-plugin-0.1.jar. Existen dos maneras para incorporar un plugin binario en una aplicación.Una consiste simplemente en colocar el JAR del plugin en el directorio lib de la aplicacion. La otra consiste en publicar el JAR en un repositorio compatible con Maven y declararlo como dependencia en grails-app/conf/BuildConfig.groovy:dependencies {
compile "mycompany:myplugin:0.1"
}Since binary plugins are packaged as JAR files, they are declared as dependencies in thedependenciesblock, not in thepluginsblock as you may be naturally inclined to do. Thepluginsblock is used for declaring traditional source plugins packaged as zip files
Como los plugins son empaquetados como ficheros JAR, son declarados como dependencias en el bloquedependencies, no en el bloquepluginscomo parece más natural. El bloquepluginses usado para declarar los plugins clasicos empaquetados con el código fuente en los ficheros zip.
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
Todos los servicios web son acerca de proveer una web API dentro de su aplicacion web y son tipicamente implementados ya sea con REST o "SOAP":http://en.wikipedia.org/wiki/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") }
/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 | show |
PUT | update |
POST | save |
DELETE | delete |
"/product/$id"(controller: "product") { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }
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"] }
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.JSONdef 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 } } }
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>
_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.XML Marshalling - Reading
The controller can use Grails' XML marshalling support to implement the GET method:import grails.converters.XMLclass ProductController { def show() { if (params.id && Product.exists(params.id)) { def p = Product.findByName(params.id) render p as XML } else { def all = Product.list() render all as XML } } .. }
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.XML Marshalling - Updating
To support updates such asPUT and POST you can use the params object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:<?xml version="1.0" encoding="ISO-8859-1"?> <product> <name>MacBook</name> <vendor id="12"> <name>Apple</name> </vender> </product>
def save() {
def p = new Product(params.product) if (p.save()) {
render p as XML
}
else {
render p.errors
}
}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)If you require different responses to different clients (REST, HTML etc.) you can use content negotationThe
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>
REST with JAX-RS
There also is a JAX-RS Plugin which can be used to build web services based on the Java API for RESTful 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:
Hay varios plugins que agregan soporte SOAP a Grails dependiendo de su enfoque preferido. Para el primer contrato de servicios SOAP esta el plugin Spring WS, mientras que si quiere generar una API de SOAP desde servicios Grails hay varios plugins que hacen esto incluyendo:- CXF plugin el cual usa la pila de SOAP CXF
- Axis2 plugin el cual usa Axis2
- Metro plugin el cual usa el framework Metro (y puede tambien ser usado por Contract First)
Most of the SOAP integrations integrate with Grails services via the
La mayoria de las integraciones de SOAP son integradas con Grails services son via la propiedad estatica exposes static property. This example is taken from the CXF plugin:
exposes. Este ejemplo esta tomado del plugin CXF:class BookService { static expose = ['cxf'] Book[] getBooks() {
Book.list() as Book[]
}
}
The WSDL can then be accessed at the location:
El WSDL puede entonces ser accesado en la ubicacion: http://127.0.0.1:8080/your_grails_app/services/book?wsdl
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.
Para mas informacion del plugin CXF refierase a la documentacion en la wiki.
13.3 RSS and Atom
No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the render method's XML capability. There is however a Feeds plugin available for Grails that provides a RSS and Atom builder using the popular ROME library. An example of its usage can be seen below:
No hay soporte directo proveido dentro de Grails para RSS y Atom. Usted podria construir RSS o ATOM feeds con los metodos de render con la capacidad de XML. Hay sin embargo un plugin de Feeds disponible para Grails que provee un constructor de RSS y ATOM usando la libreria popular ROME Un ejemplo de su uso pude verse a continuacion:def feed() {
render(feedType: "rss", feedVersion: "2.0") {
title = "My test feed"
link = "http://your.test.server/yourController/feed" for (article in Article.list()) {
entry(article.title) {
link = "http://your.test.server/article/${article.id}"
article.content // return the content
}
}
}
}14 Grails and Spring
This section is for advanced users and those who are interested in how Grails integrates with and builds on the Spring Framework It is also useful for plugin developers considering doing runtime configuration Grails.14.1 The Underpinnings of Grails
Grails is actually a Spring MVC application in disguise. Spring MVC is the Spring framework's built-in MVC web application framework. Although Spring MVC suffers from some of the same difficulties as frameworks like Struts in terms of its ease of use, it is superbly designed and architected and was, for Grails, the perfect framework to build another framework on top of.Grails leverages Spring MVC in the following areas:- Basic controller logic - Grails subclasses Spring's DispatcherServlet and uses it to delegate to Grails controllers
- Data Binding and Validation - Grails' validation and data binding capabilities are built on those provided by Spring
- Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring ApplicationContext
- Transactions - Grails uses Spring's transaction management in GORM
The Grails ApplicationContext
Spring developers are often keen to understand how the GrailsApplicationContext instance is constructed. The basics of it are as follows.
- Grails constructs a parent
ApplicationContextfrom theweb-app/WEB-INF/applicationContext.xmlfile. ThisApplicationContextconfigures the GrailsApplication instance and the GrailsPluginManager. - Using this
ApplicationContextas a parent Grails' analyses the conventions with theGrailsApplicationinstance and constructs a childApplicationContextthat is used as the rootApplicationContextof the web application
Configured Spring Beans
Most of Grails' configuration happens at runtime. Each plugin may configure Spring beans that are registered in theApplicationContext. For a reference as to which beans are configured, refer to the reference guide which describes each of the Grails plugins and which beans they configure.
14.2 Configuring Additional Beans
Using the Spring Bean DSL
You can easily register new (or override existing) beans by configuring them ingrails-app/conf/spring/resources.groovy which uses the Grails Spring DSL. Beans are defined inside a beans property (a Closure):beans = {
// beans here
}import my.company.MyBeanImplbeans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } }
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
…
}import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImplbeans = { switch(Environment.current) { case Environment.PRODUCTION: myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } break case Environment.DEVELOPMENT: myBean(MockImpl) { someProperty = 42 otherProperty = "blue" } break } }
GrailsApplication object can be accessed with the application variable and can be used to access the Grails configuration (amongst other things):import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImplbeans = { 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 agrails-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>
class ExampleController { def myBean
}Referencing Existing Beans
Beans declared inresources.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")
}
}<bean id="myBean" class="my.company.MyBeanImpl"> <property name="someProperty" value="42" /> <property name="otherProperty" value="blue" /> <property name="bookService" ref="bookService" /> </bean>
package my.companyclass MyBeanImpl { Integer someProperty String otherProperty BookService bookService // or just "def bookService" }
package my.company;class MyBeanImpl { private BookService bookService; private Integer someProperty; private String otherProperty; public void setBookService(BookService theBookService) { this.bookService = theBookService; } public void setSomeProperty(Integer someProperty) { this.someProperty = someProperty; } public void setOtherProperty(String otherProperty) { this.otherProperty = otherProperty; } }
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.For a full reference of the available beans see the plugin reference in the reference guide.
14.3 Runtime Spring with the Beans DSL
This Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at its core.In addition, Spring's regular way of configuration (via XML and annotations) is static and difficult to modify and configure at runtime, other than programmatic XML creation which is both error prone and verbose. Grails' BeanBuilder changes all that by making it possible to programmatically wire together components at runtime, allowing you to adapt the logic based on system properties or environment variables.This enables the code to adapt to its environment and avoids unnecessary duplication of code (having different Spring configs for test, development and production environments)The BeanBuilder class
Grails provides a grails.spring.BeanBuilder class that uses dynamic Groovy to construct bean definitions. The basics are as follows:import org.apache.commons.dbcp.BasicDataSource import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean import org.springframework.context.ApplicationContext import grails.spring.BeanBuilderdef bb = new BeanBuilder()bb.beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = ref('dataSource') hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } }ApplicationContext appContext = bb.createApplicationContext()
Within plugins and the grails-app/conf/spring/resources.groovy file you don't need to create a new instance ofThis example shows how you would configure Hibernate with a data source with theBeanBuilder. Instead the DSL is implicitly available inside thedoWithSpringandbeansblocks respectively.
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.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"]
}Using BeanBuilder with Spring MVC
Include thegrails-spring-<version>.jar file in your classpath to use BeanBuilder in a regular Spring MVC application. Then add the following <context-param> values to your /WEB-INF/web.xml file:<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.groovy</param-value> </context-param><context-param> <param-name>contextClass</param-name> <param-value> org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext </param-value> </context-param>
/WEB-INF/applicationContext.groovy file that does the rest:import org.apache.commons.dbcp.BasicDataSourcebeans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } }
Loading Bean Definitions from the File System
You can use theBeanBuilder 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()
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.ConfigurableLocalSessionFactoryBeanbeans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } }
Adding Variables to the Binding (Context)
If you're loading beans from a script you can set the binding to use by creating a GroovyBinding:def binding = new Binding() binding.maxSize = 10000 binding.productGroup = 'finance'def bb = new BeanBuilder() bb.binding = binding bb.loadBeans("classpath:*SpringBeans.groovy")def ctx = bb.createApplicationContext()
maxSize and productGroup properties in your DSL files.
14.4 The BeanBuilder DSL Explained
Using Constructor Arguments
Constructor arguments can be defined using parameters to each bean-defining method. Put them after the first argument (the Class):bb.beans {
exampleBean(MyExampleBean, "firstArgument", 2) {
someProperty = [1, 2, 3]
}
}MyExampleBean with a constructor that looks like this:MyExampleBean(String foo, int bar) { … }
Configuring the BeanDefinition (Using factory methods)
The first argument to the closure is a reference to the bean configuration instance, which you can use to configure factory methods and invoke any method on the AbstractBeanDefinition class:bb.beans {
exampleBean(MyExampleBean) { bean ->
bean.factoryMethod = "getInstance"
bean.singleton = false
someProperty = [1, 2, 3]
}
}bb.beans {
def example = exampleBean(MyExampleBean) {
someProperty = [1, 2, 3]
}
example.factoryMethod = "getInstance"
}Using Factory beans
Spring defines the concept of factory beans and often a bean is created not directly from a new instance of a Class, but from one of these factories. In this case the bean has no Class argument and instead you must pass the name of the factory bean to the bean defining method:bb.beans { myFactory(ExampleFactoryBean) {
someProperty = [1, 2, 3]
} myBean(myFactory) {
name = "blah"
}
}bb.beans { myFactory(ExampleFactoryBean) {
someProperty = [1, 2, 3]
} myBean(myFactory: "getInstance") {
name = "blah"
}
}getInstance method on the ExampleFactoryBean bean will be called to create the myBean bean.Creating Bean References at Runtime
Sometimes you don't know the name of the bean to be created until runtime. In this case you can use a string interpolation to invoke a bean defining method dynamically:def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1, 2, 3] } }
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") } }
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:ApplicationContext parent = ...// der bb = new BeanBuilder(parent) bb.beans { anotherBean(AnotherBean) { example = ref("${beanName}Bean", true) } }
true specifies that the reference will look for the bean in the parent context.Using Anonymous (Inner) Beans
You can use anonymous inner beans by setting a property of the bean to a block that takes an argument that is the bean type:bb.beans { marge(Person) {
name = "Marge"
husband = { Person p ->
name = "Homer"
age = 45
props = [overweight: true, height: "1.8m"]
}
children = [bart, lisa]
} bart(Person) {
name = "Bart"
age = 11
} lisa(Person) {
name = "Lisa"
age = 9
}
}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]
}
}Abstract Beans and Parent Bean Definitions
To create an abstract bean definition define a bean without aClass parameter:class HolyGrailQuest {
def start() { println "lets begin" }
}class KnightOfTheRoundTable { String name
String leader
HolyGrailQuest quest KnightOfTheRoundTable(String name) {
this.name = name
} def embarkOnQuest() {
quest.start()
}
}import grails.spring.BeanBuilderdef bb = new BeanBuilder() bb.beans { abstractBean { leader = "Lancelot" } … }
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:import grails.spring.BeanBuilderdef bb = new BeanBuilder() bb.beans { abstractBean(KnightOfTheRoundTable) { bean -> bean.'abstract' = true leader = "Lancelot" } quest(HolyGrailQuest) knights("Camelot") { bean -> bean.parent = abstractBean quest = quest } }
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.Using Spring Namespaces
Since Spring 2.0, users of Spring have had easier access to key features via XML namespaces. You can use a Spring namespace in BeanBuilder by declaring it with this syntax:xmlns context:"http://www.springframework.org/schema/context"context.'component-scan'('base-package': "my.company.domain")xmlns jee:"http://www.springframework.org/schema/jee"jee.'jndi-lookup'(id: "dataSource", 'jndi-name': "java:comp/env/myDataSource")
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:class Person { int age
String name void birthday() {
++age;
}
}class BirthdayCardSender { List peopleSentCards = [] void onBirthday(Person person) {
peopleSentCards << person
}
}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)" } } }
14.5 Property Placeholder Configuration
Grails supports the notion of property placeholder configuration through an extended version of Spring's PropertyPlaceholderConfigurer, which is typically useful in combination with externalized configuration.Settings defined in either ConfigSlurper scripts or Java properties files can be used as placeholder values for Spring configuration ingrails-app/conf/spring/resources.xml. For example given the following entries in grails-app/conf/Config.groovy (or an externalized config):database.driver="com.mysql.jdbc.Driver" database.dbname="mysql:mydb"
resources.xml as follows using the familiar ${..} syntax:<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.driver}</value> </property> <property name="url"> <value>jdbc:${database.dbname}</value> </property> </bean>
14.6 Property Override Configuration
Grails supports setting of bean properties via configuration. This is often useful when used in combination with externalized configuration.You define abeans block with the names of beans and their values:beans {
bookService {
webServiceURL = "http://www.amazon.com"
}
}[bean name].[property name] = [value]
beans.bookService.webServiceURL=http://www.amazon.com
15 Grails and Hibernate
If GORM (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map your domain classes using Hibernate, either with XML mapping files or JPA annotations. You will be able to map Grails domain classes onto a wider range of legacy systems and have more flexibility in the creation of your database schema. Best of all, you will still be able to call all of the dynamic persistent and query methods provided by GORM!15.1 Using Hibernate XML Mapping Files
Mapping your domain classes with XML is pretty straightforward. Simply create ahibernate.cfg.xml file in your project's grails-app/conf/hibernate directory, either manually or with the create-hibernate-cfg-xml command, that contains the following:<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Example mapping file inclusion --> <mapping resource="org.example.Book.hbm.xml"/> … </session-factory> </hibernate-configuration>
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"
}hibernate {
config.location = ["file:/path/to/one/hibernate.cfg.xml",
"file:/path/to/two/hibernate.cfg.xml"]
}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!
15.2 Mapping with Hibernate Annotations
To map a domain class with annotations, create a new class insrc/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; } }
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>
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.
15.3 Adding Constraints
You can still use GORM validation even if you use a Java domain model. Grails lets you define constraints through separate scripts in thesrc/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
}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 thescaffold property. Set the scaffold property in the controller to true for the Book domain class:class BookController {
static scaffold = true
}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
}- list
- show
- edit
- delete
- create
- save
- update
http://localhost:8080/app/book in a browser.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: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)
}
}class BookController { static scaffold = Book // overrides scaffolded action to return both authors and books
def list() {
[bookInstanceList: Book.list(),
bookInstanceTotal: Book.count(),
authorInstanceList: Author.list()]
} def show() {
def book = Book.get(params.id)
log.error(book)
[bookInstance : book]
}
}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>InstanceListfor collections and<propertyName>Instancefor single instances. It's tempting to use properties like 'books' and 'book', but those won't work.
Customizing the Generated Views
The views adapt to Validation constraints. For example you can change the order that fields appear in the views simply by re-ordering the constraints in the builder:def constraints = {
title()
releaseDate()
}inList constraint:def constraints = {
title()
category(inList: ["Fiction", "Non-fiction", "Biography"])
releaseDate()
}range constraint on a number:def constraints = {
age(range:18..65)
}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
grails generate-views Book
grails generate-all Book
grails generate-all com.bookstore.Book
Customizing the Scaffolding templates
The templates used by Grails to generate the controller and views can be customized by installing the templates with the install-templates command.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
grails war /opt/java/tomcat-5.5.24/foobar.war
grails-app/conf/BuildConfig.groovy that changes the default location and filename:grails.project.war.file = "foobar-prod.war"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)
}
}
}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.// 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")
}
