Skip to content

Instantly share code, notes, and snippets.

@galleon
Created November 15, 2015 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galleon/e0807499a1b8b78924ca to your computer and use it in GitHub Desktop.
Save galleon/e0807499a1b8b78924ca to your computer and use it in GitHub Desktop.
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.MultipleCompilationErrorsException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
//Logger logger = LoggerFactory.getLogger(GroovySparkThoughGroovyShell.class);
GroovyShell interpreter;
Binding binding;
binding = new Binding();
CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
//compilerConfiguration.setClasspath();
//compilerConfiguration.setOutput(new PrintWriter());
interpreter = new GroovyShell(binding, compilerConfiguration);
//logger.info("GroovySparkInterpreter<open>: interpreter", interpreter);
String script = new File('/Users/tog/Work/GroovySpark/GroovySparkWordcount.groovy').getText('UTF-8')
//logger.info("GroovySparkInterpreter<interpret>: ", script);
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintStream printStream = null;
try {
printStream = new PrintStream(stream, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringWriter stacktrace = new StringWriter();
PrintWriter errWriter = new PrintWriter(stacktrace);
System.setOut(printStream);
System.setErr(printStream);
Object result = null;
try {
result = interpreter.evaluate(script);
} catch (MultipleCompilationErrorsException e) {
stacktrace.append(e.getMessage());
} catch (Throwable t) {
t.printStackTrace(errWriter);
} finally {
System.setOut(originalOut);
System.setErr(originalErr);
}
System.out.println("" + stacktrace);
if (stacktrace.toString().length() > 0) {
println new String(stream.toByteArray()) + "\n" + stacktrace.toString()
} else {
println new String(stream.toByteArray())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment