Friday, February 16, 2007

My first Groovy program

When I heard the JavaPosse interview about Groovy I became really interested in it. The fact that it offers a scripting language based on the JVM and that it can be seamlessly integrated with Java fascinated me.

So I decided to buy the Groovy in Action book and try it out.

This is my first attempt at something that might become useful later:

def foundtypes = [:]
def sum = 0              
def stats = ""

bugs = new XmlSlurper().parse(new File("/home/ds/findbugs.xml"));

bugs.BugInstance.findAll { instance -> 
    instance.@category =~ 'CORRECTNESS|BAD_PRACTICE|MT_CORRECTNESS'
}.each { instance ->
 type = instance.@type.toString()
 foundtypes[type] = foundtypes.get(type,0) + 1
}
foundtypes.each { sum += it.value }

println "Found ${foundtypes.size()} types of errors and $sum total:"
foundtypes.each() { type ->
 stats += type.key.padLeft(42) + " : "
 stats += type.value + "\n"
}
println stats

What this does is slurp in (hence the class name...) an XML file. In this case it is a FindBugs analysis result. It then looks for all the BugInstance elements with a category attribute matching the regular expression CORRECTNESS|BAD_PRACTICE|MT_CORRECTNESS. For all matching elements it builds a map of the specific error type and a count for each. Finally it sums up all occurrences of all found bugs and prints them out somewhat nicely formatted:

Found 4 types of errors and 8 total:
                  SWL_SLEEP_WITH_LOCK_HELD : 3
                    UG_SYNC_SET_UNSYNC_GET : 1
                            DC_DOUBLECHECK : 1
                     IS2_INCONSISTENT_SYNC : 3

Next thing I am going to try is put those into a simple database, just to get some practice with it.

No comments: