Grails An Agile and Friendly Framework

0
4940

Grail Web framework

Grails is an open source Web application framework for the Java Virtual Machine. In this article, the author introduces developers to the ‘holy grail’ in software—the Grails Framework.

In the competitive world of start-ups and business expansion, a software developer is always hunting for the best technology to build applications faster. This article is an introduction to Grails, which according to Wikipedia, “… is an open source Web application framework that uses the Groovy programming language (which is in turn based on the Java platform).” If you have never worked with Groovy before, you shouldn’t worry because standard Java language constructs work as is, in Groovy. And if you know scripting languages like Python or Ruby, you will find that Groovy is very intuitive and simple to use. Another obvious reason to use Grails is that it provides built-in support for well-developed Java technologies like Spring and Hibernate, which makes migrating from a Java stack to Grails a very painless and simple process. Being a Web framework, it uses the well-tested MVC design paradigm. Quoting Wikipedia again, some of the other key features of Grails is that it offers documentation for key portions of the framework like:

  • The Persistence framework
  • Templates using GSP (Groovy Server Pages)
  • Dynamic tag libraries for creating Web page components
  • Customisable and extensible Ajax support

As a consequence, Grails is one of the most productive amongst frameworks.

Getting started
To get started with Grails on a Linux machine, follow the steps shown below. I am using Ubuntu 12.04, so in case you’re using another distro, you can easily adapt the following steps accordingly.
1. Installing JDK: On Ubuntu, you can type the following command into the terminal to install the JDK.

sudo apt-get install openjdk-6-jdk

You can alternatively use the Sun version of Java as well, but use version 6 of the OpenJDK for maximum compatibility with Grails.
2. Installing GVM (Groovy enVironment Manager): The GVM is a command line tool that helps you manage different versions of the SDK on UNIX systems. Using GVM, you can install multiple versions of Grails and Switch easily. Let’s install GVM by first using curl (a UNIX tool used to download files) to get the GVM script and then execute it. So before starting, ensure you have curl installed on your system by using the following command.

sudo apt-get install curl

After running the above command, you can use the following command to download the GVM script and execute it.

curl -s get.gvmtool.net | bash

After the script completes, you will be asked to open a new terminal and run a command in it, which will be similar to the one that follows:

source "/home/username/.gvm/bin/gvm-init.sh"

After you run the above script, you’ll be able to use the GVM to install Grails.

3. Installing Grails: Run the following command to install the latest currently available version of Grails.

gvm install grails

To install a specific version of Grails (say, version 2.3.2), you can run the following command.

gvm install grails-2.3.2

4. Testing your installation: The simplest way to test your installation of Grails is to use it to create a project. Use the following command to create a new Grails project.

mkdir test
cd test
grails create-app test
A sample project
1GrailsFolder
Figure 1 : Grails folder

The above command creates an application for you. In our above example, we used the name ‘test’ for our project. The really nifty thing about Grails (or any other Web framework) is that it provides a boilerplate application, which is ready to be used with minimal changes. Since Grails follows a ‘code by convention’ paradigm, you can build an application very quickly if you get familiar with the Grails standard conventions. The best way to figure out some of the more obvious conventions used in Grails is to look at the boilerplate application created for you. Figure 1 gives a screenshot of the files and folders Grails generates for you.
For your reference, here is a breakdown of the folder structure of Grails.

  • grails-app: Top level directory for Groovy sources
  • conf: Configuration sources
  • controllers: Web controllers – the ‘C’ in MVC
  • domain: The application domain
  • i18n: Support for internationalisation (i18n)
  • services: The service layer
  • taglib: Tag libraries
  • utils: Grails specific utilities
  • views: Groovy server pages – the ‘V’ in MVC
  • scripts: Gant scripts
  • src: Supporting sources
  • groovy: Other Groovy sources
  • java: Other Java sources
  • test: Unit and integration tests

Now let’s see Grails in action. To run the pre-built application, use the following commands.

cd test
grails run-app

At this point, Grails will install all the dependencies and do a couple of complex optimisations, which it displays on your screen. When it is ready, it will print the following message.

Server running. Browse to http://localhost:8080/test

At this point, you can fire up your browser and type that URL into the URL bar (Pro tip: if you’re feeling a bit lazy, clicking Control on the link in the terminal will open the link in your default browser).
When you go to the URL, you’ll be able to see a page like the screenshot given in Figure 2, which lists specifics about various plugins and your application’s configuration details. If you do see this screen, you’ve successfully installed Grails for your development environment.

2grailsScreenShot
Figure 2 : Grails screenshot

Warning: The run-app command is intended for development purposes only. It isn’t meant to be used for production environments. In production, you could use Grails to build WAR (Web Application Archive) files and then deploy it on an Apache Tomcat server, for instance, because a lot of possible optimisations aren’t supported by the Grails’ run-app server.

GORM
GORM is Grails’ object relational mapping (ORM) implementation. Under the hood, it uses Hibernate 3 (a very popular and flexible open source ORM solution). Thanks to the dynamic nature of Groovy, with its static and dynamic typing, along with the convention of Grails, there is much less configuration involved in creating Grails domain classes. While this is a topic that requires a separate article and a lot of practice, I will try to cover the main points about GORM. Grails is known as a domain driven language, which means that an application can be built in a bottom-up manner. Domain classes are the core of any business application. They can be linked together through relationships which can be one-to-one, one-to-many or many-to-many. By default, Grails applications are configured to use an in-memory database called HSQLDB. For the purposes of this tutorial, I will walk you through setting up MySQL. To do so, follow the steps listed below.

