use of org.ow2.proactive.utils.BoundedStringWriter in project scheduling by ow2-proactive.
the class Script method execute.
/**
* Execute the script and return the ScriptResult corresponding.
* This method can add an additional user bindings if needed.
*
* @param aBindings the additional user bindings to add if needed. Can be null or empty.
* @param outputSink where the script output is printed to.
* @param errorSink where the script error stream is printed to.
* @return a ScriptResult object.
*/
public ScriptResult<E> execute(Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) {
try {
fetchUrlIfNeeded();
} catch (Throwable t) {
String stack = Throwables.getStackTraceAsString(t);
if (t.getMessage() != null) {
stack = t.getMessage() + System.lineSeparator() + stack;
}
return new ScriptResult<>(new Exception(stack));
}
ScriptEngine engine = createScriptEngine();
if (engine == null)
return new ScriptResult<>(new Exception("No Script Engine Found for name or extension " + scriptEngineLookupName));
// SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE)
BoundedStringWriter outputBoundedWriter = new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE);
BoundedStringWriter errorBoundedWriter = new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE);
engine.getContext().setWriter(new PrintWriter(outputBoundedWriter));
engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter));
Reader closedInput = new Reader() {
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
throw new IOException("closed");
}
@Override
public void close() throws IOException {
}
};
engine.getContext().setReader(closedInput);
engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE);
try {
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
// add additional bindings
if (aBindings != null) {
for (Entry<String, Object> e : aBindings.entrySet()) {
bindings.put(e.getKey(), e.getValue());
}
}
prepareBindings(bindings);
Object evalResult = engine.eval(getReader());
engine.getContext().getErrorWriter().flush();
engine.getContext().getWriter().flush();
// Add output to the script result
ScriptResult<E> result = this.getResult(evalResult, bindings);
result.setOutput(outputBoundedWriter.toString());
return result;
} catch (javax.script.ScriptException e) {
// drop exception cause as it might not be serializable
ScriptException scriptException = new ScriptException(e.getMessage());
scriptException.setStackTrace(e.getStackTrace());
return new ScriptResult<>(scriptException);
} catch (Throwable t) {
String stack = Throwables.getStackTraceAsString(t);
if (t.getMessage() != null) {
stack = t.getMessage() + System.lineSeparator() + stack;
}
return new ScriptResult<>(new Exception(stack));
}
}
Aggregations