Tuesday, June 2, 2009

Joy Of Groovy

In my work and my volunteer, I need to do a lot of scripting for all kinds of things such as system administration, data migration etc. I have used shell script, perl and many other tools on and off for a long time before. Scripting with Groovy brings me much joy and fun.

Groovy brings the full Java language and its own flavors to your finger tips while you are typing and thinking your tasks and you can do a lot of things very easily and much simpler than other scripting. Here I will put up a few examples that demonstrate a few tricks that can simplify a lot of daily scripting work:

1. File Manipulation
2. Configuration
3. Database Access
4. Logging

Suppose you want to create a file and put stuff in it. This is how you do it:

def file=new File("test.txt")

do this:
file.append("line 1\n")
file.append("line 2\n")

Now the file has 2 lines.

Later some where, you want to do something with the data in the file, for example email the data to some one, this is how you get the content for the file:
def content=file.txt()

Suppose you want to write a method, for example log(String text). The log method basically append what ever text into a log file.

binding['writer']=new File("log.txt")

def log(String text){
writer.append(text+"\n")
}

Now suppose, instead of putting the log into a log file, I want to put the log into a database table for easy to search or may be for data warehousing purpose, you can easily change the above log method without touching the rest of your code.

def log(String text){
sql.execute("insert into usertrace(id,description) value(?,?)",[nextid(),text])
}

where nextid() is simply a method that return you the next id of table usertrace.

Now what is sql here? Before I talk sql, I need to touch the groovy configuration a bit.

The ConfigSlurper is a cool thing.

You might have been used to manipulate the java Property class which you need to load the property file and then use getter method to fetch the string property you want. The groovy way is much simpler.

In this code, MyConfig.groovy is a groovy class which contains name/value pairs, one of them is
called sql like this:

sql=groovy.sql.Sql.newInstance("jdbc:postgresql://localhost:5432/helloworld","username","password","org.postgresql.Driver")

This is how you get the property sql.

binding['cfg']=new ConfigSlurper().parse(new File('MyConfig.groovy').toURL())
binding['sql']=cfg.sql

Notice that the new variable sql is an object, not just a String as in Java Property file.
Then you can execute the method of the object sql, like we did in the above log method.

Have fun so far! As you explore Groovy, you will discover them more.

1 comment:

  1. nice tips!

    I use groovy almost daily as scripting language for admin matters in projects built on the XWiki platform, I share the joy and fun :)

    ReplyDelete