I heart groovy

Posted: January 19th, 2011 | Author: | Filed under: code | Tags: | Comments Off on I heart groovy

Reason number 2343242354 why i love groovy – I had a bunch of urls and I needed to run NSLOOKUP on them. I had a couple of options, write a shell script, do each by hand, write it in java (eeek) or write it in groovy. I chose groovy.

"https://sealserver.trustkeeper.net"].each{ url ->
println "nslookup ${url[8..-1]}".execute().text

Ok let’s look whats going on here. First thing you’ll notice if you’re coming from the java world is there is no class definition, there’s an implicit class created for you so for simple scripts especially run once scripts like this, it’s not necessary.

The first part is a list which is created with []


Next we are calling a method on the list called .each which accepts a closure which is in this case

{ url ->
println "nslookup ${url[8..-1]}".execute().text

Contained in this closure is what I really needed to do, which was do an NSLOOKUP on each url, but only the domain, I had to strip out the protocol (I know this could have easily been done with a search and replace in my editor but then you don’t have any example code)

We start by creating a groovy string – denoted by the"" which allows us to substitute the url in with the ${url} syntax. Another niceity is to omit the {}’s if you do not need to run any additional methods on the variable you are substituting – had the https:// not been in the url i could have written it like so:

println "nslookup $url".execute().text

What you’ll notice is by using the array index notation with a range I am able to get all chars starting at position 8 and go all the way to the end (in groovy -1 means the end of the string, -2 would be 2 from the right -3, 3 from the right etc. – no more subString(pos, string.len - pos)) This same syntax also works with lists

Now that I have the portion of the domain I need, we call .execute() on it. In groovy a .execute method is added to the String class and when doing so the entire string will be passed to the command line and executed. The following would print out the directory listing where the script was running.

"ls -la".execute().text

Finally we call .text (equivalent of .getText()) since .execute only returns a java.lang.UNIXProcess and the text property gives you back the output

Also note that println is the equivalent of System.out.println("text") – it’s just another groovy shortcut.