Friday, April 23, 2010

Using Clear Source Java Codes In A Groovy/Grails Application

Groovy/Grails boosts the development process in many ways. The convention over configuration approach helps the developer to develop as fast as possible. Groovy and Grails talk in a much higher level language over than Java.

Something just like the creation of Java it self, is happening again. Software market place needs to talking in a more higher level languages rather than Java I think. Business on demand pressures the market to create and use more productive tools and technologies.

However, I as a developer need to write some parts of the applications using a little bit lower level language in many situations. Moreover, the huge amounts of developed and ready to use Java libraries such as source codes, jar files, and open source solutions warn me to prevent of reinventing the wheel. So, I align my approach with using the Groovy and Grails and Java classes in source code together just to boost the development and walk with bigger steps; Furthermore, I keep using of Java libraries whenever I need.

There are many situations that you need to use Java in a Grails application. This is more than using just JVM and importing jar libraries. I mean I prefer to user clear Java source code in the Grails application to have respect for the scripting concept of Groovy even in Java classes.

Here we will use a particular Java source code in a Grails application.
Assume below particular Java class:

package com.amir.util;

class HelloWorld {

public static String getMessage() {
return "Hello World!";
}

public static String getMessageFor(String str) {
return "Hello "+ str +"!";
}
}

I am going to use HelloWorld.java instead of HelloWorld.class. Then I will be able to modify it whenever I need and Grails will compile during each "grails run-app".

To create HelloWorld Grails application you first need to give the grails a create-app command:

$> grails create-app helloworld

This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal:

$> cd helloworld/src/java

Now you need to create the packging folders:

$> mkdir com
$> mkdir com/amir
$> mkdir com/amir/util

The Java class should be find in this path:

helloworld/src/java/com/amir/util/HelloWorld.java

Now come back to the helloworld folder which is the root folder of the application and create a hello controller:

$> grails create-controller hello

This will create a new controller in the grails-app/controllers directory called HelloController.groovy. You need to modify it to call the Java HelloWorld class.

$> gedit grails-app/controllers/HelloController.groovy

And make it as below:

class HelloController {
def world = {
render HelloWorld.getMessage() + " , "
render HelloWorld.getMessageFor(" Amir ")
}
}

Now start-up the container with run-app command:

$> grails run-app

This will start-up a server on port 8080 and you should now be able to access your application with the URL: http://localhost:8080/helloworld

Job done! You used a clear source Java class instead of the compiled one in a Grails application. Everything is just scripted!

Monday, April 19, 2010

Building A Blog Using 7 Simple Steps In Grails

Building a regular web application using Grails should be the minimalistic activity that any Java developer may involved in. Just follow below 7 steps to develop your first Grails blog.

1. To create an application using Grails we should run a "grails create-app applicationName" command:

$> grails create-app com.datispars.blog

2. Change directory to the currently built directory of the application:

$> cd com.datispars.blog

3. At this point we create domain classes. Domain classes will consist the logic part of MVC model:

$> grails create-domain-class com.datispars.blog.Content
$> grails create-domain-class com.datispars.blog.Comment
$> grails create-domain-class com.datispars.blog.Author

4. To put some business policy into the model area we should modify domain classes

$> gedit grails-app/domain/com/datispars/blog/Content.groovy

You should modify Content class as below:

package com.datispars.blog

class Content {
String title
String body
Category category
Author author
static hasMany=[comments:Comment]
static constraints = {
title(blank:false, nullable: false, size:3..80)
body(blank:false, nullable:false,size:3..500)
author(nullable:false)
}
}
.....

$> gedit grails-app/domain/com/datispars/blog/Author.groovy

package com.datispars.blog

class Author {
String name
String email
String webpage
static constraints = {
name (blank:false, nullable:false, size:3..30,
matches:"[a-zA-Z1-9_]+")
email (email:true)
webpage (url:true)
}

String toString(){
return name;
}
}
....

$> gedit grails-app/domain/com/datispars/blog/Comment.groovy

package com.datispars.blog

class Comment {
static belongsTo=[content:Content]
Author author;
String comment
static constraints = {
comment (blank:false, nullable: false, size:5..200)
author (nullable: true) // Comments are allowed without a author
}

String toString(){
if (comment.size()>20){
return comment.substring(0,12);
} else
return comment;
}
}

5. To create the Controller part of MVC based on the domain classes you should run below commands:

$> grails generate-controller com.datispars.blog.Content
$> grails generate-controller com.datispars.blog.Author
$> grails generate-controller com.datispars.blog.Comment

6. Now you need to modify three controller that you have built to use Scaffold functionality of Grails:

$> gedit grails-app/controllers/com/datispars/
blog/ContentController.groovy

Scaffolding allows you to auto-generate a whole application for a given domain class. The simplest way to get started with scaffolding is to enable scaffolding via the "scaffold" property. So add the commented line (def scaffold = true) in the start part of the ContentController.groovy class:

package com.datispars.blog

