Howardism Musings from my Awakening Dementia
My collected thoughts flamed by hubris
Home PageSend Comment

Why I Like Groovy

In describing why I've been using Groovy (and Grails) to some geeky friends, I thought I would give a perfect illustration of what makes this so… uhm… groovy.

I have a project where Zip archives are given to my application. The archives contain an XML file which has lots of metadata about the archive. However, it doesn't have enough, and we decided that while we should pick up this metadata, we should allow our database model to pick up more.

So I created a domain class which Grails persists for us automatically. It contains a number of fields for everything we want. What I need to do, it instantiate one of these objects, fill in the data fields with what I can get out of the XML file, and then pass it off to Grails to be displayed in a webpage.

So, here is the code in the controller that accepts the Zip archive. The file variable is a java.io.File object passed into this code. The ZipFile is from the standard Java java.util.zip package…

    final ZipFile isvpFile = new ZipFile(file)
    final ZipEntry entry = isvpFile.getEntry ( "isv.xml" )
    if ( entry ) {
        def root = new XmlSlurper().parse ( isvpFile.getInputStream(entry) )

        props.name = root.description.name.text()
        props.owner = root.description.owner.text()
        props.description = root.description.textdescription.text()
        props.release = root.description.version.text()
        . . .

The XmlSlurper, however, is from Groovy, and simply allows me to extract data from the XML file as if it were a map or a JavaBean.

Not only is it very succinct, it is also very maintainable. Plus it allows me to take advantage of all of the Java classes that I know so well.

Tell others about this article:
Click here to submit this page to Stumble It