Friday 22 January 2016

Groovy: making and using a jar file

G'day:
First up: there's nothing clever in any of this, and I'm approaching it as a newbie. I just had to work out how to do this - which I have - and want to document it. It's nothing you couldn't find on Google with 15min effort.

We need to start writing some Groovy - cool! - for some tests we need to write. We're using SoapUI to test some of our web service end points (JSON schema validation and the like) and its built-in scripting language is Groovy. Our app itself is PHP, but that's irrelevant as it's hidden behind HTTP requests anyhow.

We have some shared utils that we want to us in our tests, and we're thinking about sticking these in a jar file so they can be a) factored-out into a separate source control project; b) plus just making our tests more focused. So I have to find out how to actually compile Groovy code, and stick it in a jar. I know if we're using jars then the source language doesn't need to be Groovy, but we've already got a bunch of the code written, so this is a refactoring exercise.

For my part, all my Groovyage so far has just been individual test scripts, run by the command-line interpreter. I've never needed to compile anything.

I'm not in the situation to actually work with our real test utils yet, so this is just a contrived example.

Here's my class:

package me.adamcameron.greetingapp

class Greeter {

    String greet(String name){
        return "G'day ${name}";
    }

}

Note I've got the package statement in there too. This is homed in me/adamcameron/greetingapp.

I googled about how to compile Groovy, and strangely enough it's much the same as Java:

>groovyc me\adamcameron\greetingapp\Greeter.groovy

>

This creates me/adamcameron/greetingapp/Greeter.class. I then jar it up in the usual way:

>jar cvf greetingapp.jar -C me\adamcameron\greetingapp .
added manifest
adding: Greeter.class(in = 4996) (out= 2092)(deflated 58%)
adding: Greeter.groovy(in = 120) (out= 101)(deflated 15%)

>


From there I just need to test it:

// testGreeter.groovy
import me.adamcameron.greetingapp.*

greeter = new Greeter()

println greeter.greet("Zachary")

And for Groovy to know where the jar file is, I need it to be on the class path:

>groovy -cp greetingapp.jar testGreeter.groovy

G'day Zachary

>

So there we go.

I didn't expect it to be tricky, but pleased how easy it really is.

Told you there'd be nothing insightful in this one!

Righto.

--
Adam