Using Within Groovy Scripts

Daniel P. Dougherty

Groovy is a programming language which, at runtime, gets dynamically compiled and run as native JAVA bytecode on the same Java Virtual Machine (JVM) as a currently executing JAVA program. Naturally, Groovy can therefore be used as a scripting language for JAVA programs or for any programs having access to a JVM.

First, to make sure that the Snifflib library is properly added to Groovy's classpath you should place the following script in your ~/.groovy directory. Create it if needed using your favorite text editor (e.g. jEdit,NEdit etc. ). Save it as startup.

#This script ensures the jars in a user's ~/.groovy/lib are added 
#to the classpath of the VM so that class loading proceeds without
#error.
echo "Running custom ~/.groovy/startup"
if [ -d ~/.groovy/lib ] ; then
    JARS=`ls ~/.groovy/lib/*.jar`
    echo "Adding jar files in ~/.groovy/lib to classpath..."
    for jar in $JARS; do 
        export CLASSPATH="$CLASSPATH:$jar"
    done
    export CLASSPATH="$CLASSPATH:."
fi


Next. copy (or link to) the latest Snifflib jar file into your ~/.groovy/lib/ folder.

As an example, consider running the following HelloSnifflib.java as a Groovy script.

package com.jdoe.demos;

import com.mockturtlesolutions.snifflib.datatypes.DblMatrix;

/**
Basic hello world program linking to Snifflib numerical library.    
*/
public class HelloSnifflib
{
    public static void main(String[] args)
    {
        System.out.println("Hello World");
        DblMatrix X = new DblMatrix("[1 2 3; 4 5 6; 7 8 9]");
        X = X.times(DblMatrix.PI);
        X.show("Hello Snifflib!");
    }
}


Running this within the groovyConsole application looks like this!

Groovy Running HelloSnifflib.java


Related

Wiki: Home