use of javax.script.Invocable in project sling by apache.
the class PipeBindings method instantiateObject.
/**
* Instantiate object from expression
* @param expr ecma expression
* @return instantiated object
*/
public Object instantiateObject(String expr) {
try {
Object result = evaluate(expr);
if (result != null && !result.getClass().getName().startsWith("java.lang.")) {
//special case of the date in which case jdk.nashorn.api.scripting.ScriptObjectMirror will
//be returned
JsDate jsDate = ((Invocable) engine).getInterface(result, JsDate.class);
if (jsDate != null) {
Date date = new Date(jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
}
return result;
} catch (ScriptException e) {
log.error("Unable to evaluate the script for expr {} ", expr, e);
}
return expr;
}
use of javax.script.Invocable in project accumulo by apache.
the class ScriptCommand method execute.
@Override
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception {
boolean invoke = false;
ScriptEngineManager mgr = new ScriptEngineManager();
if (cl.hasOption(list.getOpt())) {
listJSREngineInfo(mgr, shellState);
} else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) {
String engineName = DEFAULT_ENGINE;
if (cl.hasOption(engine.getOpt())) {
engineName = cl.getOptionValue(engine.getOpt());
}
ScriptEngine engine = mgr.getEngineByName(engineName);
if (null == engine) {
shellState.printException(new Exception(engineName + " not found"));
return 1;
}
if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) {
if (!(engine instanceof Invocable)) {
shellState.printException(new Exception(engineName + " does not support invoking functions or methods"));
return 1;
}
invoke = true;
}
ScriptContext ctx = new SimpleScriptContext();
// Put the following objects into the context so that they
// are available to the scripts
// TODO: What else should go in here?
Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE);
b.put("connection", shellState.getConnector());
List<Object> argValues = new ArrayList<>();
if (cl.hasOption(args.getOpt())) {
String[] argList = cl.getOptionValue(args.getOpt()).split(",");
for (String arg : argList) {
String[] parts = arg.split("=");
if (parts.length == 0) {
continue;
} else if (parts.length == 1) {
b.put(parts[0], null);
argValues.add(null);
} else if (parts.length == 2) {
b.put(parts[0], parts[1]);
argValues.add(parts[1]);
}
}
}
ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
Object[] argArray = argValues.toArray(new Object[argValues.size()]);
Writer writer = null;
if (cl.hasOption(out.getOpt())) {
File f = new File(cl.getOptionValue(out.getOpt()));
writer = new FileWriter(f);
ctx.setWriter(writer);
}
if (cl.hasOption(file.getOpt())) {
File f = new File(cl.getOptionValue(file.getOpt()));
if (!f.exists()) {
if (null != writer) {
writer.close();
}
shellState.printException(new Exception(f.getAbsolutePath() + " not found"));
return 1;
}
Reader reader = new FileReader(f);
try {
engine.eval(reader, ctx);
if (invoke) {
this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
}
} catch (ScriptException ex) {
shellState.printException(ex);
return 1;
} finally {
reader.close();
if (null != writer) {
writer.close();
}
}
} else if (cl.hasOption(script.getOpt())) {
String inlineScript = cl.getOptionValue(script.getOpt());
try {
if (engine instanceof Compilable) {
Compilable compiledEng = (Compilable) engine;
CompiledScript script = compiledEng.compile(inlineScript);
script.eval(ctx);
if (invoke) {
this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
}
} else {
engine.eval(inlineScript, ctx);
if (invoke) {
this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
}
}
} catch (ScriptException ex) {
shellState.printException(ex);
return 1;
} finally {
if (null != writer) {
writer.close();
}
}
}
if (null != writer) {
writer.close();
}
} else {
printHelp(shellState);
}
return 0;
}
use of javax.script.Invocable in project keystore-explorer by kaikramer.
the class PacProxySelector method compilePacScript.
private Invocable compilePacScript(String pacScript) throws PacProxyException {
try {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
Invocable invocale = (Invocable) jsEngine;
jsEngine.eval(pacScript);
jsEngine.eval(new InputStreamReader(PacProxySelector.class.getResourceAsStream("pacUtils.js")));
return invocale;
} catch (ScriptException ex) {
throw new PacProxyException(res.getString("NoCompilePacScript.exception.message"), ex);
}
}
use of javax.script.Invocable in project tutorials by eugenp.
the class NashornUnitTest method jvmBoundaryExamples.
@Test
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
Invocable invocable = (Invocable) engine;
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
Assert.assertEquals("Hello baeldung", funcResult);
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
}
use of javax.script.Invocable in project ofbiz-framework by apache.
the class ScriptUtil method executeScript.
/**
* Executes the script at the specified location and returns the result.
*
* @param filePath Script path and file name.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @param args Function/method arguments.
* @return The script result.
* @throws ScriptException
* @throws NoSuchMethodException
* @throws IOException
* @throws IllegalArgumentException
*/
public static Object executeScript(String filePath, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException, IOException {
Assert.notNull("filePath", filePath, "scriptContext", scriptContext);
scriptContext.setAttribute(ScriptEngine.FILENAME, filePath, ScriptContext.ENGINE_SCOPE);
if (functionName == null) {
// The Rhino script engine will not work when invoking a function on a compiled script.
// The test for null can be removed when the engine is fixed.
CompiledScript script = compileScriptFile(filePath);
if (script != null) {
return executeScript(script, null, scriptContext, args);
}
}
String fileExtension = getFileExtension(filePath);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension(fileExtension);
if (engine == null) {
throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
}
if (Debug.verboseOn()) {
Debug.logVerbose("Begin processing script [" + filePath + "] using engine " + engine.getClass().getName(), module);
}
engine.setContext(scriptContext);
URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(scriptUrl.getFile()), UtilIO.getUtf8())) {
Object result = engine.eval(reader);
if (UtilValidate.isNotEmpty(functionName)) {
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
}
Aggregations