Search in sources :

Example 21 with Invocable

use of javax.script.Invocable in project java8-tutorial by winterbe.

the class Nashorn5 method main.

public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval("load('res/nashorn5.js')");
    Invocable invocable = (Invocable) engine;
    Product product = new Product();
    product.setName("Rubber");
    product.setPrice(1.99);
    product.setStock(1037);
    Object result = invocable.invokeFunction("getValueOfGoods", product);
    System.out.println(result);
}
Also used : Invocable(javax.script.Invocable) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 22 with Invocable

use of javax.script.Invocable in project zaproxy by zaproxy.

the class ExtensionScript method getInterface.

/**
 * Gets the interface {@code class1} from the given {@code script}. Might return {@code null} if
 * the {@code script} does not implement the interface.
 *
 * <p>First tries to get the interface directly from the {@code script} by calling the method
 * {@code ScriptWrapper.getInterface(Class)}, if it returns {@code null} the interface will be
 * extracted from the script after invoking it, using the method {@code
 * Invocable.getInterface(Class)}.
 *
 * <p>The context class loader of caller thread is replaced with the class loader {@code
 * AddOnLoader} to allow the script to access classes of add-ons. If this behaviour is not
 * desired call the method {@code getInterfaceWithOutAddOnLoader(} instead.
 *
 * @param script the script that will be invoked
 * @param class1 the interface that will be obtained from the script
 * @return the interface implemented by the script, or {@code null} if the {@code script} does
 *     not implement the interface.
 * @throws ScriptException if the engine of the given {@code script} was not found.
 * @throws IOException if an error occurred while obtaining the interface directly from the
 *     script ( {@code ScriptWrapper.getInterface(Class)})
 * @see #getInterfaceWithOutAddOnLoader(ScriptWrapper, Class)
 * @see ScriptWrapper#getInterface(Class)
 * @see Invocable#getInterface(Class)
 */
public <T> T getInterface(ScriptWrapper script, Class<T> class1) throws ScriptException, IOException {
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(ExtensionFactory.getAddOnLoader());
    try {
        T iface = script.getInterface(class1);
        if (iface != null) {
            // the script wrapper has overridden the usual scripting mechanism
            return iface;
        }
    } finally {
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
    }
    if (script.isRunnableStandalone()) {
        return null;
    }
    Invocable invocable = invokeScript(script);
    if (invocable != null) {
        return invocable.getInterface(class1);
    }
    return null;
}
Also used : Invocable(javax.script.Invocable)

Example 23 with Invocable

use of javax.script.Invocable in project zaproxy by zaproxy.

the class ExtensionScript method invokeScriptImpl.

/**
 * Invokes the given {@code script}, handling any {@code Exception} thrown during the
 * invocation.
 *
 * <p>Script's (or default) {@code Writer} is set to the {@code ScriptContext} of the {@code
 * ScriptEngine} before the invocation.
 *
 * @param script the script that will be invoked
 * @return an {@code Invocable} for the {@code script}, or {@code null} if none.
 * @see #getWriters(ScriptWrapper)
 * @see Invocable
 */
private Invocable invokeScriptImpl(ScriptWrapper script) {
    ScriptEngine se = script.getEngine().getEngine();
    Writer writer = getWriters(script);
    se.getContext().setWriter(writer);
    // Set the script name as a context attribute - this is used for script level variables
    se.getContext().setAttribute(SCRIPT_NAME_ATT, script.getName(), ScriptContext.ENGINE_SCOPE);
    reloadIfChangedOnDisk(script);
    recordScriptCalledStats(script);
    try {
        se.eval(script.getContents());
    } catch (Exception e) {
        handleScriptException(script, writer, e);
    } catch (NoClassDefFoundError | ExceptionInInitializerError e) {
        if (e.getCause() instanceof Exception) {
            handleScriptException(script, writer, (Exception) e.getCause());
        } else {
            handleUnspecifiedScriptError(script, writer, e.getMessage());
        }
    }
    if (se instanceof Invocable) {
        return (Invocable) se;
    }
    return null;
}
Also used : Invocable(javax.script.Invocable) ScriptEngine(javax.script.ScriptEngine) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) MalformedInputException(java.nio.charset.MalformedInputException) InvalidParameterException(java.security.InvalidParameterException) ScriptException(javax.script.ScriptException) IOException(java.io.IOException)

Example 24 with Invocable

use of javax.script.Invocable in project bytecode-viewer by Konloch.

the class JavascriptPluginLaunchStrategy method run.

@Override
public Plugin run(File file) throws Throwable {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName(firstPickEngine);
    // nashorn compatability with graal
    if (engine == null) {
        engine = manager.getEngineByName(fallBackEngine);
        if (engine == null)
            throw new Exception("Cannot find Javascript script engine! Please contact Konloch.");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("polyglot.js.allowHostAccess", true);
        bindings.put("polyglot.js.allowAllAccess", true);
        bindings.put("polyglot.js.allowHostClassLookup", true);
    }
    Reader reader = new FileReader(file);
    engine.eval(reader);
    ScriptEngine finalEngine = engine;
    return new Plugin() {

        @Override
        public void execute(List<ClassNode> classNodeList) {
            try {
                // add the active container as a global variable to the JS script
                finalEngine.put("activeContainer", activeContainer);
                // invoke the JS function
                ((Invocable) finalEngine).invokeFunction("execute", classNodeList);
            } catch (NoSuchMethodException | ScriptException e) {
                BytecodeViewer.handleException(e);
            }
        }
    };
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ScriptEngineManager(javax.script.ScriptEngineManager) Reader(java.io.Reader) FileReader(java.io.FileReader) FileReader(java.io.FileReader) List(java.util.List) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) Plugin(the.bytecode.club.bytecodeviewer.api.Plugin)

Example 25 with Invocable

use of javax.script.Invocable in project jgnash by ccavanaugh.

the class ImportFilter method acceptTransaction.

public void acceptTransaction(final ImportTransaction importTransaction) {
    try {
        final Invocable invocable = (Invocable) scriptEngine;
        invocable.invokeFunction("acceptTransaction", importTransaction);
    } catch (final ScriptException | NoSuchMethodException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException)

Aggregations

Invocable (javax.script.Invocable)68 ScriptException (javax.script.ScriptException)41 ScriptEngine (javax.script.ScriptEngine)30 ScriptEngineManager (javax.script.ScriptEngineManager)22 IOException (java.io.IOException)19 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)10 FileReader (java.io.FileReader)9 Reader (java.io.Reader)9 Compilable (javax.script.Compilable)5 CompiledScript (javax.script.CompiledScript)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Bindings (javax.script.Bindings)4 ScriptContext (javax.script.ScriptContext)4 Writer (java.io.Writer)3 SimpleScriptContext (javax.script.SimpleScriptContext)3 ValidationResult (org.apache.nifi.components.ValidationResult)3