Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Friday, December 5, 2008

Ok, so while the Java language itself has lost some of it's luster for me, I still love the JVM. Here's a very common scenario:
  1. query a database and create an xml file from the dataset using tag names that you provide and write it to a file.

Not saying it can't be done quickly or cleanly in Java, but think how long it would take/how lines of (almost boilerplate) code...

Groovy to the rescue...

import org.ho.yaml.Yaml
import groovy.sql.Sql
import groovy.xml.StreamingMarkupBuilder

def sql = Sql.newInstance("jdbc:jtds:sqlserver://fakedbserver:1433/mydbname", "myusername", "mypassword", "net.sourceforge.jtds.jdbc.Driver")

def xml = new StreamingMarkupBuilder().bind {
mkp.xmlDeclaration()

events{
mkp.yield "\n"
sql.eachRow("SELECT e.id as eventId, scheduled_date, event_date, league, location, tv_station, neutral_location, preseason, tba, event_type, t.team as teamId, t.number as teamRotationNumber, p.number as propRotationNumber, prop.name as propValue FROM event e left join team_event t on t.event = e.id left join proposition_event p on p.event = e.id left join proposition prop on p.proposition = prop.id where e.id <> 0 order by e.id, t.number, p.number"){
event( eventId:"${it.eventId}",
type:"${it.event_type}",
scheduledDate:"${it.scheduled_date}",
actualDate:"${it.event_date}",
leagueId:"${it.league}",
locationId:"${it.location}",
tvStationId:"${it.tv_station}",
neutralLocation:"${it.neutral_location}",
preseason:"${it.preseason}",
tba:"${it.tba}",
rotationNumber:"${it.teamRotationNumber?:it.propRotationNumber}",
teamId:"${it.teamId?:''}",
propValue:"${it.propValue?:''}"
)
mkp.yield "\n"
}
}
mkp.yield "\n"
}
new File("scheduledump.xml").write(xml.toString())
println xml


30ish lines of code and most of that is creating the element/values? (Oh, and I don't really know Groovy that well yet) Anyone want to attempt that in Java?