Compile Groovy to Executable JAR

Compile Groovy to Executable JAR

I’ve been working on automating some deployment tasks using Jenkins and Groovy. Fun stuff, but dealing with dependencies at runtime is a hassle. Yes, Maven will fetch everything you need, but sometimes you don’t have line-of-sight to Maven Central from a production machine or don’t want to to download the Interwebs.

Fortunately, Maven’s Assembly Plugin can cram everything into a single executable JAR. Here is a simple Groovy example to show how to do it:

https://github.com/paulmcgovern/groovy-standalone

The Groovy script in the project accepts two numbers, and outputs true if the first number multiplied by three equals the second. Maven exec will execute it if you set the script as the main class in the POM.


  org.codehaus.mojo
exec-maven-plugin
1.2.1

ca.pmcgovern.Main


The compiled JAR is 6M (sic.) and arguments can be passed with exec.args JVM parameters:

$ mvn exec:java -Dexec.args="2 6"
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------------------------------------------------
[INFO] Building groovy_standalone 1.0-SNAPSHOT
[INFO] ---------------------------------------------------------------
[INFO]
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ groovy_mvn >>>
[INFO]
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ groovy_mvn <<<
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ groovy_mvn ---
2 * 3 = 6 : true
[INFO] ---------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ---------------------------------------------------------------
[INFO] Total time: 2.262s
[INFO] Finished at: Fri Sep 18 09:40:41 EDT 2015
[INFO] Final Memory: 11M/149M
[INFO] ---------------------------------------------------------------

To build the stand-alone JAR run the Assembly plugin:

$ mvn compile assembly:single

In this case, the jar weighs in at a svelte 17M, but can be run directly with Java:

$ java -jar target/groovy_mvn-1.0-SNAPSHOT-jar-with-dependencies.jar 2 6
2 * 3 = 6 : true

The JAR works because the main class is specified in the manifest and the plugin is set to include dependencies in the POM:


  org.apache.maven.plugins
maven-assembly-plugin
2.4



ca.pmcgovern.Main



jar-with-dependencies