当前位置: 首页>>代码示例>>Java>>正文


Java Invocable类代码示例

本文整理汇总了Java中javax.script.Invocable的典型用法代码示例。如果您正苦于以下问题:Java Invocable类的具体用法?Java Invocable怎么用?Java Invocable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Invocable类属于javax.script包,在下文中一共展示了Invocable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: executeJs

import javax.script.Invocable; //导入依赖的package包/类
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;
}
 
开发者ID:xbynet,项目名称:crawler,代码行数:18,代码来源:CrawlerUtils.java

示例2: main

import javax.script.Invocable; //导入依赖的package包/类
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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:Test4.java

示例3: main

import javax.script.Invocable; //导入依赖的package包/类
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!!" );
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:InvokeScriptFunction.java

示例4: invokeFunctionWithCustomScriptContextTest

import javax.script.Invocable; //导入依赖的package包/类
@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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:ScopeTest.java

示例5: invokeMethodMixEnginesTest

import javax.script.Invocable; //导入依赖的package包/类
@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());
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:InvocableTest.java

示例6: unwrapJavaObject

import javax.script.Invocable; //导入依赖的package包/类
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;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:18,代码来源:OQLEngineImpl.java

示例7: init

import javax.script.Invocable; //导入依赖的package包/类
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);
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:17,代码来源:OQLEngineImpl.java

示例8: initializeController

import javax.script.Invocable; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:kefik,项目名称:Pogamut3,代码行数:25,代码来源:StreamScriptLogic.java

示例9: getScriptedAttributesFromFile

import javax.script.Invocable; //导入依赖的package包/类
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<>();
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:25,代码来源:ScriptedRegisteredServiceAttributeReleasePolicy.java

示例10: createScriptEngine

import javax.script.Invocable; //导入依赖的package包/类
@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;
}
 
开发者ID:softelnet,项目名称:sponge,代码行数:22,代码来源:NashornKnowledgeBaseInterpreter.java

示例11: createScriptEngine

import javax.script.Invocable; //导入依赖的package包/类
@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;
}
 
开发者ID:softelnet,项目名称:sponge,代码行数:20,代码来源:ScriptKotlinKnowledgeBaseInterpreter.java

示例12: tk

import javax.script.Invocable; //导入依赖的package包/类
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);
}
 
开发者ID:a483210,项目名称:GoogleTranslation,代码行数:22,代码来源:GoogleTranslator.java

示例13: match

import javax.script.Invocable; //导入依赖的package包/类
@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;
  }
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:19,代码来源:ScriptRouter.java

示例14: main

import javax.script.Invocable; //导入依赖的package包/类
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();
        }

    }
 
开发者ID:rpgmakervx,项目名称:slardar,代码行数:24,代码来源:TestMain.java

示例15: hash

import javax.script.Invocable; //导入依赖的package包/类
/**
 * 计算一些接口的hash值</p>
 * Function: hash</p>
 * <p>Description:</p>
 *
 * @param uin
 * @param ptwebqq
 * @return
 * @author [email protected]
 * @date 2016年12月21日 下午6:25:04
 * @version 1.0
 */
public static String hash(String uin, String ptwebqq) {

    try {
        String jsSources = IOUtils.toString(SourceLoader.getResourceAsInputStream("hash.js"), "utf-8");
        ScriptEngineManager scriptEMgr = new ScriptEngineManager();
        ScriptEngine engine = scriptEMgr.getEngineByMimeType("application/javascript");
        engine.eval(jsSources);
        Invocable invocable = (Invocable) engine;
        // 调用js
        return (String) invocable.invokeFunction("hash", uin, ptwebqq);
    } catch (Exception e) {
        logger.error("计算hash值异常", e);
    }

    return null;
}
 
开发者ID:thankjava,项目名称:smartqq-agreement-core,代码行数:29,代码来源:WqqEncryptor.java


注:本文中的javax.script.Invocable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。