package net.sourceforge.javautil.groovy.cli;
import java.util.ArrayList;
import java.util.List;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import net.sourceforge.javautil.common.ReflectionUtil;
import net.sourceforge.javautil.common.StringUtil;
import net.sourceforge.javautil.ui.cli.CommandLineArgumentsStandard;
import net.sourceforge.javautil.ui.cli.CommandLineCommand;
/**
* This will take the command and arguments and make a script out of it.
*
* @author elponderador
* @author $Author$
* @version $Id$
*/
public class GroovyScriptCommand extends CommandLineCommand<GroovyCLIContext, CommandLineArgumentsStandard> {
protected final GroovyClassLoader original;
protected GroovyClassLoader compiler;
public GroovyScriptCommand(GroovyClassLoader compiler, String name) {
super(name, "Evaluate groovy script");
this.original = this.compiler = compiler;
this.addArgument("script...", String.class, "All arguments will be taken to form the script");
}
public Object execute(GroovyCLIContext ctx, CommandLineArgumentsStandard arguments) {
if (original.getParent() != Thread.currentThread().getContextClassLoader())
this.compiler = new GroovyClassLoader();
else
this.compiler = this.original;
List<String> commandInfo = new ArrayList<String>();
for (int i=0; i<arguments.getRawArgumentCount(); i++) {
commandInfo.add(arguments.getRawArgument(i));
}
StringBuffer imports = new StringBuffer();
if (ctx.getUI().imports.size() > 0) {
for (String pkg : ctx.getUI().imports) {
imports.append("import " + pkg + ".*;\n");
}
imports.append("\n");
}
String script = imports.toString() + StringUtil.join(commandInfo, ' ');
try {
Class clazz = compiler.parseClass(script);
if (Script.class.isAssignableFrom(clazz)) {
Script scriptClass = (Script) ReflectionUtil.newInstance(clazz, new Class[] { Binding.class }, ctx.getUI().domain);
return scriptClass.run();
} else {
ctx.getUI().info("Class created: " + clazz);
}
} catch (Throwable e) {
ctx.getUI().error("Error executing: " + script, e);
}
return null;
}
}