Skip to content

Commit

Permalink
implemented issue JPPF-546
Browse files Browse the repository at this point in the history
  • Loading branch information
lolocohen committed Sep 17, 2018
1 parent 0d121c6 commit c5514ca
Show file tree
Hide file tree
Showing 11 changed files with 274 additions and 167 deletions.
Expand Up @@ -99,20 +99,14 @@ private void invokeScript(final MouseEvent event, final String eventType) {
variables.put("option", option);
variables.put("event", event);
variables.put("eventType", eventType);
ScriptRunner runner = null;
try {
runner = ScriptRunnerFactory.getScriptRunner(this.language);
final ScriptDefinition spec = new ScriptDefinition(this.language, scriptText, uuid, variables);
final long start = System.nanoTime();
runner.evaluate(uuid, scriptText, variables);
spec.evaluate();
final long elapsed = (System.nanoTime() - start) / 1_000_000L;
if (debugEnabled) {
final StringBuilder sb = new StringBuilder("executed ").append(language).append(" script in ").append(elapsed).append(" ms for [").append(option).append(']');
log.debug(sb.toString());
}
if (debugEnabled) log.debug(new StringBuilder("executed ").append(language).append(" script in ").append(elapsed).append(" ms for [").append(option).append(']').toString());
} catch (final JPPFScriptingException e) {
log.error("Error while executing script for " + option + "\nScript = \n" + scriptText, e);
} finally {
ScriptRunnerFactory.releaseScriptRunner(runner);
}
}

