© Adam L. Davis 2016

Adam L. Davis, Learning Groovy, 10.1007/978-1-4842-2117-4_13

13. Grails

Adam L. Davis

(1)New York, USA

Grails is a web framework for Groovy that follows the example of Ruby on Rails to be an opinionated web framework with a command-line tool that gets things done really fast. Grails uses convention over configuration to reduce configuration overhead.

Grails lives firmly in the Java ecosystem and is built on top of technologies like Spring and Hibernate. Grails also includes an Object-Relational-Mapping (ORM) framework called GORM and has a large collection of plugins.

Different versions of Grails can be very different, so you need to take care when upgrading your Grails application, especially with major versions (2.4 to 3.0, for example).

This chapter contains a quick overview of how Grails (2) works, and then includes a history of Grails.

Quick Overview of Grails

After installing Grails1, you can create an app by running the following on the command-line:

1   $ grails create-app

Then, you can run commands like create-domain-class and generate-all to create your application as you go. Run grails help to see the full list of commands available.

Grails applications have a very specific project structure. The following is a simple breakdown of most of that structure:

  • grails-app—The Grails-specific folder.

    • conf—Configuration, such as the DataSource script and Bootstrap class.

    • controllers—Controllers with methods for index/create/edit/delete or anything else.

    • domain—Domain model; classes representing your persistent data.

    • i18n—Message bundles.

    • jobs—Any scheduled jobs you might have go here.

    • services—Backend services where your backend or "business" logic goes.

    • taglib—You can very easily define your own tags for use in your GSP files.

    • views—Views of MVC; typically these are GSP files (HTML based).

  • src—Any utilities or common code that don’t fit anywhere else.

    • java—Java code

    • groovy—Groovy code

  • web-app

    • css—CSS stylesheets

    • images—Images used by your web-application

    • js—Your JavaScript files

    • WEB-INF—Spring’s applicationContext.xml goes here

To create a new domain (model) class, run the following:

1   $ grails create-domain-                    class                                                                    

It’s a good idea to include a package for your domain classes (like example.Post).

A domain class in Grails also defines its mapping to the database. For example, here’s a domain class representing a blog post (assuming User and Comment were already created):

 1   class  Post  {
 2       String text
 3       int rating
 4       Date created = new  Date()
 5       User createdBy
 6   
 7       static hasMany = [comments: Comment]
 8   
 9       static constraints = {
10           text(size:10..5000)
11       }
12   }

The static hasMany field is a map that represents one-to-many relationships in your database. Grails uses Hibernate in the background to create tables for all of your domain classes and relationships. Every table gets an id field for the primary key by default.

To have Grails automatically create your controller and views, run the following:

1   $ grails generate-all
A426440_1_En_13_Figa_HTML.jpg Warning

Grails will ask if you want to overwrite existing files if they exist. Be careful when using this command.

When you want to test your app, you simply run the following:

1   $ grails run-app

When you’re ready to deploy to an application container (e.g., Tomcat), you can create a war file by typing this:

1   $ grails war

Plugins

The Grails ecosystem now includes over 1,000 plugins . To list all of the plugins, simply execute this command:

1   $ grails list-plugins

When you’ve picked out a plugin you want to use, execute the following (with the plugin name and version):

1   $ grails install-plugin [NAME] [VERSION]

This will add the plugin to your project. If you decide to uninstall it, simply use the uninstall- plugin command.

REST in Grails

Groovy includes some built-in support for XML, such as the XMLSlurper. Grails also includes converters for converting objects to XML or JSON or vice versa.

 1   import grails.converters.JSON          
 2   import grails.converters.XML
 3   
 4   class  PostController  {
 5               def getPosts = {
 6                       render Post.list() as  JSON
 7               }
 8               def     getPostsXML = {
 9                       render Post.list() as  XML
10               }
11   }

For REST services that service multiple formats, you can use the built-in withFormat in Grails. So the above code would become the following:

1   def getPosts = {
2           withFormat {
3                   json { render list as  JSON }
4                   xml { render list as  XML }
5           }
6   }

Then Grails would decide which format to use based on numerous inputs, the simplest being the extension of the URL such as .json or the request’s Accept header.

For using web services in Grails, there’s a REST plugin2.

Short History of Grails

What follows is a brief history of the features added to Grails starting with version 2.0.

Grails 2.0

There have been a lot of great changes in Grails 2.0:

  • Grails docs are better.

  • Better error page that shows code what caused the problem.

  • H2 database console in development mode (at the URI /dbconsole).

  • Grails 2.0 supports Groovy 1.8.

  • Runtime reloading for typed services, domain classes, src/groovy, and src/java.

  • Run any command with -reloading to dynamically reload it.

  • Binary plugins (jars).

  • Better scaffolding that’s HTML 5 compliant (mobile/tablet ready).

  • PageRenderer and LinkGenerator API for services.

  • Servlet 3.0 async API supported; events plugin; platform core.

  • Resources plugin integrated into core.

  • Plugins for GZIP, cache, bundling (install-plugin cached-resources, zipped-resources).

  • New tags: img, external, and javascript.

  • The jQuery plugin is now the default JavaScript library installed in a Grails application.

  • A new date method has been added to the params object to allow easy, null-safe parsing of dates: def val = params.date('myDate', 'dd-MM-yyyy').

