Saturday, July 30, 2011

GRAILS Tutorial -- Head Start

In this post I will make a sample application. I have also provided download option at the end of the post in  zip format.

If this is the first time you are looking into grails then I would suggest you to go through my blog post here and make sure that your grails setup is up and running.

In this sample I will show you how to create a domain class, a controller and also basic CRUD operation using GRAILS scaffolding feature. I will be using grails console for giving all commands and eclipse for doing my code editing.

We will make a sample application for a school. let's say SchoolApp. First step for starting a GRAILS application is creating an application using the create-app command. so go ahead and type the below command.


grails create-app SchoolApp 

As soon as you execute this command grails will create complete application structure for you. Now that we are done with our app creation we will go to our first domain class.

We will create a domain class named Student. To do this go into the SchoolApp directory and type the below command.


grails create-domain-class Student

Once done you should find two files created.
  • Student.groovy (grails-app/domain)
  • StudentTests.groovy (test/unit)
The Student.groovy file will have below piece of code.
class Student {
    
   static constraints = {
    }   
}
Lets add some fields to our Student class.
class Student {

    Integer rollNumber;
    String name;
    Date dob;
    Integer age;    
}
I have added 4 fields to our domain class. Also note that I have removed the static constraints section as it was not of any use to us as of now.

We will create a controller for our Student class. Execute the below command to create a controller.

grails create-controller Student

Again you should find two files created.
  • StudentController.groovy (grails-app/controllers)
  • StudentControllerTests.groovy (grails-app/unit)
The StudentController.groovy will have below piece of code.
class StudentController {

  def index = { }    
}
Now, we will add scaffolding feature to our controller.
class StudentController {

  def Scaffold = Student    
}
So, that's it. Our CRUD for Student class is ready for use. I have also removed the def index = { } from the generated code as again it is not needed.

Next, we are going to run our app. To do this we will execute the below command.

grails run-app

In case you get something like below.

Server failed to start: java.net.BindException: Address already in use

It means that your port 8080 is already been used by some other service. So you will need to change your port to say 9090. To do this kindly go through my post here.

If things go well then you should receive a message like below.

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

Now, go and hit to the url above in your browser. You will get below page with you controller named StudentController.











When you click on the StudentController you will be able to do CRUD for Student class.

Grails comes bundled with HSQLDB. In case you want to change it to MYSQL or you want to get some information about various database settings and environments within grails, then you can go through my datasource post here.

The download zip of the code is here.

Once you download the zip file, extract it and go inside the SchoolApp folder. Then do a grails run-app as shown above.

In my next post I will show you how to do Relational Mappings, views of grails (GSP's)  etc. Stay tuned.

If you have any suggestions or if you are having any problem in running this sample application, Kindly leave a message and I will get back to you at the earliest.

Saturday, June 25, 2011

GRAILS Configuration -- Port Settings

Port settings for grails can be done at
$GRAILS_HOME/scripts/_GrailsSettings.groovy.
Just look for below piece of code
serverPort = getPropertyValue("server.port", 8080).toInteger()
Change the port number to your liking.
Note: port settings is no more available in the init.groovy file.

GRAILS Configuration -- Proxy Settings

There are two commands to set proxy in GRAILS.
  • Add Proxy - adds a proxy server setting in proxysettings.groovy file
  • Set Proxy - sets the current proxy in the proxysettings.groovy file.
grails add-proxy client --host=proxy-server --port=4300 --username=guest --password=guest
grails set-proxy client
For example:
grails add-proxy myproxy --host=internet --port=8085
grails set-proxy myproxy
If you are using windows console then you will need to enclose parameters with double quotes.
grails add-proxy myproxy "--host=internet" "--port=8085"
grails set-proxy myproxy
Settings can then be verified in the proxysettings.groovy file. This file can be located in the .grails folder.

Sunday, June 19, 2011

GRAILS Configuration -- DataSource

The dataSource.groovy file is used for database configuration within Grails. Grails by default comes bundled with HSQLDB. The are three basic environments and settings available for configuration.

ENVIRONMENTS
  • development
  • test
  • production

SETTINGS / DbCreate
  • create-drop : Creates all the tables when application is started and drops them when application shuts down.
  • create : Creates all the tables when application starts.
  • update : Updates already created tables. Used in production mode.
URL : This option specifies which url and which database to hit for a particular environment.

As soon as a new app is created, the datasource file will be configured to HSQLDB. Below is the code.


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 = 'net.sf.ehcache.hibernate.EhCacheProvider'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
            url = "jdbc:hsqldb:mem:devDB"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:mem:testDb"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:file:prodDb;shutdown=true"
        }
    }
}


  1. First section specifies the driver of the database and also login credentails.
  2. Second section is for hibernate settings.
  3. Third section is for dbCreate and url settings for each of the environment.
For configuring the datasource to MYSQL, Firstly the MYSQL JDBC Connector JAR needs to be added to the lib folder. The JAR can be found here. So, finally the datasource for MYSQL could be something like below.


dataSource {
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    username = "root"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
            url = "jdbc:mysql://localhost/devDb"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost/testDb"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost/prodDb"
        }
    }
}


Also, when we do a Grails run-app it runs the application in dev environment by default.
So, in order to run it in test environment use


grails run-app (will run in development environment by default)
grails test run-app (will run in test environment)
grails [env]* run-app (Basic Syntax)



Wednesday, June 1, 2011

GRAILS Getting Started

I have been working in GRAILS for more than a year and was very much impressed with the simplicity and power of this framework. It's a JAVA/J2EE framework which is based on GROOVY and SPRING SOURCE. The framework follows a convention over configuration design. In short, it helps me to get rid of loads and loads of xml configuration.

INSTALL GRAILS

Installing GRAILS should be a piece of cake for any java developer. Infact you can even install grails and groovy directly from your eclipse spring tool suite. Anyways its up to you but I rather like the console version for commands.

CREATE APP

This is basically the first step of GRAILS. This can be done directly from console or from your Spring Tool Suite Dashboard.

Once Grails support is installed for your spring tool suite, you will get an option of creating a new grails project from the STS dashboard. 



This is the console command for creating a new web project or app. 





Beware : The console command will create your new project in the current working directory whereas the STS will create it in your workspace.


FOLDER STRUCTURE

Once an app is created, GRAILS will create quite a lot of folders for you.
I created an app called LetsGrail. Below is the complete folder structure of the app.

Folder structure of grails within STS
























I believe all the folder names are self explanatory so I will leave it for you to figure out. In addition to this GRAILS will also create folders called .grails and .ivy2 in your Users folder. For me its here C:\Users\Lalit\. We will discuss more about both the folders when we go deep into grails.

WHAT's NEXT !!!

In my next post, I will explain about the database connection in GRAILS and basic configurations.