Friday, July 16, 2010

Grab Groovy in a Shell

I saw a tweat today about Groovy Grab and using it in a shell script. It reminded me how cool Grapes and Grab are for pulling dependencies into a Groovy file.

Here is a little script that will execute an HTTP call using Apache HttpClient and the script is executable like any other shell script on your machine ./go.sh.

  1. Create a file named go.sh

  2. copy the code below into the file

  3. from shell type "chmod +x go.sh" without parentheses



#!/usr/bin/env groovy
@Grab(group='commons-httpclient',module='commons-httpclient',version='3.1')
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod

HttpClient client = new HttpClient();
GetMethod get = new GetMethod("http://www.apache.org/");
client.executeMethod( get)
println get.responseBodyAsString

Note: The @Grab is actually annotating the first import statement.

No comments: