Groovy

Groovy & Grails Understanding – Part2

Grails

Grails is a web framework based on Groovy and Java which can be deployed into existing Java web servers, e.g. Tomcat or Jetty. Its scaffolding capabilities let you create a new project within a few minutes. Grails is based on the “convention over configuration” idea which allows the application to auto-wires itself based on naming schemes (instead of using configuration files, e.gl XML files).

The Grails framework allows instance development without requiring any configuration. Grails accomplish this by automatically providing the Tomcat web container and the HSQLDB database during development. Grails uses GORM (Grails
 
Object Relational Mapping) for the persistence of the domain model. GORM is based on Hibernate. You can test with the HSQLDB and run in production against another database simply by changing the configuration file (DataSource.groovy). Grails uses Java EE as the architectural basis and Spring for structuring the application via dependency injection. Grails is plug-in based and provides its own build system (Gant). The Grails homepage provides several pre-defined plugins which extend the Grails framework. Grails has been developed with a number of goals in mind:

  • Provide a high-productivity web framework for the Java platform.
  • Re-use proven Java technologies such as Hibernate and Spring under a simple, consistent interface
  • Offer a consistent framework which reduces confusion and is easy to learn.
  • Offer documentation for those parts of the framework which matter for its users.
  • Provide what users expect in areas which are often complex and inconsistent:
    • Powerful and consistent persistence framework.
    • Powerful and easy to use view templates using GSP (Groovy Server Pages).
    • Dynamic tag libraries to easily create web page components.
    • Good Ajax support which is easy to extend and customize.
  • Provide sample applications which demonstrate the power of the framework.
  • Provide a complete development mode, including web server and automatic reload of resources.

Architecture

Grails is an open source web application framework which leverages on Groovy (Figure 2: Grails is build on top of Groovy). It was first developed in 2005 and the first “1.0” release was announced in 2008 .

Arch1
Figure : Grails is build on top of Groovy

Arch2
Figure : Grails Architecture

Grails builds on several well-established software frameworks, and combines their functionality via Groovy. These frameworks include Java Enterprise Edition (Java EE, JEE), spring, Hibernate and Quartz. Grails combines the speed of scripting languages with the stability and security of Java and is therefore ideally suited for enterprise use.

The Grails Directory Structure

The Grails project structure (shown in Figure 3 below) relies heavily on convention and establishes a sensible organizational structure for an application’s various artifacts.

folderStructure
Figure: Project Structure

Environment Setting

Need to follow below steps for Grails environment setup

  • Install JDK1.5 or higher from oracle
  • Point the JAVA_HOME environment variable at your JDK installation.
  • Download the latest release of Grails from http://grails.org/Download.
  • Unzip Grails
  • Create a GRAILS_HOME environment variable
  • Add GRAILS_HOME/bin to the PATH

Domain Classes

Domain classes are the lifeblood of a Grails application. A corresponding database table is automatically created for each domain class. Controllers and views derive their names from the associated domain class. This is where validation rules are stored, one-to-many relationships are defined, and much more. Below command to create domain class:

grails create-domain-class domain-class-name

Notice that Grails creates both a domain class and a test class. We’ll put the test class to use later. For now, let’s focus on the domain class

Scaffolding Controllers and Views

Controllers and views round out the “Big Three” in Grails applications. The Model/View/Controller (MVC) pattern is undoubtedly familiar to most web developers. By enforcing a clean separation of concerns among these three elements, your efforts are paid back in terms of maximum flexibility and reuse. Grails supports both static and dynamic scaffolding. The First example will show how to work with the static scaffolding. And afterwards there will be a small example on how to use dynamic scaffolding

Static Scaffolding

To generate the scaffolds in Grails, the following command will need to be executed through the command-line inside the project directory

staticScafolding

In this example, the ‘Address’ domain class will be scaffolded. The Controller and Views will now be generated for the developer. The way the code is generated, is based on templates that can be changed. Next to the CRUD actions, Grails adds the “list” action. The “edit” and “save” functions work together with “update” and “create”.

Createcreate.gspCreates a new address
Readshow.gspShow one address (Based on ID)
Updateedit.gspRetrieve one address (Based on ID) that needs to be changed
DeleteNo viewDelete one address (Based on ID)
Listlist.gspList all addresses
EditNo viewSave the updated address
SaveNo viewSaves the newly created address

