Java 类javax.script.Invocable 实例源码

项目:crawler    文件:CrawlerUtils.java   
public Object executeJs(String js,@Nullable String funcName,Object... args){
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
        Object res=engine.eval(js);
        if(StringUtils.isNotBlank(funcName)){
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable) engine;
                res = invoke.invokeFunction(funcName, args);
            }
        }
        return res;
    } catch (Exception e) {
        log.error("",e);
    }
    return null;
}
项目:openjdk-jdk10    文件:Test4.java   
public static void main(String[] args) throws Exception {
    System.out.println("\nTest4\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", "."), "Test4.js")));
    Invocable inv = (Invocable)e;
    Runnable run1 = (Runnable)inv.getInterface(Runnable.class);
    run1.run();
    // use methods of a specific script object
    Object intfObj = e.get("intfObj");
    Runnable run2 = (Runnable)inv.getInterface(intfObj, Runnable.class);
    run2.run();
}
项目:openjdk-jdk10    文件:InvokeScriptFunction.java   
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!!" );
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:incubator-netbeans    文件:OQLEngineImpl.java   
public Object unwrapJavaObject(Object object, boolean tryAssociativeArray) {
    if (object == null) return null;
    String className = object.getClass().getName();
    boolean isNativeJS = className.contains(".javascript.")     // NOI18N
                      || className.equals("jdk.nashorn.api.scripting.ScriptObjectMirror"); // NOI18N

    try {
        Object ret = ((Invocable)engine).invokeFunction("unwrapJavaObject", object); // NOI18N
        if (isNativeJS && (ret == null || ret.equals(object)) && tryAssociativeArray) {
            ret = ((Invocable)engine).invokeFunction("unwrapMap", object); // NOI18N
        }
        return ret;
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Error unwrapping JS object", ex); // NOI18N
    }
    return null;
}
项目:incubator-netbeans    文件:OQLEngineImpl.java   
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
项目:Pogamut3    文件:StreamScriptLogic.java   
/**
 * Constructor which is needed when you have to initialize the
 * environment of the scripting language.
 * <p>
 * Currently used by SPOSHBot.
 */
@Override
public void initializeController(UT2004Bot bot) {
    super.initializeController(bot);
    // first create proper ScriptEngine
    scriptEngineManager = createScriptEngineManager();
    this.engine = createScriptEngine(scriptEngineManager);
    this.invocableEngine = (Invocable) this.engine;
    this.engineBinded();

    // and than load up the script.
    try {
        evalStream(this.getScriptStream());
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ScriptedAgentException("Unable to evaluate script", ex);
    }
    scriptBinded();
}
项目:cas-5.1.0    文件:ScriptedRegisteredServiceAttributeReleasePolicy.java   
private Map<String, Object> getScriptedAttributesFromFile(final Map<String, Object> attributes) throws Exception {
    final String engineName = getScriptEngineName();
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName(engineName);
    if (engine == null || StringUtils.isBlank(engineName)) {
        LOGGER.warn("Script engine is not available for [{}]", engineName);
        return new HashMap<>();
    }

    final File theScriptFile = ResourceUtils.getResourceFrom(this.scriptFile).getFile();
    if (theScriptFile.exists()) {
        LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
        final Object[] args = {attributes, LOGGER};

        LOGGER.debug("Executing  script's run method, with parameters [{}]", args);
        engine.eval(new FileReader(theScriptFile));
        final Invocable invocable = (Invocable) engine;
        final Map<String, Object> personAttributesMap = (Map<String, Object>) invocable.invokeFunction("run", args);

        LOGGER.debug("Final set of attributes determined by the script are [{}]", personAttributesMap);
        return personAttributesMap;
    }
    LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
    return new HashMap<>();
}
项目:sponge    文件:NashornKnowledgeBaseInterpreter.java   
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    // ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine result = factory.getScriptEngine("-scripting");

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, NashornPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(result, cls));

    result.put(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    eval(result, "load(\"classpath:" + INITIAL_SCRIPT + "\");");

    return result;
}
项目:sponge    文件:ScriptKotlinKnowledgeBaseInterpreter.java   
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    KotlinConstants.PROCESSOR_CLASSES
            .forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, KPlugin.class, Plugin.class.getSimpleName());

    // TODO The line below performs very slow in Kotlin
    eval(result, getStandardImportClasses().stream().map(cls -> "import " + cls.getName()).collect(Collectors.joining("\n")));

    setVariable(result, KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    return result;
}
项目:GoogleTranslation    文件:GoogleTranslator.java   
private String tk(String val) throws Exception {
    String script = "function tk(a) {"
            + "var TKK = ((function() {var a = 561666268;var b = 1526272306;return 406398 + '.' + (a + b); })());\n"
            + "function b(a, b) { for (var d = 0; d < b.length - 2; d += 3) { var c = b.charAt(d + 2), c = 'a' <= c ? c.charCodeAt(0) - 87 : Number(c), c = '+' == b.charAt(d + 1) ? a >>> c : a << c; a = '+' == b.charAt(d) ? a + c & 4294967295 : a ^ c } return a }\n"
            + "for (var e = TKK.split('.'), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {"
            + "var c = a.charCodeAt(f);"
            + "128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)"
            + "}"
            + "a = h;"
            + "for (d = 0; d < g.length; d++) a += g[d], a = b(a, '+-a^+6');"
            + "a = b(a, '+-3^+b+-f');"
            + "a ^= Number(e[1]) || 0;"
            + "0 > a && (a = (a & 2147483647) + 2147483648);"
            + "a %= 1E6;"
            + "return a.toString() + '.' + (a ^ h)\n"
            + "}";

    engine.eval(script);
    Invocable inv = (Invocable) engine;
    return (String) inv.invokeFunction("tk", val);
}
项目:saluki    文件:ScriptRouter.java   
@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;
  }
}
项目:slardar    文件:TestMain.java   
public static void main(String[] args) {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine engine = engineManager.getEngineByName("javascript");
        try {
//            UserVO user = new UserVO();
//            user.setId(1000);
//            user.setUsername("xingtianyu");
//            Map<String,Object> usermap = new HashMap<>();
//            usermap.put("id",user.getId());
//            usermap.put("username",user.getUsername());
            JSContext context = new JSContext();
            engine.put(JSContext.CONTEXT,context.getCtx());
            engine.eval(new FileReader("/home/code4j/IDEAWorkspace/myutils/myutils-slardar/src/main/resources/mapper/usermapper.js"));
            Invocable func = (Invocable)engine;
//            Map<String,Object> resultMap = (Map<String, Object>) func.invokeFunction("findUserByCondition",usermap);
//            Map<String,Object> paramMap = (Map<String, Object>) resultMap.get("param");
//            System.out.println(resultMap.get("sql"));
//            System.out.println(paramMap.get("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
项目:openjdk-jdk10    文件:Test8.java   
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");
}
项目:openjdk-jdk10    文件:RunnableImplObject.java   
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();
}
项目:openjdk-jdk10    文件:InvokeScriptMethod.java   
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 !!" );
}
项目:openjdk-jdk10    文件:RunnableImpl.java   
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();
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@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
     final Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Try passing non-interface Class object for interface implementation.
 */
