Pages

Monday, December 18, 2006

Groovy from SQL and templates

Groovy is a real fun! Get some data from database and put it to XML - must be quick-n-dirty :)
Let the table be:
-- Apache Derby ij script
connect 'jdbc:derby:../../myderby;create=true;user=test;password=test';
create table test(
name varchar(20),
age integer,
gender char(1)
);
insert into test values ('John Doe', 55, 'M');
insert into test values ('Diana Smith', 34, 'F');
insert into test values ('Foo Bar', 21, 'M');
disconnect;
exit;
... and the template.txt:
<person>
<name>${name}</name>
<age>${age}</age>
<gender>${gender}</gender>
</person>
.. and now, Groovy rocks! :)
import groovy.sql.Sql
import groovy.text.Template
import groovy.text.SimpleTemplateEngine
import java.io.File

class SQL2XML{
static void main(args) {
def file = new File("template.txt")
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file)
def sql = Sql.newInstance("jdbc:derby:myderby",
"test", "test",
"org.apache.derby.jdbc.EmbeddedDriver")
sql.eachRow("SELECT * FROM TEST") {
def binding = ["name":"${it.name}",
"age":"${it.age}",
"gender":"${it.gender}"]
def result = template.make(binding)
println result
}
}
}

It seems to me that the dynamic features might be useful for adding customizations to the end-user application.

Saturday, December 16, 2006

Apache Derby with Eclipse

I sticked with Apache Derby for simple desktop application development. Derby (or JavaDB) is becoming part of the JDK, so it might be a good long term bet. The Eclipse plug-in appeared quite useful in this case.

The functionality of the plug-in makes the core jar files available in the project. One could run the ij queries just inside Eclipse console and execute custom scripts using a context menu item available via riht-button-click on the target file.

Disqus for Code Impossible