javax.script.Invocable Java Examples

The following examples show how to use javax.script.Invocable. 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: InvokeScriptFunction.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 hello(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // invoke the global function named "hello"
    inv.invokeFunction("hello", "Scripting!!" );
}
 
Example #2
Source File: JavascriptTextTransformer.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes the UDF with specified data.
 *
 * @param data data to pass to the invocable function
 * @return The data transformed by the UDF in String format
 */
@Nullable
public String invoke(String data) throws ScriptException, IOException, NoSuchMethodException {
  Invocable invocable = getInvocable();
  if (invocable == null) {
    throw new RuntimeException("No udf was loaded");
  }

  Object result = getInvocable().invokeFunction(functionName(), data);
  if (result == null || ScriptObjectMirror.isUndefined(result)) {
    return null;

  } else if (result instanceof String) {
    return (String) result;

  } else {
    String className = result.getClass().getName();
    throw new RuntimeException(
        "UDF Function did not return a String. Instead got: " + className);
  }
}
 
Example #3
Source File: InvocableTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeMethod throws NoSuchMethodException on missing method.
 */
public void invokeMethodMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, "nonExistentMethod");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #4
Source File: ScriptTemplateView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	try {
		ScriptEngine engine = getEngine();
		Invocable invocable = (Invocable) engine;
		String url = getUrl();
		String template = getTemplate(url);

		Object html;
		if (this.renderObject != null) {
			Object thiz = engine.eval(this.renderObject);
			html = invocable.invokeMethod(thiz, this.renderFunction, template, model, url);
		}
		else {
			html = invocable.invokeFunction(this.renderFunction, template, model, url);
		}

		response.getWriter().write(String.valueOf(html));
	}
	catch (ScriptException ex) {
		throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
	}
}
 
Example #5
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #6
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Tests whether invocation of a JavaScript method through a variable arity
 * Java method will pass the vararg array. Both non-vararg and vararg
 * JavaScript methods are tested.
 *
 * @throws ScriptException
 */
public void variableArityInterfaceTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.eval(
            "function test1(i, strings) {"
            + "    return 'i == ' + i + ', strings instanceof java.lang.String[] == ' + (strings instanceof Java.type('java.lang.String[]')) + ', strings == ' + java.util.Arrays.toString(strings)"
            + "}"
            + "function test2() {"
            + "    return 'arguments[0] == ' + arguments[0] + ', arguments[1] instanceof java.lang.String[] == ' + (arguments[1] instanceof Java.type('java.lang.String[]')) + ', arguments[1] == ' + java.util.Arrays.toString(arguments[1])"
            + "}");
    final VariableArityTestInterface itf = ((Invocable) e).getInterface(VariableArityTestInterface.class);
    Assert.assertEquals(itf.test1(42, "a", "b"), "i == 42, strings instanceof java.lang.String[] == true, strings == [a, b]");
    Assert.assertEquals(itf.test2(44, "c", "d", "e"), "arguments[0] == 44, arguments[1] instanceof java.lang.String[] == true, arguments[1] == [c, d, e]");
}
 
Example #7
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that getInterface on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void getInterfaceNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).getInterface(new Object(), Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #8
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeMethod throws NPE on null method name.
 */
public void invokeMethodNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #9
Source File: JavaScriptEnginesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void returnArrayInJS() throws Exception {
    Object fn = engine.eval("(function(obj) {\n"
            + "  return [ 1, 2, 'a', Math.PI, obj ];\n"
            + "})\n");
    assertNotNull(fn);

    Sum sum = new Sum();
    Object raw = ((Invocable) engine).invokeMethod(fn, "call", null, sum);

    ArrayLike res = ((Invocable) engine).getInterface(raw, ArrayLike.class);
    if (res == null) {
        assumeNotNashorn();
    }
    assertNotNull("Result looks like array", res);

    List<?> list = ((Invocable) engine).getInterface(raw, List.class);
    assertEquals("Length of five", 5, list.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 #10
Source File: InvocableTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * check that null function name results in NPE.
 */
public void invokeFunctionNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable)e).invokeFunction(null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #11
Source File: RunnableImpl.java    From openjdk-jdk8u-backup 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 #12
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that calling method on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(new Object(), "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #13
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeMethod throws NoSuchMethodException on missing method.
 */
public void invokeMethodMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, "nonExistentMethod");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #14
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that attempt to call missing function results in
 * NoSuchMethodException.
 */
public void invokeFunctionMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable)e).invokeFunction("NonExistentFunc");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #15
Source File: ScriptRouter.java    From saluki with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(List<GrpcURL> providerUrls) {
  String rule = super.getRule();
  try {
    engine.eval(super.getRule());
    Invocable invocable = (Invocable) engine;
    GrpcURL refUrl = super.getRefUrl();
    Object obj = invocable.invokeFunction("route", refUrl, providerUrls);
    if (obj instanceof Boolean) {
      return (Boolean) obj;
    } else {
      return true;
    }
  } catch (ScriptException | NoSuchMethodException e) {
    log.error("route error , rule has been ignored. rule: " + rule + ", url: " + providerUrls, e);
    return true;
  }
}
 
