Package net.sourceforge.javautil.groovy.cli

Source Code of net.sourceforge.javautil.groovy.cli.GroovyRunCommand

package net.sourceforge.javautil.groovy.cli;

import java.io.IOException;

import org.codehaus.groovy.control.CompilationFailedException;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import net.sourceforge.javautil.common.ReflectionUtil;
import net.sourceforge.javautil.common.io.impl.SystemFile;
import net.sourceforge.javautil.ui.cli.CommandLineArgumentsStandard;
import net.sourceforge.javautil.ui.cli.CommandLineCommand;
import net.sourceforge.javautil.ui.command.UICommandArguments.PassedArgument;

/**
* This will run a script.
*
* @author elponderador
* @author $Author$
* @version $Id$
*/
public class GroovyRunCommand extends CommandLineCommand<GroovyCLIContext, CommandLineArgumentsStandard> {

  protected final GroovyClassLoader compiler;
 
  public GroovyRunCommand(GroovyClassLoader compiler, String name) {
    super(name, "Run a groovy script with domain bindings");
   
    this.compiler = compiler;
   
    this.addArgument("file", String.class, "The file that is the groovy script");
  }

  public Object execute(GroovyCLIContext ctx, CommandLineArgumentsStandard arguments) {
    PassedArgument arg = arguments.getArgument(0);
   
    String filename = (String) arg.getValue();
    SystemFile file = new SystemFile(filename);
   
    if (file.isExists()) {
      try {
        Class clazz = compiler.parseClass(file.getInputStream());
        if (Script.class.isAssignableFrom(clazz)) {
          Script script = (Script) ReflectionUtil.newInstance(clazz, new Class[] { Binding.class }, ctx.getUI().getDomain());
          return script.run();
        } else {
          ctx.getUI().error("File is not a script: " + filename + ": " + clazz, null);
        }
      } catch (CompilationFailedException e) {
        ctx.getUI().error("Could not compile script", e);
      } catch (IOException e) {
        ctx.getUI().error("Could not compile script", e);
      }
    } else {
      ctx.getUI().error("No such file: " + filename, null);
    }
   
    return null;
  }

}
TOP

Related Classes of net.sourceforge.javautil.groovy.cli.GroovyRunCommand

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.