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:
<br> #!/usr/bin/env groovy</p> <p>System.in.withReader { reader -><br> println "[Wicket Quickstart Script]"<br> print "groupId: "<br> def groupId = reader.readLine()<br> print "artifactId: "<br> def artifactId = reader.readLine()</p> <p>def command = """/usr/bin/mvn archetype:create<br> -DarchetypeGroupId=org.apache.wicket<br> -DarchetypeArtifactId=wicket-archetype-quickstart<br> -DarchetypeVersion=1.4-rc4<br> -DgroupId=${groupId} -DartifactId=${artifactId}"""</p> <p>def proc = command.execute()<br> proc.in.newReader().eachLine {<br> line -> println line<br> }<br> }<br>
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!

[…] Shebang! Birth of a Groovy script « JTeam Blog / JTeam: Enterprise … […]
Hi Frank! You should find interesting Gant project. Is based on Groovy and let you write your own task as Groovy object, without xml or command string.
Bye!
Hey Andrea, thanks for your comment. This page: http://gant.codehaus.org/Maven+Target+Set seems to describe how to use Maven through Gant. I’ll check it out.
[…] So, here is an example in two lines of Groovy code (really one line if you don’t count the shebang […]