Example #16
Source File: ReactorScriptManager.java    From mapleLemon with GNU General Public License v2.0 6 votes vote down vote up
public void act(MapleClient c, MapleReactor reactor) {
    try {
        Invocable iv = getInvocable("reactors/" + reactor.getReactorId() + ".js", c);
        if (iv == null) {
            if (c.getPlayer().isShowPacket()) {
                c.getPlayer().dropMessage(5, "未找到 反应堆 文件中的 " + reactor.getReactorId() + ".js 文件.");
            }
            FileoutputUtil.log(FileoutputUtil.Reactor_ScriptEx_Log, "未找到 反应堆 文件中的 " + reactor.getReactorId() + ".js 文件.");
            return;
        }
        ScriptEngine scriptengine = (ScriptEngine) iv;
        ReactorActionManager rm = new ReactorActionManager(c, reactor);

        scriptengine.put("rm", rm);
        iv.invokeFunction("act", new Object[0]);
    } catch (ScriptException | NoSuchMethodException e) {
        System.err.println("执行反应堆文件出错 反应堆ID: " + reactor.getReactorId() + ", 反应堆名称: " + reactor.getName() + " 错误信息: " + e);
        FileoutputUtil.log(FileoutputUtil.Reactor_ScriptEx_Log, "执行反应堆文件出错 反应堆ID: " + reactor.getReactorId() + ", 反应堆名称: " + reactor.getName() + " 错误信息: " + e);
    }
}
 
Example #17
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 #18
Source File: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

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

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example #19
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeMethod throws NPE on null method name.
 */
public void invokeMethodNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #20
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void invokeFunctionInGlobalScopeTest() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
     final ScriptContext ctxt = engine.getContext();

     // define a function called "func"
     engine.eval("func = function() { return 42 }");

     // move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
     ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define new function that calls "func" now in GLOBAL_SCOPE
     engine.eval("newfunc = function() { return func() }");

     // call "newfunc" and check the return value
     Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
 
Example #21
Source File: InvocableTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that calling method on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(new Object(), "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #22
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example #23
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a compiled script and returns the result.
 *
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        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;
}
 
Example #24
Source File: ScriptEngineView.java    From ask-sdk-frameworks-java with Apache License 2.0 6 votes vote down vote up
@Override
protected String renderInternal(Map<String, Object> model) throws Exception {
    SimpleBindings bindings = new SimpleBindings(model);
    Object result;
    if (renderFunction == null && renderObject == null) {
        // result of script is the response, no method is invoked and the model attributes are bounded globally
        result = scriptEngine.eval(script, bindings);
    } else {
        if (renderObject != null) {
            Object thiz = scriptEngine.eval(renderObject);
            result = ((Invocable) scriptEngine).invokeMethod(thiz, renderFunction, bindings);
        } else {
            result = ((Invocable) scriptEngine).invokeFunction(renderFunction, bindings);
        }
    }

    return toJson(result);
}
 
Example #25
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that attempt to call missing function results in
 * NoSuchMethodException.
 */
public void invokeFunctionMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable)e).invokeFunction("NonExistentFunc");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #26
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that calling method on null 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(null, "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #27
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that calling method on mirror created by another engine results in
 * IllegalArgumentException.
 */
public void invokeMethodMixEnginesTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine1 = m.getEngineByName("nashorn");
    final ScriptEngine engine2 = m.getEngineByName("nashorn");

    try {
        final Object obj = engine1.eval("({ run: function() {} })");
        // pass object from engine1 to engine2 as 'thiz' for invokeMethod
        ((Invocable) engine2).invokeMethod(obj, "run");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #28
Source File: InvocableTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that calling method on mirror created by another engine results in
 * IllegalArgumentException.
 */
public void invokeMethodMixEnginesTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine1 = m.getEngineByName("nashorn");
    final ScriptEngine engine2 = m.getEngineByName("nashorn");

    try {
        final Object obj = engine1.eval("({ run: function() {} })");
        // pass object from engine1 to engine2 as 'thiz' for invokeMethod
        ((Invocable) engine2).invokeMethod(obj, "run");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #29
Source File: FlowScriptStrategy.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
public String resolve(String mcgWebScoketCode, String httpSessionId, String flowId, String script, JSON param) throws ScriptException, NoSuchMethodException {
	if(StringUtils.isNotEmpty(script)) {
		script = script.replace("console.info(", "console.info(\"" + mcgWebScoketCode + "\", \"" + httpSessionId + "\", \"" + flowId + "\", ")
				.replace("console.success(", "console.success(\"" + mcgWebScoketCode + "\", \"" + httpSessionId + "\", \"" + flowId + "\", ")
				.replace("console.error(", "console.error(\"" + mcgWebScoketCode + "\", \"" + httpSessionId + "\", \"" + flowId + "\", ");
	}
	String dataJson = null;
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();  
    ScriptEngine engine = scriptEngineManager.getEngineByName("nashorn");
	engine.eval(script);
    Invocable invocable = (Invocable) engine;
    Object result = invocable.invokeFunction("main", param);
    
    dataJson = JSON.toJSONString(result);
    return dataJson;
}
 
Example #30
Source File: Test8.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest8\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test8.js")));
    Invocable inv = (Invocable)e;
    inv.invokeFunction("main", "Mustang");
    // use method of a specific script object
    Object scriptObj = e.get("scriptObj");
    inv.invokeMethod(scriptObj, "main", "Mustang");
}