How do I include jars in a groovy script?
JavaGroovyJarClasspathJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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][1] 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.
[1]: http://jira.codehaus.org/browse/GMOD-226 "groovy issue"
Solution 2 - Java
If you really have to you can also load a JAR at runtime with:
this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())
Solution 3 - Java
You can add the jars to $HOME/.groovy/lib
Solution 4 - Java
My Favorite way to do this is with Groovy Grapes. These access the Maven Central Repository, download the referenced jar, and then put it on the classpath. Then you can use the library like any other library. The syntax is really simple:
@Grab(group='com.google.collections', module='google-collections', version='1.0')
You can read more details here. One major advantage here is that you don't need to distribute your dependencies when you distribute your script. The only drawback to this method is that the Jar has to be in the Maven repository.
Solution 5 - Java
You can also try out Groovy Grape. It lets you use annotations to modify the classpath. Its experimental right now, but pretty cool. See docs.groovy-lang.org/.../grape
Solution 6 - Java
The same as you would in Java.
This is an example of running a MySQL status monitoring script. mysql.jar contains the MySQL connector that I call from script status.groovy.
groovy -cp mysql.jar status.groovy ct1
Solution 7 - Java
Below is a combination of Patrick's solution, Maarteen Boekhold's solution, and foozbar's comment that works with both Linux and Cygwin:
#!/bin/bash
// 2>/dev/null; SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
// 2>/dev/null; OPTS="-cp $SCRIPT_DIR/lib/extra.jar:$SCRIPT_DIR/lib/spring.jar"
// 2>/dev/null; OPTS="$OPTS -d"
// 2>/dev/null; OPTS="$OPTS -Dlog4j.configuration=file:/etc/myapp/log4j.xml"
// 2>/dev/null; exec groovy $OPTS "$0" "$@"; exit $?
import org.springframework.class.from.jar
//other groovy code
println 'Hello'
How it works:
//
is a valid groovy comment, so all of the bash commands are ignored by Groovy.//
will return an error, but the error output is redirected to/dev/null
and is therefore not displayed.- bash executes commands following a semicolon even though the previous command failed.
exec
replaces the current program in the current process without forking a new process. Thus, groovy runs within the original script process (ps
shows the process as the script rather than the groovy executable)- The
exit $?
statement followingexec groovy
prevents bash from trying to interpret the rest of the script as a bash script, and also preserves the return code from the groovy script.
The above bash trick is more convenient in some cases than the RootLoader trick because you can use regular import statements within the script. Using the RootLoader trick forces you to load all of the classes using reflection. This is fine in some situations (such as when you need to load a JDBC driver), but inconvenient in others.
If you know your script will never be executed on Cygwin, then using Patrick's or Maarteen's solution will likely result in slightly better performance because they avoid the overhead of generating and throwing away an error.
Solution 8 - Java
Adding to @Patrick his answer, which helped me a lot, I recently discovered another trick.
If you add lots of jars to the classpath all on one line, things can become quite unreadable. But you can do the following!
#!/bin/bash
//bin/true && OPTS="-cp blah.jar -Dmyopt=value"
//bin/true && OPTS="$OPTS -Dmoreopts=value2"
//usr/bin/env groovy $OPTS "$0" $@; exit $?
println "inside my groovy script"
Let your imagination run wild on how complex a command line you can break down this way into manageable pieces
Maarten
Solution 9 - Java
If you want to use it right away before the import
declarations it is possible like this :) :
// printEmployees.groovy
this.class.classLoader.rootLoader.addURL(
new URL("file:///C:/app/Dustin/product/11.1.0/db_1/jdbc/lib/ojdbc6.jar"))
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr",
"oracle.jdbc.pool.OracleDataSource")
sql.eachRow("SELECT employee_id, last_name, first_name FROM employees")
{
println "The employee's name is ${it.first_name} ${it.last_name}."
}
Taken from this javaworld.com article.