Tuesday, February 26, 2008

Damn you DBUnit!

I simply can't get over how powerful the Groovy XML and SQL support is, especially when you combine the two. Did you ever find yourself in the position where you wanted to convert a Hypersonic database to a DBUnit dataset? I did, and I told my co-worker, somewhat disgruntled, that "I bet this could be done with 30 lines of Groovy". Well, it could:


import groovy.sql.Sql
import groovy.xml.MarkupBuilder

def sql = Sql.newInstance("jdbc:hsqldb:my_db", "sa", "", "org.hsqldb.jdbcDriver")

def sw = new StringWriter()
def xml = new MarkupBuilder(sw)

xml.dataset {
sql.eachRow "select * from system_tables where table_type != 'SYSTEM TABLE'", {
table(name:it.TABLE_NAME.toLowerCase()) {
sql.rows("select * from ${t}", { md ->
md.columnCount.times {
column md.getColumnName(it + 1).toLowerCase() ?: ""
}
}).each { r ->
row {
r.size().times {
value r[it]
}
}
}
}
}
}

println sw

This is why I like Groovy - it's powerful, yet elegant.

Sunday, February 24, 2008

Groovy power

The concurrent API that was added to Java 5 is very powerful for sumbitting tasks to a worker thread pool, but when you combine it with the Groovy ability to implement single-method interfaces with closures you have a real winner.


import java.util.concurrent.Callable
import java.util.concurrent.Executors

def executorService = Executors.newFixedThreadPool(4)

def x = {
20.times {
println "X"
}
} as Callable

def y = {
20.times {
println " Y"
}
} as Callable

executorService.invokeAll([x, y])

executorService.shutdown()

which of course has an output similar to this:

X
Y
Y
Y
X
Y
X
Y
X
Y
Y
X
X
Y
X
Y
Y
X
X
X

Pretty neat, huh?