Expand Down
Expand Up @@ -94,20 +94,17 @@ public void valueChanged(final ValueChangeEvent event) {
final Map<String, Object> variables = new HashMap<>();
variables.put("root", option.getRoot());
variables.put("option", option);
ScriptRunner runner = null;
try {
runner = ScriptRunnerFactory.getScriptRunner(this.language);
final ScriptDefinition spec = new ScriptDefinition(this.language, scriptText, uuid, variables);
final long start = System.nanoTime();
runner.evaluate(uuid, scriptText, variables);
spec.evaluate();
final long elapsed = (System.nanoTime() - start) / 1_000_000L;
if (debugEnabled) {
final StringBuilder sb = new StringBuilder("executed ").append(language).append(" script in ").append(elapsed).append(" ms for [").append(option).append(']');
log.debug(sb.toString());
}
} catch (final JPPFScriptingException e) {
log.error("Error while executing script for " + option + "\nScript = \n" + scriptText, e);
} finally {
ScriptRunnerFactory.releaseScriptRunner(runner);
}
}
}
10 changes: 2 additions & 8 deletions admin/src/java/org/jppf/ui/options/xml/OptionElementFactory.java
Expand Up @@ -445,14 +445,8 @@ public List<OptionElement> loadImport(final OptionDescriptor desc) throws Except
} else if ("script".equalsIgnoreCase(source)) {
if (!desc.scripts.isEmpty()) {
final ScriptDescriptor scriptDesc = desc.scripts.get(0);
ScriptRunner runner = null;
try {
runner = ScriptRunnerFactory.getScriptRunner(scriptDesc.language);
final String path = (String) runner.evaluate(scriptDesc.content, new HashMap<String, Object>());
if (path != null) list.add(builder.buildPage(path, null));
} finally {
ScriptRunnerFactory.releaseScriptRunner(runner);
}
final String path = (String) new ScriptDefinition(scriptDesc.language, scriptDesc.language).evaluate();
if (path != null) list.add(builder.buildPage(path, null));
}
}
return list;
Expand Down
53 changes: 11 additions & 42 deletions common/src/java/org/jppf/node/policy/ScriptedPolicy.java
Expand Up @@ -40,42 +40,22 @@ public class ScriptedPolicy extends ExecutionPolicy {
*/
private static Logger log = LoggerFactory.getLogger(ScriptedPolicy.class);
/**
* The script language to use.
* The script specification.
*/
protected final String language;
/**
* A unique id given to this script, to allow caching its compiled version.
*/
protected final String id;
/**
* The script to execute.
*/
protected String script;
protected final ScriptDefinition spec;
/**
* Flag set if an error is raised while executing the script,
* to avoid evaluating the script again.
*/
protected boolean evaluationError = false;

/**
* Initialize this policy with a script language.
* @param language the script language to use.
*/
private ScriptedPolicy(final String language) {
if (language == null) throw new IllegalArgumentException("the script language cannot be null");
this.id = JPPFUuid.normalUUID();
this.language = language;
}

/**
* Initialize this policy with a script language and a script.
* @param language the script language to use.
* @param script the script to execute.
*/
public ScriptedPolicy(final String language, final String script) {
this(language);
if (script == null) throw new IllegalArgumentException("the script cannot be null");
this.script = script;
this.spec = new ScriptDefinition(language, script);
}

/**
Expand All @@ -85,9 +65,7 @@ public ScriptedPolicy(final String language, final String script) {
* @throws IOException if any error occurs while reading the script from the reader.
*/
public ScriptedPolicy(final String language, final Reader scriptReader) throws IOException {
this(language);
if (scriptReader == null) throw new IllegalArgumentException("the script reader cannot be null");
this.script = FileUtils.readTextFile(scriptReader);
this.spec = new ScriptDefinition(language, scriptReader);
}

/**
Expand All @@ -97,15 +75,12 @@ public ScriptedPolicy(final String language, final Reader scriptReader) throws I
* @throws IOException if any error occurs while reading the script from the reader.
*/
public ScriptedPolicy(final String language, final File scriptFile) throws IOException {
if (language == null) throw new IllegalArgumentException("script language cannot be null");
this.language = language;
this.script = FileUtils.readTextFile(scriptFile);
this.id = JPPFUuid.normalUUID();
this.spec = new ScriptDefinition(language, scriptFile);
}

@Override
public boolean accepts(final PropertiesCollection<String> info) {
if ((script == null) || evaluationError) return false;
if (evaluationError) return false;
final Map<String, Object> variables = new HashMap<>();
variables.put("jppfSystemInfo", info);
final PolicyContext ctx = getContext();
Expand All @@ -116,27 +91,21 @@ public boolean accepts(final PropertiesCollection<String> info) {
variables.put("jppfDispatches", ctx.getJobDispatches());
variables.put("jppfStats", ctx.getStats());
}
ScriptRunner runner = null;
try {
runner = ScriptRunnerFactory.getScriptRunner(language);
if (runner != null) {
final Object result = runner.evaluate(id, script, variables);
if (!(result instanceof Boolean)) throw new JPPFException("result of scripted policy should be a boolean but instead is " + result);
return (Boolean) result;
}
final Object result = spec.evaluate(variables);
if (!(result instanceof Boolean)) throw new JPPFException("result of scripted policy should be a boolean but instead is " + result);
return (Boolean) result;
} catch (final Exception|NoClassDefFoundError e) {
evaluationError = true;
log.error("exception occurred evaluating scripted policy: {}\npolicy is\n{}", ExceptionUtils.getStackTrace(e), this);
} finally {
if (runner != null) ScriptRunnerFactory.releaseScriptRunner(runner);
}
return false;
}

@Override
public String toString(final int n) {
final StringBuilder sb = new StringBuilder(indent(n)).append("<Script language=\"").append(language).append("\"><![CDATA[\n");
if (script != null) sb.append(script).append('\n');
final StringBuilder sb = new StringBuilder(indent(n)).append("<Script language=\"").append(spec.getLanguage()).append("\"><![CDATA[\n");
sb.append(spec.getScript()).append('\n');
return sb.append(indent(n)).append("]]></Script>\n").toString();
}
}
61 changes: 19 additions & 42 deletions common/src/java/org/jppf/node/protocol/ScriptedTask.java
Expand Up @@ -39,21 +39,9 @@ public class ScriptedTask<T> extends AbstractTask<T> {
*/
private static final long serialVersionUID = 1L;
/**
* The JSR 223 script language to use.
* Specfications for the script to execute.
*/
protected String language;
/**
* The script to execute from this task.
*/
protected String script;
/**
* Unique identifier for the script, which allows reusing a compiled version if one has already been produced.
*/
protected String reusableId;
/**
* The bindings provide variables available to the script engine during execution of the script.
*/
protected Map<String, Object> bindings = new HashMap<>();
protected ScriptDefinition scriptSpec;

/**
* Default constructor provided as a convenience for subclassing.
Expand All @@ -71,12 +59,7 @@ protected ScriptedTask() {
* @throws IllegalArgumentException if {@code language} or {@code script} is {@code null}.
*/
public ScriptedTask(final String language, final String script, final String reusableId, final Map<String, Object> bindings) throws IllegalArgumentException {
if (language == null) throw new IllegalArgumentException("the script language cannot be null");
if (script == null) throw new IllegalArgumentException("the script source cannot be null");
this.language = language;
this.script = script;
this.reusableId = reusableId;
if (bindings != null) this.bindings.putAll(bindings);
this.scriptSpec = new ScriptDefinition(language, script, reusableId, bindings);
}

/**
Expand All @@ -91,7 +74,7 @@ public ScriptedTask(final String language, final String script, final String reu
*/
public ScriptedTask(final String language, final Reader scriptReader, final String reusableId, final Map<String, Object> bindings)
throws IllegalArgumentException, IOException {
this(language, FileUtils.readTextFile(scriptReader), reusableId, bindings);
this.scriptSpec = new ScriptDefinition(language, FileUtils.readTextFile(scriptReader), reusableId, bindings);
}

/**
Expand All @@ -106,26 +89,20 @@ public ScriptedTask(final String language, final Reader scriptReader, final Stri
*/
public ScriptedTask(final String language, final File scriptFile, final String reusableId, final Map<String, Object> bindings)
throws IllegalArgumentException, IOException {
this(language, FileUtils.readTextFile(scriptFile), reusableId, bindings);
this.scriptSpec = new ScriptDefinition(language, FileUtils.readTextFile(scriptFile), reusableId, bindings);
}

@Override
public void run() {
ScriptRunner runner = null;
try {
runner = ScriptRunnerFactory.getScriptRunner(language);
if (runner != null) {
final Map<String, Object> bnd = new HashMap<>(bindings);
bnd.put("jppfTask", this);
@SuppressWarnings("unchecked")
final T result = (T) runner.evaluate(reusableId, script, bnd);
// may have been set from the script
if ((getResult() == null) && (result != null)) setResult(result);
}
} catch(final Exception e) {
final Map<String, Object> bnd = new HashMap<>();
bnd.put("jppfTask", this);
@SuppressWarnings("unchecked")
final T result = (T) scriptSpec.evaluate(bnd);
// may have been set from the script
if ((getResult() == null) && (result != null)) setResult(result);
} catch(final JPPFScriptingException e) {
setThrowable(e);
} finally {
ScriptRunnerFactory.releaseScriptRunner(runner);
}
}

Expand All @@ -134,31 +111,31 @@ public void run() {
* @return the script language a s a script.
*/
public String getLanguage() {
return language;
return scriptSpec.getLanguage();
}

/**
* Get the script to execute from this task.
* @return the script source as a string.
*/
public String getScript() {
return script;
return scriptSpec.getScript();
}

/**
* Get the unique identifier for the script.
* @return the identifier as a string.
*/
public String getReusableId() {
return reusableId;
return scriptSpec.getId();
}

/**
* Get the user-defined variable bindings.
* @return a map of variable names to their value.
*/
public Map<String, Object> getBindings() {
return bindings;
return scriptSpec.getBindings();
}

/**
Expand All @@ -167,8 +144,8 @@ public Map<String, Object> getBindings() {
* @param value the value of the variable.
* @return this task, for method chaining.
*/
public ScriptedTask<T>addBinding(final String name, final Object value) {
bindings.put(name, value);
public ScriptedTask<T> addBinding(final String name, final Object value) {
scriptSpec.addBinding(name, value);
return this;
}

Expand All @@ -178,6 +155,6 @@ public Map<String, Object> getBindings() {
* @return the value of the variable, or {@code null} if the variable was not bound.
*/
public Object removeBinding(final String name) {
return bindings.remove(name);
return scriptSpec.removeBinding(name);
}
}

0 comments on commit c5514ca

Please sign in to comment.