Sunday, 15 May 2016

Groovy Automation Script

There are many instances where you may need to run a small script to automate some task. Usually this is done through scripting languages such as python and ruby. However if you would like to use the libraries that you already use in java and prefer java like syntax then groovy is the ideal solution see: (Groovy docs)

First create a launcher script:

On windows create a run.bat file and put this into it:
java -cp "lib/*" groovy.ui.GroovyMain testScript.groovy

On Unix/Linux create a run.sh file and put this into it:
#!/bin/bash
java -cp "lib/*" groovy.ui.GroovyMain testScript.groovy

Now create a file called testScript.groovy with the contents:
print "Hello world"

When this script runs it will print Hello world to the screen. Most java code is valid groovy code, so you can put any java code in this script and run it, provided you put the relevant jars in the lib folder(see below) or use @Grab annotation on your classes to specify maven dependencies (see @Grab docs)


Create a folder called lib. Download the groovy jar into the lib folder. Here is the link to the latest groovy jar at the time of writing:
http://central.maven.org/maven2/org/codehaus/groovy/groovy-all/2.4.6/groovy-all-2.4.6.jar


Now running run.sh will run your script.

No comments:

Post a Comment