Day 6: Rapid Web Development on the JVM with Grails - Archived

On 6th day of 30 technologies in 30 days challenge, I have decided to learn the Grails web application framework.

Grails is an open source web framework built on Groovy and Java.
Its a JVM response to the popular Rails or Django web frameworks, helping developers quickly craft applications that can be fronted with standard Jetty or Tomcat servers. In this blog, we’ll cover building a simple web application using the Grails Eclipse plugin.

Why should we care about Grails?

The two reasons why I considered learning Grails are :

  1. Rapid web development: It can help us achieve productivity benefits similar to Rails or Django but without leaving JVM and Java knowledge.

  2. Powered by proven technologies: Grails underneath uses Spring and Hibernate to power web applications. It can be considered as syntactic sugar over these technologies.

Prerequisites

  1. Basic Java knowledge is required.

  2. Install the latest Java Development Kit (JDK) on your operating system. You can either install OpenJDK 7 or Oracle JDK 7. OpenShift support OpenJDK 6 and 7.

  3. Download the latest Eclipse package for your operating system from official Eclipse website. At the time of writing this blog, the latest Eclipse package is called Kepler.

Download Eclipse

It is very easy to install eclipse , just extract the downloaded package and you are done. On linux or mac machines , open a new command line terminal and type command shown below.

$ tar -xzvf eclipse-jee-kepler-R-*.tar.gz 

On windows you can extract the zip file using winzip or 7-zip or any other software.
After extracting the Eclipse archive, you should have a local eclipse folder available. You can optionally create a shortcut to the executable file.

Installing Grails

Please refer to the Grails getting started guide for information.

The Grails version that we will be using in this blog is 2.3.1. Run the grails -version command to check the version number.

$ grails -version
Grails version: 2.3.1

When I first ran the version command, I got the following exception.

$ grails -version
Exception in thread "main" java.lang.NoClassDefFoundError:
org/codehaus/groovy/grails/cli/support/GrailsStarter

The reason for the exception is that there is an older installation of Grails on the machine. On a mac, go to /usr/local/bin and you might find another installation. I sometime back unknowingly installed grails using brew, so I uninstalled it.

brew uninstall grails

Step 1 : Install Eclipse Grails plugin

After extracting the Eclipse Kepler IDE for Java EE, open Eclipse and then navigate to project workspace. Go to Help > Eclipse Marketplace, and then search for Grails. Install the “Groovy/Grails Tool Suite(GGTS) for Eclipse Kepler(4.3)“. Restart Eclipse after installing the plugins.

Step 2 : Create a new Grails project

In this blog, we will build a simple link sharing application. The user can first registers himself/herself with the application and then submit links.

Create a new grails project by clicking File > New > Grails Project and enter the details. The name of application is linkbin.

Eclipse create new project

The first time we create Grails project we also have to configure Grails installation. Click on “Configure Grails Installations” and then add a new Grail installation.

Eclipse add new grails installation

We can also specify a different location for the project as shown below and press the “Finish” button.

Eclipse change default location

Eclipse will ask us whether we want to open the “Grails perspective”, say yes. The project is created and then imported into Eclipse.

Eclipse import application

Step 3 : Create domain model

The application domain model is very simple. We have two entities: User and Story

The User entity has two fields: email and fullName. We’ve added not blank, email, and unique constraints on the email field. The email constraint provides email format validation for this field. fullName has not blank and size constraints. The size constraint is uses groovy range to restrict the size of a collection, number, or the length of a String. To create a new domain class, right click on the domain and then select New > Domain Class.

Eclipse create Domain class

This will create the User domain class. Replace the User domain class code with the code shown below.

package linkbin
 
class User {
    String email
    String fullName
    static constraints = {
        email unique:true , blank : false , email:true
        fullName size:5..100  , blank : false
    }
}

The Story entity has three fields: link, description, and submittedOn. The link field corresponds to the web url that the user will submit. The description and submittedOn fields are for additional text for the link and submission date. We have added not blank constraints to our link and description fields. Also, unique and url constraints have been added to the link field.

package linkbin
 
class Story {
    String link
    String description
    Date submittedOn
 
    static constraints = {
        link url : true , blank : false ,unique : true 
        description size : 10..1000 , blank : false 
    }
}

Now we will add relationship between User and Story. A user can submit many stories, and story belongs to a user. The relationship is shown below.

package linkbin
class User {
    String email
    String fullName
    static hasMany = [stories : Story]
    static constraints = {
        email unique:true , blank : false , email:true
        fullName size:5..100  , blank : false
    }
    static mapping = {
        table 'users'
    }
}

A story belongs to a user:

