Running standalone Groovy scripts

As I mentioned in my post Learning Groovy, I am writing Groovy scripts to automate some simple tasks. Now I want to share the scripts with others. I did not want them to install Groovy just to run the scripts. I had the groovy-all-1.8.0.jar, so I typed the following in the command prompt:

[cc lang='dos' ]C:\temp>java -jar groovy-all-1.8.0.jar Hello.groovy
Hello[/cc]

It worked. Simple. Now I tried to run my script that retrieved the XMLs from a database.

[cc lang='dos' ]
C:\work\FetchData>java -jar groovy-all-1.8.0.jar FetchData.groovy
Caught: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at FetchData.fetch(FetchData.groovy:51)
at FetchData.run(FetchData.groovy:3)
[/cc]

Of course I need the driver jar in the classpath. So I added the sqljdbc.jar to the classpath.

[cc lang='dos' ]
C:\work\FetchData>java -cp sqljdbc.jar -jar groovy-all-1.8.0.jar FetchData.groovy
Caught: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at FetchData.createCSV(FetchData.groovy:51)
at FetchData.run(FetchData.groovy:3)
[/cc]

Looks like the script is run with a different classloader and the java classpath is not passed to it. I did some lazy googling but did not find the answer I was looking for. So I looked at how eclipse is doing it. Eclipse used GroovyStarter and GroovyMain to run scripts. Not knowing which to use, I just used GroovyMain:

[cc lang='dos' ]
C:\work\FetchData>java -cp lib/groovy-all-1.8.0.jar;lib/sqljdbc.jar groovy.ui.GroovyMain FetchData.groovy
Fetched Data!
[/cc]

It worked! I just added the command in a batch file to share the script.

Vasanth Dharmaraj is a Java Architect currently working for Western Union living in the Bay Area. He is interested in programming, gadgets, formula one... You can follow him on Twitter.

Posted in Groovy, Java, Software

Ads By Google