Sunday, February 17, 2008

a Groovy Utility class :)

I wrote a Groovy utility class to help with setting Bindings for the GroovyShell. Additionally, I wrote a method that completely encapsulates the GroovyShell entirely.


import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import org.codehaus.groovy.control.CompilationFailedException;


/**
* Created: Feb 17, 2008 3:31:44 PM
*
* @author Robert O'Connor
*/
public final class GroovyUtil {
/**
* Utility method to set up bindings.
*
* @param bind the string you're binding
* @param obj to bind to.
* @return the Binding object
*/
public static Binding bindTo(String bind, Object obj) {
Binding b = new Binding();
b.setVariable(bind, obj);
return b;
}

/**
* Utility method to get a shell with the specified binding
*
* @param bind the binding
* @return the shell instance.
*/
public static GroovyShell getShell(Binding bind) {
return new GroovyShell(bind);
}

/**
* Execute a Groovy script.
*
* @param bind binding String
* @param obj Object binding
* @param code script code.
* @throws CompilationFailedException if the compilation fails.
* @throws IllegalArgumentException if you do not specify the bindings.
*/
public static void exec(String bind, Object obj, String code)
throws CompilationFailedException {
if ((obj == null) || (bind == null) || bind.equals("")) {
throw new IllegalArgumentException("No binding specified.");
}

GroovyUtil.getShell(GroovyUtil.bindTo(bind, obj)).evaluate(code);
}
}

No comments: