For a few days I have been browsing through Groovy in Action and wanted to give Groovy a try. So what should I code? I was busy with other stuff and while I was setting up a wicket project at home I wondered….what was the mvn wicket-quickstart syntax again?! I could have just pasted the command from the wicket site, but I decided to let Groovy handle this one. My first Groovy script was born. Nothing fancy, the script reads an artifactId and groupId from standard input and prods maven to create a quickstart project. It’s really nothing but a thin wrapper around the maven command. Anyway, it’s a nice opportunity to play with Groovy. Read the script below and I’ll comment right after:

#!/usr/bin/env groovy

System.in.withReader { reader ->
println "[Wicket Quickstart Script]"
print "groupId: "
def groupId = reader.readLine()
print "artifactId: "
def artifactId = reader.readLine()

def command = """/usr/bin/mvn archetype:create
-DarchetypeGroupId=org.apache.wicket
-DarchetypeArtifactId=wicket-archetype-quickstart
-DarchetypeVersion=1.4-rc4
-DgroupId=${groupId} -DartifactId=${artifactId}"""

def proc = command.execute()
proc.in.newReader().eachLine {
line -> println line
}
}

One thing I didn’t know earlier is that you can’t shebang a Groovy script as usual on a *NIX machine. Instead you put #!/usr/bin/env groovy at the top which fires up Groovy indirectly. Now the actual script. Reading the input uses a closure, similar to anonymous inner classes in Java, but way more powerful. Next, the script creates the maven command string. This part uses multi line strings, created with “”” and GStrings, which allow $variable interpolation. See Strings and GStrings. Quite useful. The final part does process management with execute(), again using a closure to loop through the maven output and print each line.

It seems that Groovy makes these scripting tasks easy to do, with very little code. From what I’ve seen so far Groovy has the familiar OO foundation of Java and the shortcut power features of scripting languages like perl and ruby. I’ll definitely use Groovy for similar scripts in the future and I am curious about using Groovy along with Java. This is really scratching the surface of what you can do with Groovy, there is a whole lot to explore!