1. Creating a database in MySQL: Use the following command in MySQL to create a database.

CREATE DATABASE test_prod

This will create a database called test_prod, which we will use in production. Additionally, we can create a database called test_dev, which can be used in development mode for testing our application.
2. Updating the BuildConfig.groovy file in grails-app/conf: We do this to tell Grails that our application needs to use the MySQL connector, so we need to add that as a dependency to our application. All dependencies must be specified in this file. When your application is run, all dependencies specified here are automatically downloaded and installed so that your application can use them. Open up the BuildConfig file located in the grails-app/conf folder and find the line…

// runtime 'mysql:mysql-connector-java:5.1.24'

…and uncomment it. The complete BuildConfig file can be downloaded from https://www.opensourceforu.com/article_source_code/sept14/grails.zip
3. Updating DataSource.groovy in grails-app/conf: After setting up the dependencies, we must set up our application to use certain data sources. In our project, we’d like it to use our test_dev for development purposes and test_prod for production. First, we must edit the DataSource variable so that it knows how to use the InnoDB engine, as follows:

dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
}

The next step is to configure the environments variable to use test_dev for development and test_prod for production.
Edit your environment’s variable as shown in the code snippet below.

environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:mysql://localhost/test_dev”
username = "root"
password = "root"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost/test_prod"
username = "root"
password = "root"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost/test_prod"
username = "root"
password = "root"
}
}
}

dbCreate deserves a special mention. It determines what happens to your database between server restarts. For example, a value of create-drop means that the database tables will be dropped and then recreated when you start the server, so you lose any data that was in there. This is fine for testing, but is definitely not what you want in production.

4. Creating a new domain class: We’re done with setting up Grails to use MySQL; so now we can simply create a domain class which will be persisted in our database. Let’s create a domain class that represents a user of our application, using the following command.

grails create-domain-class test.User

After this, Grails will tell you that it created a few files. Let’s now edit Grails app/domain/test/User.groovy file to store the information of our users. The following is the edited User.groovy file.

package test

class User {
long userid
String username
String password
static constraints = {
userid(unique:true)
username(blank: false)
password(blank:false)
}
}
3mySqlScreenShot
Figure 3 : My SQL screenshot
4userControllerscreenShot2
Figure 4 : UserController screenshot

 

 

 

 

 

 

5. To create a controller for User.groovy, type:

grails create-controller test.User

Update the file UserController.groovy under grails-app/controller/test.
Inside the controller, we will define a scaffold that will automatically create the CRUD (Create, Read, Update, Delete) function for our domain class.
Your final UserController.groovy will look like what follows:

package test
class UserController {
def scaffold = User
def index() { }
}

Let’s check everything out by running our application, so run the following in your terminal:

grails run-app

Now, if you check out your MySQL databases, you’ll notice that a table called ‘user’ has been created. The userid field has a constraint of being unique, while the ‘username’ and ‘password’ fields are strings that cannot be blank.
If you check the contents of the table called ‘user’, user it’ll be empty. You can check this with the following command.

select * from user;

Let’s navigate to the http://localhost:8080/test URL. There we will be able to see our new controller. Click on it to start CRUD activities.
Next, let’s create a new user by clicking on the ‘new user’ button.
Finally, let’s check if our data has been inserted into our table in MySQL.
This is how you integrate MySQL with a Grails application. Grails is not limited to MySQL. You can also use any other database like PostgreSQL or MongoDB.

5userControllerScreenShot
Figure 5 : New Controller added to grails
6 createUser
Figure 6 : Create user
7mySql
Figure 7 : MySQL query output

Advice for the veterans
This section gives you some of the best practices in Grails, which will help you rapidly develop applications and tools with this framework.
1. Always use a domain-driven design: First, create your basic domain model classes and then use scaffolding to get them online. This will help you stay motivated and understand your domain better.
2. Follow Grails conventions: Grails is a convention-driven development environment.
3. Use DataSource.groovy: Use DataSource.groovy to configure data sources.
4. Use BuildConfig.groovy: This is to install any plugin in your application rather than using the ‘install-plugin’ command.
5. Keep your view simple: Make your views as simple as possible.
6. Use layouts: Use a layout for a consistent look across your UI.
7. DRY: Keep your views DRY (‘Don’t repeat yourself’). Split the repeated content into templates.
8. Automate the process: Write scripts to automate any repetitive tasks. This will reduce errors and improve overall productivity.
9. The location convention: Services go into the Services folder. Controllers go into the Controller folder.
10. The naming convention: All models, services, controllers and scripts should be named consistently. In our example application, we had a model named ‘User’; hence, our controller was named ‘UserController’. Grails will link them
based on the naming convention.

With Grails, we can develop applications quickly and in an agile manner. Since it is based on well tested paradigms like ‘Convention over configuration’ and DRY, Grails provides a robust platform for development. In a world where developers race against the clock to meet vicious deadlines, having a framework which provides so many built-in features makes Grails an invaluable tool.

LEAVE A REPLY

Please enter your comment!
Please enter your name here