class ContentController {

def scaffold = true // The only modification
// in the controller you should do...

static allowedMethods = [save: "POST", update: "POST",
delete: "POST"]

def index = {
redirect(action: "list", params: params)
}
....


Do just the same operatoion for AuthorController.groovy and CommentController.groovy (Same as 12 step) .

7. Run the application:

$> grails run-app

After running the server you should see below response in the terminal:

Server running. Browse to http://localhost:8080/com.datispars.blog

So, you browse http://localhost:8080/com.datispars.blog

Grails Over Rails

After a few research around rapid application development tools and frameworks, I started to try Groovy and Grails. This just happened after a couple of weeks using of Ruby on Rails. Ruby on Rails has excited me when I knew Groovy and Grails. I have had some difficulties with Ruby on Rails at initiating days that I didn't touch them again during using of Groovy and Grails.

At first I needed to install Grails. This was as much easy as you imagine. Later, I have explained how I installed Ruby on Rails on Ubuntu Linux in the previous article in current web log that shows rails installation needs some struggles to the end of deployment. But, Grails installation is just like a piece of cake in my experience. There is a binary version that is available as a zipped file that just needs to download and extract it. Then you should set two environmental variable. I am using Grails on Ubuntu Linux. So I had to fix a stupid bug at first try. In fact, Groovy and Grails are more indicated for Java developers because they can leverage their knowledge on Java platform and they can also turn to Java whenever they feel so, since Groovy runs on top of JVM. After all you have Spring and Hibernate ready available. Grails is very easy to get started with for Java developers. Also, You'll be able to continue using the same libraries that you used to (among many other things). The wide and enriched Java libraries are mostly accessible to your Grails application. All the code you developed and bug fixed routines are reusable in the Groovy applications. So you wont repeat all you have done.

I think Grails follows Rails track but in a more organized way. The main different is Java compatibility of Grails I think. If you try to deploy a Rails application on a JEE application server you will find that there is not a straight forward procedure at all. I found that setting up the environment to develop Rails application needs gathering some very dependent components that you have to arrange them just like a puzzle and I don't know why they did not put them all in the same package!. In the opposite, Grails gives the same functionality by a more consistent and integrated solution. For making a war of the Grails application that you developed, this is enough to give it a "grails war" in the root folder of the application.

Furthermore I found Groovy scripts meaningful and more conceptual. This may be just because the background I had from Java. I know Ruby is so abstracted and sharp but I used to explain exactly what I need, even by using a bit more symbols and reserve words. I cant feel the Japanese culture of Ruby short hands!

Here is a piece of Groovy code:

class User {
String name
String email
String webpage
static constraints = {
name (blank:false, nullable:false, size:3..30, matches:"[a-zA-Z1-9_]+")
email (email:true)
webpage (url:true)
}

String toString(){
return name;
}
}

I have never seen any implementation of the validation routines as much simplified as Groovy codes. The "constraints" block has described validation rules clearly. Email and webpage validations are brilliant:

email (email:true)
webpage (url:true)

I think Grails accelerates the outlet of the development process for the everyone who needs to build Java compatible web applications using new generation of RAD tools and scripts.

During working with Grail I've used this article from Lars Vogel. This could be an easy tutorial that shows how Grails works.

Sunday, April 4, 2010

Intstall "Ruby on Rails" on Ubuntu 9.04 and Dont Repeat Yourself Anymore

My new position during initiating days of the new Iranian's year just started by a weird project that outsourced by an over seas company to an Iranian one.

I have cooperated in some software projects with different technologies such as Java, .Net and Delphi. Indeed, the latest one is a Ruby on Rails web based project that I have selected by the boss as the technology specialist and the senior developer to find out the way of using this unfamiliar technology. The project requirements and specifications ride us toward cutting edge technologies. For the first day searching and surfing through technical pages have filled my working time.

I remember some months ago, a friend of mine tried to hire some Ruby on Rails developers in Tehran. He didn't succeed. This is why I feel so lucky. Ruby on Rails is designed based on the “Convention over Configuration” idea, and the rapid development principle of “Don't Repeat Yourself(DRY)”. I have found its agile motivations so practical. I as a web developer have wast a vast of time to implement repeated and simple parts of the applications such as database connectivity and configurations. Ruby on Rails reduces this times by emphasizing CoC and DRY concepts.

Ruby on Rails is often installed using RubyGems, a package manager which is included with Ruby. Many Linux flavors also support installation of Rails and its dependencies through their native package management system.
I tried to deploy it on Ubuntu 9.04. It wasn't easy and straight forward in my case. I tried a couple of times.

I found that I have to install ruby-full and ruby-elips packages first. Next, its time to install Ruby and Rails. Leave RubyGems for the latest installation. After all you need an IDE. RadRails is an Eclipse based Ruby on Rails IDE that facilitating the developments using its nice and fast tools and services.

Here are all commands in detail:
First remove all installed Ruby, Rails, Gems and everything you will install in next steps. Any remain parts may make some troubles for this process.

Make sure your repository is updated:
sudo apt-get update

Install rails by below command:
sudo apt-get install ruby ri rdoc irb libopenssl-ruby ruby-dev

Download RubyGem.

Extract it and then install Gem by following commands:
tar xvzf rubygems-1.3.5.tgz
cd rubygems-1.3.5
sudo ruby setup.rb

You don't need to the downloaded file and extracted folder any more. So remove it:
rm -r rubygems-1.3.5 rubygems-1.3.5.tgz

Now, create a set of simlinks:
sudo ln -s /usr/bin/gem1.8 /usr/local/bin/gem
sudo ln -s /usr/bin/ruby1.8 /usr/local/bin/ruby
sudo ln -s /usr/bin/rdoc1.8 /usr/local/bin/rdoc
sudo ln -s /usr/bin/ri1.8 /usr/local/bin/ri
sudo ln -s /usr/bin/irb1.8 /usr/local/bin/irb

Make sure ruby-dev installed:
sudo apt-get install ruby-dev

Next, install the Rails:
sudo gem install rails

You need Mongrel as server:
sudo gem install mongrel passenger capistrano


Setup databases (sqlite3 and MySQL):
sudo apt-get install sqlite3 swig libsqlite3-ruby libsqlite3-dev
sudo gem install sqlite3-ruby
sudo apt-get install mysql-client libmysqlclient15-dev
sudo gem install mysql

Test what have you done:
rails test_app

Test the application with MySQL support:
rails test-app -d mysql

Run the application:
cd test_app
script/server