Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy script classpath

I'm writing a script in Groovy and I would like someone to be able to execute it simply by running ./myscript.groovy. However, this script requires a 3rd party library (MySQL JDBC), and I don't know of any way to provide this to the script other than via a -classpath or -cp argument, e.g.

`./monitor-vouchers.groovy -cp /path/to/mysql-lib.jar`

For reasons I won't go into here, it's not actually possible to provide the JAR location to the script using the -classpath/-cp argument. Is there some way that I can load the JAR from within the script itself? I tried using @Grab

import groovy.sql.Sql


@Grab(group='mysql', module='mysql-connector-java', version='5.1.19')
def getConnection() {
    def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
    def dbUser = 'pucaroot'
    def dbPassword = 'password'
    def driverClass = "com.mysql.jdbc.Driver"

    return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}

getConnection().class

But this causes the following error:

Caught: java.sql.SQLException: No suitable driver
java.sql.SQLException: No suitable driver
        at monitor-vouchers.getConnection(monitor-vouchers.groovy:13)
        at monitor-vouchers.run(monitor-vouchers.groovy:17)

Is there a way I can execute this script using just ./monitor-vouchers.groovy

like image 684
Dónal Avatar asked May 14 '12 14:05

Dónal


People also ask

How do I set classpath in groovy?

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

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.

Does Groovy compile?

The Groovy compiler seems to compile directly from source to bytecode: groovyc is the Groovy compiler command line tool. It allows you to compile Groovy sources into bytecode. It plays the same role as javac in the Java world.


1 Answers

You should be able to do:

import groovy.sql.Sql

@GrabConfig(systemClassLoader=true)
@Grab('mysql:mysql-connector-java:5.1.19')
def getConnection() {
    def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
    def dbUser = 'pucaroot'
    def dbPassword = 'bigsecret'
    def driverClass = "com.mysql.jdbc.Driver"

    return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}

getConnection().class
like image 109
tim_yates Avatar answered Oct 16 '22 20:10

tim_yates