Scripting magic with Groovy, Grape and Jetty

Groovy 1.7 has just been release and it’s time to play again. One of the new features, Grape inspired me to the try the following. I created a script that acts as a simple webserver using embedded jetty without the need to install anything else than Groovy 1.7 on your computer. Just save the script as simpleWebServer, make it executable and start it like

./simpleWebServer -d someDirWithHTMLFiles -p 9000

Surf to http://localhost:9000 and you will see.

Here is the full script. I will explain the details further down.

#!/usr/bin/env groovy

@Grab('org.mortbay.jetty:jetty:6.1.22')
import org.mortbay.jetty.*;
import org.mortbay.jetty.handler.*

def cli = new CliBuilder (usage:'simpleHtmlServer -p PORT -d DIRECTORY')
cli.with {
 h longOpt:'help', 'Usage information'
 p longOpt:'port',argName:'port', args:1, type:Number.class,'Default is 8080'
 d longOpt:'dir', argName:'directory', args:1, 'Default is .'
}

def opts = cli.parse(args)
if(!opts) return
if(opts.help) {
  cli.usage()
  return
}

def server = new Server(opts.port.toInteger()?:8080)
def resourceHandler = new ResourceHandler(welcomeFiles:["index.html"],
                                         resourceBase:opts.dir?:".")
server.handler = new HandlerList(handlers:[resourceHandler, new DefaultHandler()])

server.start()
server.join()

Here are the magic details about the script:

1. The Shebang

The first important thing about this script is the shebang.

#!/usr/bin/env groovy

If you are using a real operating system (sorry Windows users), this will let you start the script like a normal executable. I usually skip the .groovy appendix on script files, so it really feels like you are using a normal command line utility.

2. Grape

The next line uses the new feature of Groovy 1.7, called Grape. This is a dependency System that allows to load any dependency, that is available in the maven-repositories to be used inside a script.

@Grab('org.mortbay.jetty:jetty:6.1.22')

The syntax is pretty easy. It uses the maven notation: groupId:artifactId:version. There is an alternative version that uses separate attributes for each but I prefer the shortcut.
This line will lookup the dependency in the maven repository, download it and store it in ~/.groovy/grape. So the first start of the script might take a moment. The second time will be faster.
Grape allows to use the full java ecosystem in a simple groovy script without any additional install. Groovy 1.7 is enough. I think this makes scripting in groovy incredible powerful.

3. The CliBuilder
The script should really feel like a command line utility. Therefore it needs to deal with parameters. This is where the CliBuilder comes in.

def cli = new CliBuilder (usage:'simpleHtmlServer -p PORT -d DIRECTORY')
cli.with {
 h longOpt:'help', 'Usage information'
 p longOpt:'port',argName:'port', args:1, type:Number.class,'Default is 8080'
 d longOpt:'dir', argName:'directory', args:1, 'Default is .'
}

def opts = cli.parse(args)
if(!opts) return
if(opts.help) {
  cli.usage()
  return
}

Groovy includes Apache commons CLI. But where the Java version is already helpful in parsing parameters, the Groovy version gets really simple. The example above creates one CliBuilder, that provides a “DSL” for defining the parameters. Further down they are three parameters defined. This is all thats needed.
After the args are parsed we can just simply use them using Groovy properties syntax like opts.parameterName. Even a pretty usage statement can be printed, when –help is called.

4. Dynamic constructors
I used one of the embedded Jetty examples (FileServer.java) as the foundation of my script. The configuration of the handlers looked something like that in Java:

ResourceHandler resource_handler=new ResourceHandler();
resource_handler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase(args.length==2?args[1]:".");

HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler,new DefaultHandler()});

Thats pretty long. Now the Groovy version looks like that:

def resourceHandler = new ResourceHandler(welcomeFiles:["index.html"],
                                          resourceBase:opts.dir?:".")
server.handler = new HandlerList(handlers:[resourceHandler, new DefaultHandler()])

It uses dynamic constructors. Groovy allows to call a virtual constructor with a map of arguments, where the elements are actually bean properties. This allows a much more concise construction of an object, even if the original creator wasn’t so kind to provide a convenience constructor.

5. The Elvis Operator

You probably wondered what the following statement did in the last example:

opts.dir?:"."

Well, that was Elvis. In Java there is the ternary operator, which goes like this:

(condition)?(result if true):(result if false) 

In Grovvy there is something called the Groovy truth, which says if a statement is null, then it is false, else it is true. This makes the Elvis operator possible. Elvis says, if the statement is true (as in Groovy truth) then use the value of the statement, else use the value after the colon. This is a very concise way for realizing default values, which is often needed in scripts

With all the scripting features that were added in earlier versions and with Grape in 1.7 I think Groovy is finally a great alternative to usual scripting languages. When you are experienced in Java it’s probably much simpler to write a script in Groovy than in Perl, Ruby or even Bash. For me this is definitely true.

Well done, Groovy team!

Be Sociable, Share!
  1. […] This post was mentioned on Twitter by Joerg Mueller, Rayk Fenske. Rayk Fenske said: RT @JoergM: New blog post: Scripting magic with Groovy, Grape and Jetty http://bit.ly/54rK5s #groovy #blog […]

  2. […] to classic shell scripting for the Java experienced developer. I already wrote about this here. A common scenario is to call other shell commands from your scripts. Groovy makes this easy, but […]

  3. […] Groovy+Jetty blog featuring support for command-line arguments, @Grab, and serving of static […]

Leave a Reply