Bootstrapping Grails integration tests

It is quite easy to prepare test environment the same as the development one. Just use Bootstrap.

class BootstrappedTests extends GroovyTestCase {
  void testBootstrap() {
    new BootStrap().init(null) 
    assert MyDomain.count() == 5   // Perform your tests here
    }
}

Custom iterative tag in Grails with named variable

I will show you how to create an iterative Grails tag that can contain another tag. The inner tag will use variable of the iterative tag. So, we are going to implement a tag that creates n links ’/show/1’, ’/show/2’, etc. with description ‘Article number 1’, ‘Article number 2’ etc.:

First of all, there is a nice and handy example for a simple iterative tag on the Grails site.

Definition:

def repeat = { attrs, body ->
  def i = Integer.valueOf( attrs["times"] )
  def current = 0
  i.times {
    // pass the current iteration as the groovy default arg "it"
    // then pass the result to "out" to send it to the view
    out << body( ++current )
  }
}

Usage:

<g:repeat times="3">
  <p>Repeat this 3 times! Current repeat = ${it}</p>
</g:repeat>

Slight modification of the tag does not lead to the requested functionality:

<g:repeat times="3"> 
  <g:link action="show" id="${it}">Hello number  ${it}</g:link> 
</g:repeat>

It just generates the “Article number” string three times, because the it variable is not known here.
Thus it is necessary to change the tag definition. Lets add another parameter vars as a symbolic name of the current member of the collection.

def repeat = { attrs, body -> 
  def pars = [:]
 
  attrs.times?.toInteger().times { n -> 
    pars[attrs.var] = n
    out << body(pars) 
  } 
}

And now it is possible to use g:link inside the custom tag:

<g:repeat times="3" var="num"> 
  <g:link action="show" id="${num}">Hello number  ${num}</g:link> 
</g:repeat>

I am not sure if it is supported, but it is definitely working.

From Mysql to Oracle: Grails application migration

Today I have finished migration of our Grails prototype. Originally we did develop it for MySQL, but the final system have to work with Oracle. This post summarize troubles and differences I was facing.

User creation

Since I am not Oracle administrator, it took me some time to put together script that creates user and appropriate rights for the Grails application. Use the script for development only.

CREATE user grails IDENTIFIED BY grassword;
GRANT connect  TO habilion;
GRANT CREATE TABLE TO habilion;
GRANT CREATE sequence TO habilion;
GRANT unlimited tablespace TO habilion;

Identifier length limitation

I usually do not use identifiers that are 30 characters long. But, there is a trick.

Imagine two classes: Author and Content. Author having multiple Contents.

Now, imagine there is several types of Content – Book, Newspaper, ElectronicNewspaper, ScientificArticle…
So, we can model the situation using following classes:

Class Content{
  static belongsTo = [ contentAuthor:Author ]
}
 
Class Book extends Content {}
Class Newspaper extends Content {}
Class ElectronicNewspaper extends Content {}
Class ScientificArticle extends Content {}
 
Class Author{
  static hasMany = [ contents: Content ]
}

And now comes the trick. The ‘content’ table in the database contains long columns:

content_author_id
newspaper_content_author_id
electronic_newspaper_content_author_id
book_content_authot_id
scientific_article_author_id

As you can see, it is easy to hit the 30 characters limit. If you look deeper, you will see the solution. The column names are composed of class name of the Content descendants and variable name pointing to the master entity.
So, I renamed the contentAuthor to ca, created getter and setter for contentAuthor and checked all “new Book…” snippets. God bless MVC!

Column size

The second major issue was a String column. I had a string column of 10000 characters.

Class Content {
  String abstract
  static constraints = { abstract(maxSize:10000) }
}

It was translated to Long data type. Unfortunately there is a bug in Oracle JDBC driver that causes nasty stack traces when processing Long data type. There is a workaround on the Internet, but it is working only for some versions of Oracle. Moreover, there is just one Long column allowed per table. So, changed the size to 4000 characters and the column was created as VARCHAR2.

And thats it!

Update: Empty strings

One thing to mention is a fact that Oracle does not distinguish between null and an empty string. So, if you try to store an empty string to Oracle DB, it actually stores it as a null value.