public void getNonInterfaceGetInterfaceTest() {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");
    try {
        log(Objects.toString(((Invocable) engine).getInterface(Object.class)));
        fail("Should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            fail("IllegalArgumentException expected, got " + exp);
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final Object obj = e.eval("({ run: function() { } })");

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

        final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that getInterface on null 'thiz' results in
 * IllegalArgumentException.
 */
public void getInterfaceNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).getInterface(null, Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that calling getInterface on mirror created by another engine
 * results in IllegalArgumentException.
 */
public void getInterfaceMixEnginesTest() {
    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 getInterface
        ((Invocable) engine2).getInterface(obj, Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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());
        }
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@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]");
}
项目:openjdk-jdk10    文件:PluggableJSObjectTest.java   
@Test
public void hidingInternalObjectsForJSObjectTest() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");

    final String code = "function func(obj) { obj.foo = [5, 5]; obj.bar = {} }";
    e.eval(code);

    // call the exposed function but pass user defined JSObject impl as argument
    ((Invocable)e).invokeFunction("func", new AbstractJSObject() {
        @Override
        public void setMember(final String name, final Object value) {
            // make sure that wrapped objects are passed (and not internal impl. objects)
            assertTrue(value.getClass() == ScriptObjectMirror.class);
        }
    });
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void currentGlobalMissingTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");

    final Context ctx = new Context();
    e.put("ctx", ctx);
    e.eval("var obj = { foo: function(str) { return str.toUpperCase() } }");
    e.eval("ctx.set(obj)");
    final Invocable inv = (Invocable)e;
    assertEquals("HELLO", inv.invokeMethod(ctx.get(), "foo", "hello"));
    // try object literal
    e.eval("ctx.set({ bar: function(str) { return str.toLowerCase() } })");
    assertEquals("hello", inv.invokeMethod(ctx.get(), "bar", "HELLO"));
    // try array literal
    e.eval("var arr = [ 'hello', 'world' ]");
    e.eval("ctx.set(arr)");
    assertEquals("helloworld", inv.invokeMethod(ctx.get(), "join", ""));
}
项目:Lucid2.0    文件:ReactorScriptManager.java   
public final void act(final MapleClient c, final MapleReactor reactor) {
    try {
        final Invocable iv = getInvocable("reactor/" + reactor.getReactorId() + ".js", c);

        if (iv == null) {
            return;
        }
        final ScriptEngine scriptengine = (ScriptEngine) iv;
        ReactorActionManager rm = new ReactorActionManager(c, reactor);

        scriptengine.put("rm", rm);
        iv.invokeFunction("act");
    } catch (ScriptException | NoSuchMethodException e) {
        System.err.println("Error executing reactor script. ReactorID: " + reactor.getReactorId() + ", ReactorName: " + reactor.getName() + ":" + e);
    }
}
项目:xdman    文件:XDMAutoProxyHandler.java   
public ProxyInfo[] getProxyInfo(URL paramURL) throws Exception {
    ProxyInfo[] arrayOfProxyInfo = null;
    if (this.engine != null) {
        try {
            this.engine.put("obj", this);
            //System.out.println(this.autoProxyScript.toString());
            this.engine.eval(this.autoProxyScript.toString());
            if ((this.engine instanceof Invocable)) {
                Invocable localInvocable = (Invocable) this.engine;
                Object localObject = localInvocable.invokeFunction(
                        "FindProxyForURL", new Object[] {
                                paramURL.toString(), paramURL.getHost() });
                arrayOfProxyInfo = extractAutoProxySetting((String) localObject);
            }
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
    // if (arrayOfProxyInfo == null) {
    // arrayOfProxyInfo = fallbackGetProxyInfo(paramURL);
    // }
    return arrayOfProxyInfo;
}
项目:manifold    文件:JavascriptTemplate.java   
public static String renderToStringImpl(ScriptEngine engine, JSTNode templateNode, Object... args) {
  try {
    //make argument list including the raw string list
    Object[] argsWithStrings = Arrays.copyOf(args, args.length + 1);

    List rawStrings = templateNode.getChildren(RawStringNode.class)
      .stream()
      .map(node -> node.genCode())
      .collect(Collectors.toList());

    argsWithStrings[argsWithStrings.length - 1] = rawStrings;

    String ret = (String) ((Invocable) engine).invokeFunction("renderToString", argsWithStrings);
    return ret;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:VISNode    文件:ScriptRunner.java   
/**
 * Builds the script invocable
 */
private void buildInvocable() {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    try {
        if (hasScript()) {
            engine.eval(script.getValue());
            inv = (Invocable) engine;
        }
    } catch (ScriptException e) {
        ExceptionHandler.get().handle(e);
    }
}