Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include jars in a groovy script? [duplicate]

I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.

like image 778
timdisney Avatar asked Nov 20 '08 17:11

timdisney


People also ask

How do I run a JAR file in groovy script?

Since Groovy 2.1 we can even run scripts that are packaged in an archive with the jar: protocol. Let's create first a simple Groovy script and package it in a sample. jar file. We can place the JAR file on a web server and use the jar:http://<address>/sample.jar!/cookies.groovy syntax to run the scripts remotely.

How do I set classpath in groovy?

Try this: C:\Temp>set CLASSPATH=foo C:\Temp>groovy -cp bar -e "println System.


1 Answers

Starting a groovy script with #!/usr/bin/env groovy has a very important limitation - No additional arguments can be added. No classpath can be configured, no running groovy with defines or in debug. This is not a groovy issue, but a limitation in how the shebang (#!) works - all additional arguments are treated as single argument so #!/usr/bin/env groovy -d is telling /usr/bin/env to run the command groovy -d rathen then groovy with an argument of d.

There is a workaround for the issue, which involves bootstrapping groovy with bash in the groovy script.

#!/bin/bash                                                                                                                                                                  //usr/bin/env groovy  -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@; exit $?  import org.springframework.class.from.jar //other groovy code println 'Hello' 

All the magic happens in the first two lines. The first line tells us that this is a bash script. bash starts running and sees the first line. In bash # is for comments and // is collapsed to / which is the root directory. So bash will run /usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@ which starts groovy with all our desired arguments. The "$0" is the path to our script, and $@ are the arguments. Now groovy runs and it ignores the first two lines and sees our groovy script and then exits back to bash. bash then exits (exit $?1) with status code from groovy.

like image 126
Patrick Avatar answered Oct 06 '22 23:10

Patrick