Various GORM improvements include:

  • Support for DetachedCriteria and new findOrCreate and findOrSave methods.

  • GORM now supports MongoDB3, riak4, Cassandra5, neo4j6, redis7, and Amazon SimpleDB.

  • New compile-time checked query DSL (where with a closure): avg, sum, subqueries, .size(), and so on.

  • Multiple scoped data sources.

  • Added database-migration plugin for updating production databases.

Grails 2.1

  • Grails’ Maven support has been improved in a number of significant ways. For example, it is now possible to specify plugins within your pom.xml file.

  • The grails command now supports a -debug option which will start the remote debug agent.

  • Installs the cache plugin by default.

  • In Grails 2.1.1, domain classes now have static methods named first and last that retrieve the first and last instances from the datastore.

Grails 2.2

  • Grails 2.2 supports Groovy 2.

  • Adds new functionality to criteria queries to provide access to Hibernate’s SQL projection API.

  • Supports forked JVM execution of the Tomcat container in development mode.

  • Includes improved support for managing naming conflicts between artifacts provided by an application and its plugins.

Grails 2.3

  • Improved Dependency Management using the same library used by Maven (Aether) by default.

  • Includes a new data binding mechanism that’s more flexible and easier to maintain than the data binder used in previous versions.

  • All major commands can now be forked into a separate JVM, thus isolating the build path from the runtime and test paths.

  • Grails’ REST support has been significantly improved.

  • Grails’ Scaffolding feature has been split into a separate plugin (includes support for generating REST controllers, async controllers, and Spock unit tests).

  • Includes new Asynchronous Programming APIs that allow for asynchronous processing of requests and integrates seamlessly with GORM.

  • Controllers may now be defined in a namespace that allows for multiple controllers to be defined with the same name in different packages.

Grails 2.4

  • Grails 2.4 comes with Groovy 2.3.

  • Uses Hibernate 4.3.5 by default. (Hibernate 3 is still available as an optional install.)

  • The Asset-Pipeline replaces Resources to serve static assets.

  • Now has great support for static type checking and static compilation. The GrailsCompileStatic annotation (from the grails.compiler package) behaves much like the groovy.transform.Compi annotation and provides special handling for Grails.

Grails 3.1.x

Grails 3 represents a huge refactoring of Grails. The public API is now located in the grails package and everything has been redone to use traits. Each new project also features an Application class with a traditional static void main.

Grails 3 comes with Groovy 2.4, Spring 4.1, and Spring Boot 1.2 and the build system now uses Gradle instead of the Gant-based system.

Among other changes, the use of filters has been deprecated and should be replaced with interceptors. To create a new interceptor, use the following command:

1   grails create-interceptor MyInterceptor

An interceptor contains the following methods:

1   boolean before() { true }
2   boolean after() { true }
3   void afterView() {}
  • The before method is executed before a matched action. The return value determines whether the action should execute, allowing you to cancel the action.

  • The after method is executed after the action executes but prior to view rendering. Its return value determines whether the view rendering should execute.

  • The afterView method is executed after view rendering completes.

Grails 3 supports built-in support for Spock/Geb functional tests using the create-functional-test command.

Testing

Grails supports unit testing with a mixin approach. Annotations:

  • @TestFor(X): Specifies the class under test.

  • @Mock(Y): Creates a mock for the given class.

For tests, GORM provides an in-memory mock database that uses a ConcurrentHashMap. You can create tests for tag libraries, command objects, URL-Mappings, XML and JSON, and so on.

Cache Plugin

The Cache plugin can be used to cache content for highly performant web applications.

  • You can add the @Cacheable annotation on Service or Controller methods.

  • cache tags include cache:block, cache:render

  • Includes cache-ehcache, -redis, and –gemfire.

  • Cache configuration DSL.

Grails Wrapper

The Grails wrapper was added in Grails 2.0. You can create the wrapper using the following command:

1   $ grails wrapper

This produces grailsw and grailsw.bat (for *nix and Windows, respectively).

The Grails wrapper is helpful when multiple people are working on a project. The wrapper scripts will actually download and install Grails when run. Then you can send these scripts to anyone or keep them in your repository.

Cloud

Grails is supported by the following cloud providers:

  • CloudFoundry8

  • Amazon9

  • Heroku10

A426440_1_En_13_Figb_HTML.jpg Only an Overview

This has been a brief overview of Grails. Many books have been written about Grails and how to use it. For more information on using Grails, visit grails.org 11.

A426440_1_En_13_Figc_HTML.jpg Exercise

Create your own Grails app and then deploy it in the cloud.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233