Java Code Examples for javax.script.Invocable#getInterface()

The following examples show how to use javax.script.Invocable#getInterface() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RunnableImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 2
Source File: RunnableImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 3
Source File: RunnableImpl.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 4
Source File: RunnableImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 5
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void pythonFn() throws Exception {
    ScriptEngine python = Scripting.createManager().getEngineByMimeType("text/x-python");
    assumeNotNull("Need python", python);
    Object rawMul = python.eval(MUL);
    assertNotNull("mul created", rawMul);
    assertTrue("Engines are invocable: " + python, python instanceof Invocable);
    final Invocable inv = (Invocable)python;

    Object res = inv.invokeFunction("mul", 6, 7);
    assertNotNull("Expecting non-null", res);

    assertTrue("Expecting number: " + res + " type: " + res.getClass(), res instanceof Number);
    assertEquals(42, ((Number)res).intValue());

    Mul mul = inv.getInterface(rawMul, Mul.class);
    assertEquals(42, mul.multiplyTwoNumbers(7, 6));
}
 
Example 6
Source File: RunnableImplObject.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 7
Source File: RunnableImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 8
Source File: RunnableImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 9
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void defaultMethodTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Invocable inv = (Invocable) e;

    final Object obj = e.eval("({ apply: function(arg) { return arg.toUpperCase(); }})");
    @SuppressWarnings("unchecked")
    final Function<String, String> func = inv.getInterface(obj, Function.class);
    assertEquals(func.apply("hello"), "HELLO");
}
 
Example 10
Source File: StandardScriptFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
protected Object adaptToInterfaces(
		@Nullable Object script, ScriptSource scriptSource, Class<?>... actualInterfaces) {

	Class<?> adaptedIfc;
	if (actualInterfaces.length == 1) {
		adaptedIfc = actualInterfaces[0];
	}
	else {
		adaptedIfc = ClassUtils.createCompositeInterface(actualInterfaces, this.beanClassLoader);
	}

	if (adaptedIfc != null) {
		ScriptEngine scriptEngine = this.scriptEngine;
		if (!(scriptEngine instanceof Invocable)) {
			throw new ScriptCompilationException(scriptSource,
					"ScriptEngine must implement Invocable in order to adapt it to an interface: " + scriptEngine);
		}
		Invocable invocable = (Invocable) scriptEngine;
		if (script != null) {
			script = invocable.getInterface(script, adaptedIfc);
		}
		if (script == null) {
			script = invocable.getInterface(adaptedIfc);
			if (script == null) {
				throw new ScriptCompilationException(scriptSource,
						"Could not adapt script to interface [" + adaptedIfc.getName() + "]");
			}
		}
	}

	return script;
}
 
Example 11
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void mirrorUnwrapInterfaceMethod() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine engine = engineManager.getEngineByName("nashorn");
    final Invocable invocable = (Invocable)engine;
    engine.eval("function apply(obj) { " +
        " return obj instanceof Packages.jdk.nashorn.api.scripting.ScriptObjectMirror; " +
        "}");
    @SuppressWarnings("unchecked")
    final Function<Object,Object> func = invocable.getInterface(Function.class);
    assertFalse((boolean)func.apply(engine.eval("({ x: 2 })")));
}
 
Example 12
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void checkMirrorToObject() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine engine = engineManager.getEngineByName("nashorn");
    final Invocable invocable = (Invocable)engine;

    engine.eval("function test1(arg) { return { arg: arg }; }");
    engine.eval("function test2(arg) { return arg; }");
    engine.eval("function compare(arg1, arg2) { return arg1 == arg2; }");

    final Map<String, Object> map = new HashMap<>();
    map.put("option", true);

    final MirrorCheckExample example = invocable.getInterface(MirrorCheckExample.class);

    final Object value1 = invocable.invokeFunction("test1", map);
    final Object value2 = example.test1(map);
    final Object value3 = invocable.invokeFunction("test2", value2);
    final Object value4 = example.test2(value2);

    // check that Object type argument receives a ScriptObjectMirror
    // when ScriptObject is passed
    assertEquals(ScriptObjectMirror.class, value1.getClass());
    assertEquals(ScriptObjectMirror.class, value2.getClass());
    assertEquals(ScriptObjectMirror.class, value3.getClass());
    assertEquals(ScriptObjectMirror.class, value4.getClass());
    assertTrue((boolean)invocable.invokeFunction("compare", value1, value1));
    assertTrue(example.compare(value1, value1));
    assertTrue((boolean)invocable.invokeFunction("compare", value3, value4));
    assertTrue(example.compare(value3, value4));
}
 