The AddressController now looks like this. The functions are self-explanatory.

Class AddressController {
Def index = { redirect (action:list, param:param)}
//delete , save and update actions only accept post requests
def allowedMethods =[delete: ‘POST’ , save:’POST’ , update: ‘POST’]
def list = {//…….}
def show = {//…….}
def delete = {//…….}
def edit = {//…….}
def update = {//…….}
def create = {//…….}
def save = {//…….}

Dynamic Scaffolding

Dynamic Scaffolding in Grails is really easy. This can be achieved by adding the following line inside the controller that needs to be scaffolded.

def scaffold =true

The CRUD actions and views will be automatically generated at runtime for the previously defined model

Databases – GORM

The Grails Object-Relational Mapping API allows us to stay squarely in an Object frame of mind – no getting bogged down in relational database-related SQL. GORM is a thin Groovy façade over Hibernate. While creating an application, Grails automatically creates a Data source class where configurations for different environments can be defined. This allows for an easy switch between the development, test and production stage of a project. GORM data source could be configured on grailsapp/conf/DataSource.groovy

dataSource {
pooled = true
driverClassName = “org.hsqldb.jdbcDriver”
username =”sa”
password = “”
}
Hibernate {
Cache.use_second_level_cache = true
Cache.use_query_cache = “true”
Cache.provider_class = ‘com.opensymphony.oscace.hibernate.OSCachePovider’
}
Environment {
Development {
dataSource {
// one of ‘create’, create-drop’ , ‘update’
dbCreate= “create-drop”
urk = “jdbc:hsqldb:main:devDB”
}
}
Production {
dataSource {
dbCreate = “update”
url = “jdbc:hsqldb:file:prodDB;shutdown=true”
}
}
}

Controllers

View and Controller will be generated based on the Model and will automatically implement CRUD actions. Here we will expose the default scaffolded Controller code so that and relationship between actions in the Controllers and the URL. It will also allow us to see the relationship between action and the corresponding Groovy Server Pages (GSPs).

create-controller vs. generate-controller

Controller will be generated using scaffolding not only it generate controller but also generate GSP view using def scaffold =true. Normally I’d have you type “grails create-controller User” at this point. Recall that the create-* commands create an empty, stubbed out class. Instead, type grails generate-all User. The generate-all command writes out a fully implemented controller and a corresponding set of GSP views. (You can also type generate-views to see just the GSPs, or generate-controller to create just the Controller.) Instead of the one-line Controller you are used to seeing, you’ll now see 100 lines of Groovy code

URLs and Controllers

Class UserController {
Static allowedMethods = {save: “POST”, update : “POST” , delete: “POST”|
def index = {
redirect {action: “lisy” , params}
}
def list = {
params.max = Math.mi(params.max ?
                        params.int(‘max’) :10,100)
def create = {
def userInstance =new User ()
userInstance.properties = paams
return { userInstance : userInstance}
def save = {//…….}
def show = {//…….}
def delete = {//…….}
def edit = {//…….}
def update = {//…….}
}

Consider the types of URLs we saw as we worked our way through the application: http://localhost:9090/application/user/show/2 Each component of the URL plays an important role in the Grails convention. And it’s by following that convention that we (thankfully) free ourselves from having to wire together our URLs, controllers, and views in external configuration files

UrlsLInk

The first part of the URL is the application name, or Application Context Root. The next part of the URL is the controller name. Notice that the Controller part of UserController gets dropped off, and the first letter is changed to lowercase. After the controller name, you’ll see an optional action name. This name corresponds directly to the action in the Controller.

If we try “http://localhost:9090/application/user” in our web browser, we will end up with an empty list of users. Since no action is specified, Grails routes the request to the index action. The index action, in turn, redirects the request to the list action, passing along the query string as well. The name:value structure used in the redirect method is used throughout Controllers.

GSP

Grails uses GSP for the presentation tier. The Groovy in Groovy Server Pages not only identifies the underlying technology, but also the language you can use if you want to write a quick scriptlet or two. Groovy Taglib and partial templates give you a more sophisticated way of sharing code and behavior across Web pages. GSPs are the foundation of Grails’ page-centric MVC world view. The page is the basic unit of measure. The List page offers links to the Show page. The Show page allows you to click through to the Edit page, and so on. Whether you’re a seasoned Struts developer or a recent Rails enthusiast, you’re already familiar with this type of Web life cycle.

A sample GSP page (list.gsp) depicted below:

<g:each in=”${userInstanceList}”
Satus=”i” var=”userInstance”>
<tr class=”${(i%2)==0?’odd’ : ‘event’}”>
<td>
<g:link action=”show” id=”${userInstance.id}”>
${fieldValue{bean:userInstance, field:’id’)}
</g:link>
</td>
<td>${fieldValue(bean:userInstance, field:’login’)}</td>
<td>${fieldValue(bean:userInstance, field:’password’)}</td>

<td>${fieldValue(bean:userInstance, field:’role’)}</td>

Scopes in Grails

There are four scopes in Grails: request, flash, session, and application. Each one has a different lifespan

  1. Variables placed in request scope last just long enough to be displayed in the response and then are discarded.
  2. Values in flash scope (commonly used for error messages in Grails) can survive a single redirect.
  3. Session scope is used for values that should stick around for multiple requests, but are limited to the current user.
  4. Values placed in application scope are “global”—they last for as long as Grails is running, and they are shared across all users.

Services

Grails Service uses to separate your business logic from the other layer or component. Services are named in the format SomeNameService.groovy and placed in the directory /grails-app/services/. Services can make use of dependency injection features, and you can easily call these services from within controllers.

Class SearchableService {
Booleab transactional =true
def compass
def compassGps
def searchableMethodFactory
def search (Object[] args){
searcgableMethodFactory.getMethod(“searcg”).invoke(*args)
}

Above depicts the SearchableService. SearchableService (stored in grailsapp/services) got added to the SearchableController automatically using single line def searchableService right after the class declaration of the Controller. This is the way Grails uses dependency injection, or “DI” for short. Unit Testing Controllers

Plug-in

Grails plugins are like JARs on steroids. They can include not only one or more JARs, but also GSPs, Controllers, TagLibs, Codecs, and more. In essence, they are mini Grails applications expressly meant to be merged with other Grails applications.

Unit Testing

GrailsUnitTestCase and GroovyTestCase both extend JUnit 3.x TestCase.MVC Unit Test case will extend GrailsUNitTest case and delegate the test case control to ControllerUnitTestCase and TagLibUnitTestCase

UNit Test

GrailsUnitTestCase and its offspring offer mock services that replicate the services available in integration tests, without incurring the overhead of running the real services. A GrailsUnitTestCase makes three convenience methods available: mockForConstraintsTests(), mockDomain(), and mockLogging(). Normally you would have to create an integration test to write assertions against this functionality. And you still can, if you’d like. But knowing that unit tests run much faster than integration tests, it’s nice to be able to mock this behavior out.

Import grails.test.*
Class UserTests extends GrailsUnitTestCase {
Void testsimpleConstraints {
Def user = new User ( login: “someone”, password: “xxx”, role :”admin”)
assertFals user.validate()
}}

For example, suppose that you’d like to test the validation on the User class.

Deployment

We can easily generate a WAR file and deploy it to Tomcat, JBoss, GlassFish, or the application server of your choice. Command “grails clean” will clean and to make sure that there aren’t any lingering development-mode artifacts hanging around. After clean command execute grails war . You should end up with a genuine JEE WAR file, suitable for deploying to any Java application server

Import grails.test.*
Class UserTests extends GrailsUnitTestCase {
Void testsimpleConstraints {
Def user = new User ( login: “someone”, password: “xxx”, role :”admin”)
assertFals user.validate()
}}

No additional server configuration is necessary to deploy your WAR – it includes the Groovy JAR, the Grails supporting JARs, and everything else that you added to the lib directory.

Summary

Grails’s main target is to develop web application quickly and rapidly in agile manner. Grails is based on Convention over configuration and DRY(Don’t Repeat yourself) and not only that we can re use existing java code in Grails that give power to build robust and stable web application in quickly and rapid manner. This paper explained the usage and best practices around the Groovy and Grails.

Resources

 

Reference: Groovy & Grails Understanding – Part2 from our JCG partner Nitin Kumar at the Tech My Talk blog.

Nitin Kumar

Nitin Kumar works as a Software Architect , predominately focus on Agile, TDD, Service Oriented Architecture, Grails and JEE. Besides working in software development, He writes technical articles and watches and studies new technologies
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button