Breaking out of closures

gotcha, groovy 6 Comments »

coming from java I’m used to using break & continue to manipulate loops. Groovy doesn’t allow these keywords, so iterating with closures presented a problem.

Consider a piece of code like:

List people = // instantiate some Person ’s (idiots at the back)

// print the useful people
for (Person person : people) {
    if (person.isNuisance()) {
        break;
    }
    System.out.println(”name : ” + person.getName());
}

To achieve the same effect in groovy, the common trick is to use .find {} rather than .each{}

find loops over all the items in the list just like each, except it breaks out and returns the current object when a true condition is returned from the closure. So there is no reason why you can’t add logic to find, and use it in this manner

class Person { String name; boolean nuisance}

def people = [new Person(name:"person1",nuisance:false),
              new Person(name:"person2",nuisance:false),
	      new Person(name:"person3",nuisance:true),
	      new Person(name:"person4",nuisance:true)]

people.find() {
	if (it.nuisance) return true // break out
	println it.name
}

Groovy Builders Primer

gotcha, groovy 2 Comments »

Groovy lends itself to be extremely useful as a builder for all sorts of data structures. This article intends to investigate why that is. What exactly are builders? And why is groovy so good at it.

To answer these questions, 2 important concepts need to be addressed first

  1. DSL - Domain Specific Languages
  2. The Builder Pattern

Domain Specific Languages

He that is good with a hammer tends to think everything is a nail — Abraham Maslow

Advocates of ruby, and more recently groovy have traditionally embraced the “best tool for the job” attitude. The Pragmatic Programmer (a must have in any developers bookshelf ) suggests learning a new language every year. For some this might be taking it a step too far, but it definitely fits the former argument.

Computer science knows all too many one trick ponies who get stuck inside that one language of their choosing, and spend the majority of their free time insecurely and childishly flaming the new programming language on the block. The evident truth is that one shoe never first all, and a little flexibility in mindset goes a long way towards solving a problem. Which brings us to the concept of a DSL

The basic idea of a domain specific language (DSL) is a computer language that’s targeted to a particular kind of problem, rather than a general purpose language that’s aimed at any kind of software problem. Domain specific languages have been talked about, and used for almost as long as computing has been done. – Martin Fowler

XML is the current reigning king of this field. Unfortunately one may add . From a java background you’ll be familiar with XML as a DSL for:

  • Spring Configuration
  • Ant build files
  • log4j
  • hibernate mappings (pre annotations)
  • container configs (Tomcat / JBOSS / …)
  • web.xml

With all the advantages that XML files do carry. Such as allowing a strict definition through XSL/DTD as well as being able to define any datatype you wish, there is one major pitfall. XML is not a programming language and there is no concept of even a simple loop, which is particularly limiting in something like an ant build file.

Groovy suits itself perfectly as a DSL, because of its loose syntax allowing all sorts of creative possibilities. Closures, easy map definition and the metaclass being key.

The grails framework is a perfect example. GORM - the DSL for hibernate code allows you to define domain classes as follows.

  class Author {
	String email
	String username
	String password

	static hasMany = [books:Book]

	static constraints = {
           email(email:true, blank:false, unique:true)
           username(size:4..15, blank:false,unique:true)
           password(size:4..25, blank:false)
       }
   }

The code is readable, and easily understandable, by people unfamiliar with hibernate or groovy. GORM has in essence defined a DSL (leveraging groovy) to define the model, and the relationships which need to be mapped to the database.

Grails Controllers also utilize groovy in a similar way to provide a DSL for spring web-mvc.

The Builder Pattern

The Builder Pattern aims to seperate the creation of complex objects, the product, from its representation.

In a simple example:

If we define the creation steps of compiling our project, generating a war, deploying the war to the server, reloading tomcat in our own custom builder syntax “GroovyBuilder”. We could then still freely choose the actual representation. Do we generate an ANT build.xml from it. Or a linux shell script, even a dos batch file? “GroovyBuilder” is a generic syntax for building our choice of implementation of production steps.

Looking back at the example above from the GORM domain class Author, we could now also say that GORM is a builder for hibernate mappings. GORM seperates the creation of the model and its relationships from the represenation (the hibernate mapping).

GANT - Groovy Ant

GANT is a good example to put all of this together.

Below is a simple ant config:

<target name="compile">
   <mkdir dir="target/classes" />
   <javac srcdir="src" destdir="target/classes" />
</target>

The GANT counterpart

target(compile:"compiles source code"){
   Ant.mkdir(dir:"target/classes")
   Ant.javac(srcdir:"src", destdir:"target/classes")
}

At first site, this might not seem like all too much of an improvement. But the GANT code is pure groovy. Meaning all the conditional logic, and variable declaration is available to the developer. For larger build files this is a godsend.

There are many other, builders out there, which i’d like to expand upon, soon.

Critics and comments welcome ;)

holygrails.net goes live

holygrails 1 Comment »

We launched the first version of www.holygrails.net

The site is entirely written in grails, and we intend to update and expand it actively in the coming months. Currently we’ve launched a digg like / dzone voting system based on groovy and grails posts.

One of the great things about the grails community is that it is still young, and somewhat limited in numbers. Although we hope to see this change, the community is vibrant, and more importantly friendly.

Our mission is to empower the community to filter through the active teachings and blogrolls posted each day, and naturally evolve the better articles to the top. Without the negative ,troll activities some of the larger, less focused communities seem to acquire.

Some of the things we are currently working on / would like to see:

  • Plugin rating system - a repository off all plugins, with ratings and comments by the community
  • Useful RSS feeds - With a more active community, we would hope to provide custom feeds, with a set minimum votes

You can see our current site at

http://www.holygrails.net

are these good ideas - bad? We’d really like to hear from you.

stacktrace.log - everywhere

gotcha, grails No Comments »

I’ve noticed stacktrace.log showing up all over my system. The smart thing would have been to immediately link it to my recent surge in grails activity, but google wasn’t hinting me in this direction. The fact that these where empty files, didn’t help either.

I’d even gone as far as to write a shell script called cleanStacks on my production system :(

It turns out, this is mentioned in the grails reference however:

When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.

When this happens, the full trace is always written to the StackTrace logger. This logs to a file called stacktrace.log

The solution is to edit your grails-app/conf/Config.groovy, and change the line

StackTrace="error,stacktraceLog"

to

StackTrace="error"

I think it’s a good idea to print full stacktraces to a log file, but the problem is that the file is produced, relative to where I start tomcat from. Since I invoke tomcat restart from various paths in my production system, these files where cluttering up my system