Example 13
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void defaultMethodTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Invocable inv = (Invocable) e;

    final Object obj = e.eval("({ apply: function(arg) { return arg.toUpperCase(); }})");
    @SuppressWarnings("unchecked")
    final Function<String, String> func = inv.getInterface(obj, Function.class);
    assertEquals(func.apply("hello"), "HELLO");
}
 
Example 14
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void checkMirrorToObject() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine engine = engineManager.getEngineByName("nashorn");
    final Invocable invocable = (Invocable)engine;

    engine.eval("function test1(arg) { return { arg: arg }; }");
    engine.eval("function test2(arg) { return arg; }");
    engine.eval("function compare(arg1, arg2) { return arg1 == arg2; }");

    final Map<String, Object> map = new HashMap<>();
    map.put("option", true);

    final MirrorCheckExample example = invocable.getInterface(MirrorCheckExample.class);

    final Object value1 = invocable.invokeFunction("test1", map);
    final Object value2 = example.test1(map);
    final Object value3 = invocable.invokeFunction("test2", value2);
    final Object value4 = example.test2(value2);

    // check that Object type argument receives a ScriptObjectMirror
    // when ScriptObject is passed
    assertEquals(ScriptObjectMirror.class, value1.getClass());
    assertEquals(ScriptObjectMirror.class, value2.getClass());
    assertEquals(ScriptObjectMirror.class, value3.getClass());
    assertEquals(ScriptObjectMirror.class, value4.getClass());
    assertTrue((boolean)invocable.invokeFunction("compare", value1, value1));
    assertTrue(example.compare(value1, value1));
    assertTrue((boolean)invocable.invokeFunction("compare", value3, value4));
    assertTrue(example.compare(value3, value4));
}
 
Example 15
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void mirrorUnwrapInterfaceMethod() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine engine = engineManager.getEngineByName("nashorn");
    final Invocable invocable = (Invocable)engine;
    engine.eval("function apply(obj) { " +
        " return obj instanceof Packages.jdk.nashorn.api.scripting.ScriptObjectMirror; " +
        "}");
    @SuppressWarnings("unchecked")
    final Function<Object,Object> func = invocable.getInterface(Function.class);
    assertFalse((boolean)func.apply(engine.eval("({ x: 2 })")));
}
 
Example 16
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void returnArrayInPython() throws Exception {
    ScriptEngine python = Scripting.createManager().getEngineByMimeType("text/x-python");
    assumeNotNull("Need python", python);
    python.eval("\n"
            + "import math\n"
            + "\n"
            + "def arr(x):\n"
            + "  return [ 1, 2, 'a', math.pi, x ]\n"
            + "\n"
    );

    assertTrue("Engines are invocable: " + python, python instanceof Invocable);
    final Invocable inv = (Invocable)python;

    Sum sum = new Sum();
    Object raw = inv.invokeFunction("arr", sum);

    List<?> list = inv.getInterface(raw, List.class);
    assertNotNull("List " + list, list);
    assertEquals("Length of five", 5, list.size());

    List<?> list2 = inv.getInterface(list, List.class);
    assertNotNull("List 2 " + list2, list2);
    assertEquals("Length 2 of five", 5, list2.size());

    assertEquals(1, list.get(0));
    assertEquals(2, list.get(1));
    assertEquals("a", list.get(2));
    assertEquals(Math.PI, list.get(3));
    assertEquals(sum, list.get(4));
}
 