package linkbin
class Story {
    String link
    String description
    Date submittedOn  
    static belongsTo = [user : User]
    static constraints = {
        link url : true , blank : false ,unique : true 
        description size : 10..1000 , blank : false 
    }
    static mapping = {
        table 'stories'
    }
}

Step 4 : Scaffold controllers and views from domain model

Grails make it very easy to generate controller and view for the domain model. To generate controller and view for User domain class open the “Grails Command Wizard”.

Eclipse open grails command wizard

It will open the command wizard where we can see all the grails command. We will use the generate-all command to generate controller and views.

Eclipse generate all

Next it will ask the name of the domain class. Enter linkbin.User and press the “Finish” button.

<img style=”width: 50%;” alt=”Eclipse generate all class name” src=”https://www.openshift.com/sites/default/files/images/generate-all-class-name.preview.png />

Similarly, generate controller and views for the Story domain class.

The generate-all command generates CRUD controllers and views for both the entities.

Step 5 : Run the application

All grails project has inbuilt support for running an embedded tomcat server. To run the project locally, right click on the project, and then select “Run as grails app“.

Run as Grails App

This will start an embedded tomcat servlet container, and we will see the following logs in the console.

| Loading Grails 2.3.1
| Configuring classpath.
| Environment set to development.....
| Packaging Grails application.....
| Running Grails application
| Server running. Browse to http://localhost:8080/linkbin

Step 6 : Deploy to the cloud

The grails apps are packaged as war files. OpenShift is an open source, public, scalable Platform as a Service. If you are a Java, Python, Node.js, Ruby, or PHP developer, then you should take a look at OpenShift. OpenShift is a public Platform as a Service, and you can use it to deploy your applications for free.

Before we deploy the application to OpenShift, we’ll have to do few setup tasks :

  1. Sign up for an OpenShift Account. It is completely free and Red Hat gives every user three free Gears on which to run your applications. At the time of this writing, the combined resources allocated for each user is 1.5 GB of memory and 3 GB of disk space.
  2. Install the rhc client tool on your machine. rhc is installable as a ruby gem, so you need to have ruby 1.8.7 or above on your machine. To install rhc, just type:

sudo gem install rhc

To update rhc to the latest version, execute the following command:

sudo gem update rhc

For additional assistance setting up the rhc command-line tool, see the following page: https://openshift.redhat.com/community/developers/rhc-client-tools-install

  1. Setup your OpenShift account using rhc setup command. This command will help you create a namespace and upload your ssh keys to OpenShift server.

OpenShift also has eclipse plugin, but in this blog I will use OpenShift rhc command line tool.

After setup, we can create OpenShift application by running the following command.

$ rhc create-app linkbin tomcat-7 postgresql-9.2

This will create an application container for us, called a gear, and setup all of the required SELinux policies and cgroup configuration. OpenShift will also setup a private git repository for us and clone the repository to the local system. Finally, OpenShift will propagate the DNS to the outside world. The application will be accessible at http://linkbin-domain-name.rhcloud.com/. Replace domain-name with your own unique OpenShift domain name (also sometimes called a namespace).

As we will be deploying war file, so we have to delete the default source generated by OpenShift.

$ git rm -rf src/ pom.xml
$ git commit -am "deleted default source code"

Go to Eclipse, and change the datasource configuration to use postgresql. Grails maintain all database configuration in conf/Datasource.groovy. Update the production configuration to use PostgreSQL settings.

production {
    dataSource {
        dbCreate = "update"
        driverClassName = "org.postgresql.Driver"
        dialect = org.hibernate.dialect.PostgreSQLDialect   
    uri = new URI(System.env.OPENSHIFT_POSTGRESQL_DB_URL)
    url = "jdbc:postgresql://"+uri.host+uri.path+"/"+System.env.OPENSHIFT_APP_NAME
        username = System.env.OPENSHIFT_POSTGRESQL_DB_USERNAME
        password = System.env.OPENSHIFT_POSTGRESQL_DB_PASSWORD
    }
}

Now we have to package the grails application into a war file. To do that, we will use grails war command. Open the “Grails Command Wizard”, use war command. It will ask for a war file name, give the name as target/ROOT.war. It will generate ROOT.war in the target folder. Copy ROOT.war to your OpenShift linkbin application webapps folder.

Now add the war to your git repository and push the changes.

$ git add .
$ git commit -am "linkbin app deployed to cloud"
$ git push

After code is pushed and war is successfully deployed, we can view the application running at http://linkbin-{domain-name}.rhcloud.com.

A functional demo of the resulting project is available for review at http://linkbin-shekhargulati.rhcloud.com.

That’s it for today — I hope this blog will be useful for fellow developers. Keep the feedback coming!

Next Steps

Categories
Java, OpenShift Online
Tags
Comments are closed.