Learning Groovy

I have dabbled a bit with scripting languages before but for some reason never really used one long term. I think that might change with Groovy. A colleague of mine got me interested in it and I have been picking up all the cool things Groovy can do by reading Dustin’s “Inspired by Actual Events” blog. Come to think of it Groovy could have saved me a ton of time I spent in writing small tools to help me in development.

I like the how concise and simple writing groovy scripts are. Here is a snippet of code to print rows retrieved from a database.

[cc lang=’groovy’ ]

// Get instance of Groovy’s Sql class
// See http://marxsoftware.blogspot.com/2009/05/groovysql-groovy-jdbc.html
import groovy.sql.Sql

def sql = Sql.newInstance(“jdbc:oracle:thin:@localhost:1521:orcl”, “hr”, “hr”, “oracle.jdbc.pool.OracleDataSource”)

// iterate over query’s result set and “process” each row by printing two names
sql.eachRow(“SELECT employee_id, last_name, first_name FROM employees”)
println “Employee ${it.first_name} ${it.last_name} has ID of ${it.employee_id}.”


At work I needed to retrieve about 100 XMLs stored in a database, strip out some tags from it and write it to a file. It took about 15 lines of Groovy code to do it. Probably could have done it in less but I am just learning Groovy.

Here is another way to use Groovy that I wish I knew before. Embedding Groovy in Ant:

[cc lang='xml' ]

     project.references.found.each {
         println it.name


Though the above snippet is simple, it shows how the Groovy script is aware of the Ant references. Pretty powerful.

I will showcase just another snippet before I am off to learn more Groovy. Invoking a web service:

[cc lang=’groovy’ ]
@Grab(group=’org.codehaus.groovy.modules’, module=’groovyws’, version=’0.5.2′)
import groovyx.net.ws.WSClient

proxy = new WSClient(“http://www.w3schools.com/webservices/tempconvert.asmx?WSDL”, this.class.classLoader)

result = proxy.CelsiusToFahrenheit(0)
println “You are probably freezing at ${result} degrees Farhenheit”