The problem arises, if you have not null column and you try to store empty string ‘’. For Grails it is a not null value, so it does not apply defaults. For Oracle it is null and thus constraint violation…

Making Grails log a Rails log

Grails log is verbose… very verbose. I got used to the Rails one, especially for the stack traces. Most of the time I am not interested in hundreds of messages about Hibernate not being happy with the parameter I did pass to it. Most of the time the problem is on my side and I want to know which object is it and which line of code.

So, i did a small trick with egrep. I run the grails application using this command:

grails run-app | egrep -v "at [a-z]+"

Sometime I have to go to my log file to check more details, but over 80% this is more than enough.

Rails and Grails comparison

I have spent few years developing in Ruby on Rails. For the last half of year I have been learning Grails, too. The things described here are a summarization of the differences that I had to come over.

The comparison will be written in a simple “table based” structure. I just got used to it when preparing comparisons or product studies for tenders.

Ruby on Rails

A lightweight web framework written in Ruby scripting programming language. It contains its own application server. See the Rails home website.

Grails

A web framework written in Groovy. The source code is compiled to byte code and can be run on Java application servers. Grails home website.

Maturity

Before I start comparison, it is fair to say, that Rails has been around from 2004 while Grails final version dates from 2008. So, some of the differences are caused by this time shift.

Both of the frameworks are more evolutionary than revolutionary. They just implement the right patterns and they do it right.

Ruby on Rails Grails
First release (version 1.0) July 2004 February 2008
Life cycle Mature framework with solid base of developers Young framework with a growing base of developers and a huge base of potential developers (from Java)

Documentation

Ruby on Rails Grails
Framework Excellent. Uses the RDoc that contains not only list of methods, classes and files, but also source code of a method, with syntax highlighting. Very good. Contains list of classes, methods, files… but I am really missing the source code. If the code is not documented, the documentation is useless
Application Excellent. Only the application files are documented using the RDoc (including syntax highlighting) On one hand it is exhaustive, because it generates documentation for all classes in the project (including plugins). On the other hand it does not contain the source code. So, once the code is not documented, the documentation is useless. So, on average I would say it is good.

Development

Both frameworks are based on flexible languages that allow meta programming – changing classes on the fly.

Ruby on Rails Grails
Developer audience From beginners Some experience is required
Language constructs Readable, sometimes like natural language Readable, sometimes too many brackets (but as I said, I spent some time in Ruby :o)
Mapping objects to database Excellent, all declarative Excellent, all declarative
Libraries Wide variety of libraries and plugins. Almost everything I needed was available (except for Kerberos support…) Huge amount of java libraries could be used together with Grails. This is one of Grails killer features.
Scaffold The default scaffold looks terrible, custom plugins needs to be installed. Looks nice out of the box, implements handy nice features like table sorting.
Tools rake (~make), rjs (ruby java script – library that allows to write java script functionality in ruby), migrations (tool that uses ruby syntax to change database schema – very useful) ant (~make)
Log file Very descriptive, it provides exactly the information needed: controller/action/parameters, time spent on DB, VIEW, CONTROLLER, SQL statements (including timing) Verbose… very. Exception generated 1000 lines of code in log, missing the information about SQL statements and the things that are in the Rails log. This was a disappointment.
Console Simple terminal window working in command/result mode Window based – command answer is displayed in different frame at the end of it (unfortunately it is not scrolling properly, so it is quite annoying). I take it as a temporary problem.  
Folder structure Simple, follows the MVC Following MVC, slightly more complex than RoR
Thread support Poor Native

Production

Ruby on Rails Grails
Resource usage Medium resource usage Higher resource usage

Potential

Ruby on Rails Grails
Internet High potential. The framework allows fast development of an application with a very good performance. High potential. It alows fast development and it can utilize all of the Java frameworks.
Enterprises Just for prototyping or small applications. The support of enterprise technologies is not at the focus of the community. Could be used for prototyping and also for real applications

Last, but not least, the popularity of both frameworks:




There are many more differences that were not mentioned here. If you find a major one not mentioned here, please leave me a comment. I will appreciate it.