Example 17
Source File: Contexts.java    From nano with Apache License 2.0 5 votes vote down vote up
public static HttpHandler instantiate(Path scriptFile) {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine engine = sem.getEngineByName("javascript");
    try {
        engine.eval(new FileReader(scriptFile.toFile()));
    } catch (ScriptException | FileNotFoundException ex) {
        throw new IllegalStateException(ex);
    }
    Invocable invocable = (Invocable) engine;
    NanoRequest request = invocable.getInterface(NanoRequest.class);

    return (HttpExchange he) -> {
        final OutputStream responseBody = he.getResponseBody();
        StringBuilder builder = new StringBuilder();
        ResponseWriter writer = builder::append;
        final InputStream requestBody = he.getRequestBody();
        String requestContent;
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(requestBody))) {
            requestContent = buffer.lines().collect(Collectors.joining("\n"));
        }
        Headers requestHeaders = he.getRequestHeaders();
        Headers responseHeaders = he.getResponseHeaders();
        int statusCode = request.process(he.getRequestMethod(), requestHeaders, responseHeaders, requestContent, writer);
        String content = builder.toString();
        he.sendResponseHeaders(statusCode, content.length());
        responseBody.write(content.getBytes());
        responseBody.flush();
        he.close();
    };
}
 
Example 18
Source File: FunctionScriptLoader.java    From enhydrator with Apache License 2.0 5 votes vote down vote up
public ColumnTransformer createFromScript(Reader script) {
    Invocable invocable = (Invocable) engine;
    try {
        if (scriptEngineBindings != null) {
            manager.getBindings().putAll(scriptEngineBindings);
        }
        engine.eval(script);
    } catch (ScriptException ex) {
        throw new IllegalStateException("Cannot evaluate script", ex);
    }
    return invocable.getInterface(ColumnTransformer.class);

}
 
Example 19
Source File: FunctionScriptLoader.java    From enhydrator with Apache License 2.0 5 votes vote down vote up
public ColumnTransformer createFromScript(String script) {
    Invocable invocable = (Invocable) engine;
    try {
        if (scriptEngineBindings != null) {
            manager.getBindings().putAll(scriptEngineBindings);
        }
        engine.eval(script);
    } catch (ScriptException ex) {
        throw new IllegalStateException("Cannot evaluate script", ex);
    }
    return invocable.getInterface(ColumnTransformer.class);

}
 
Example 20
Source File: ScriptingTutorial.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void callJavaScriptClassFactoryFromJava() throws Exception {
    String src = "\n"
        + "(function() {\n"
        + "  class JSIncrementor {\n"
        + "     constructor(init) {\n"
        + "       this.value = init;\n"
        + "     }\n"
        + "     inc() {\n"
        + "       return ++this.value;\n"
        + "     }\n"
        + "     dec() {\n"
        + "       return --this.value;\n"
        + "     }\n"
        + "  }\n"
        + "  return function(init) {\n"
        + "    return new JSIncrementor(init);\n"
        + "  }\n"
        + "})\n";

    // Evaluate JavaScript function definition
    Object jsFunction = engine.eval(src);

    final Invocable inv = (Invocable) engine;

    // Execute the JavaScript function
    Object jsFactory = inv.invokeMethod(jsFunction, "call");

    // Execute the JavaScript factory to create Java objects
    Incrementor initFive = inv.getInterface(
        inv.invokeMethod(jsFactory, "call", null, 5),
        Incrementor.class
    );
    Incrementor initTen = inv.getInterface(
        inv.invokeMethod(jsFactory, "call", null, 10),
        Incrementor.class
    );

    initFive.inc();
    assertEquals("Now at seven", 7, initFive.inc());

    initTen.dec();
    assertEquals("Now at eight", 8, initTen.dec());
    initTen.dec();

    assertEquals("Values are the same", initFive.value(), initTen.value());
}