java类javax.script.ScriptEngineManager的实例源码

CrawlerUtils.java 文件源码 项目:crawler 阅读 18 收藏 0 点赞 0 评论 0
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;
}
ScriptRouter.java 文件源码 项目:EatDubbo 阅读 22 收藏 0 点赞 0 评论 0
public ScriptRouter(URL url) {
    this.url = url;
    String type = url.getParameter(Constants.TYPE_KEY);
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
    if (type == null || type.length() == 0){
        type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
    }
    if (rule == null || rule.length() == 0){
        throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule));
    }
    ScriptEngine engine = engines.get(type);
    if (engine == null){
        engine = new ScriptEngineManager().getEngineByName(type);
        if (engine == null) {
            throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule));
        }
        engines.put(type, engine);
    }
    this.engine = engine;
    this.rule = rule;
}
Test4.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
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();
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
@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());
        }
    }
}
PluggableJSObjectTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
// array-like indexed access for a JSObject
public void indexedAccessTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final BufferObject buf = new BufferObject(2);
        e.put("buf", buf);

        // array-like access on BufferObject objects
        assertEquals(e.eval("buf.length"), buf.getBuffer().capacity());
        e.eval("buf[0] = 23");
        assertEquals(buf.getBuffer().get(0), 23);
        assertEquals(e.eval("buf[0]"), 23);
        assertEquals(e.eval("buf[1]"), 0);
        buf.getBuffer().put(1, 42);
        assertEquals(e.eval("buf[1]"), 42);
        assertEquals(e.eval("Array.isArray(buf)"), Boolean.TRUE);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
CustomFrameTitleBuilder.java 文件源码 项目:custom-title-plugin 阅读 20 收藏 0 点赞 0 评论 0
public CustomFrameTitleBuilder() {
    PropertiesComponent prop = PropertiesComponent.getInstance();

    projectPattern = prop.getValue(Settings.TEMPLATE_PATTERN_PROJECT, DEFAULT_TEMPLATE_PATTERN_PROJECT);
    filePattern = prop.getValue(Settings.TEMPLATE_PATTERN_FILE, DEFAULT_TEMPLATE_PATTERN_FILE);

    engine = new ScriptEngineManager().getEngineByName("nashorn");

    try {
        // evaluate JavaScript Underscore library
        engine.eval(new InputStreamReader(getClass().getResourceAsStream("/underscore-min.js")));

        // create new JavaScript methods references for templates
        engine.eval("var projectTemplate;");
        engine.eval("var fileTemplate;");

        prepareTemplateSettings();
    } catch (Exception e) {
        // we took precaution below
    }

    TitleComponent.addSettingChangeListener(this);
}
RunnableImplObject.java 文件源码 项目:openjdk-jdk10 阅读 15 收藏 0 点赞 0 评论 0
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();
}
ScriptEngineTest.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void functionalInterfaceObjectTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");
    final AtomicBoolean invoked = new AtomicBoolean(false);
    e.put("c", new Consumer<Object>() {
        @Override
        public void accept(final Object t) {
            assertTrue(t instanceof ScriptObjectMirror);
            assertEquals(((ScriptObjectMirror)t).get("a"), "xyz");
            invoked.set(true);
        }
    });
    e.eval("var x = 'xy'; x += 'z';c({a:x})");
    assertTrue(invoked.get());
}
PluggableJSObjectTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
// a factory JSObject
public void factoryJSObjectTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.put("Factory", new Factory());

        // check new on Factory
        assertEquals(e.eval("typeof Factory"), "function");
        assertEquals(e.eval("typeof new Factory()"), "object");
        assertEquals(e.eval("(new Factory()) instanceof java.util.Map"), Boolean.TRUE);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
ScriptEngineTest.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@Test
// check that print prints all arguments (more than one)
public void printManyTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final StringWriter sw = new StringWriter();
    e.getContext().setWriter(sw);
    try {
        e.eval("print(34, true, 'hello')");
    } catch (final Throwable t) {
        t.printStackTrace();
        fail(t.getMessage());
    }

    assertEquals(sw.toString(), println("34 true hello"));
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
@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());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
@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());
        }
    }
}
ScriptObjectMirrorTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void indexPropertiesExternalBufferTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptObjectMirror obj = (ScriptObjectMirror)e.eval("var obj = {}; obj");
    final ByteBuffer buf = ByteBuffer.allocate(5);
    int i;
    for (i = 0; i < 5; i++) {
        buf.put(i, (byte)(i+10));
    }
    obj.setIndexedPropertiesToExternalArrayData(buf);

    for (i = 0; i < 5; i++) {
        assertEquals((byte)(i+10), ((Number)e.eval("obj[" + i + "]")).byteValue());
    }

    e.eval("for (i = 0; i < 5; i++) obj[i] = 0");
    for (i = 0; i < 5; i++) {
        assertEquals((byte)0, ((Number)e.eval("obj[" + i + "]")).byteValue());
        assertEquals((byte)0, buf.get(i));
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@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());
    }
}
ScriptedRegisteredServiceAttributeReleasePolicy.java 文件源码 项目:cas-5.1.0 阅读 26 收藏 0 点赞 0 评论 0
private static Map<String, Object> getAttributesFromInlineGroovyScript(final Map<String, Object> attributes,
                                                                       final Matcher matcherInline) throws ScriptException {
    final String script = matcherInline.group(1).trim();
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
    if (engine == null) {
        LOGGER.warn("Script engine is not available for Groovy");
        return new HashMap<>();
    }
    final Object[] args = {attributes, LOGGER};
    LOGGER.debug("Executing script, with parameters [{}]", args);

    final Bindings binding = new SimpleBindings();
    binding.put("attributes", attributes);
    binding.put("logger", LOGGER);
    return (Map<String, Object>) engine.eval(script, binding);
}
JSExec.java 文件源码 项目:react-native-console 阅读 15 收藏 0 点赞 0 评论 0
/**
 * Exec a string match function with JavaScript regex expression and return the match result.
 * @param str
 * @param regex
 * @return null if no match, otherwise a String[] result value
 */
public static String[] jsMatchExpr(String str, String regex) {
    // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array
    if(engine == null) {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
    }
    try {
        engine.put("str", str);
        String[] value = (String[])engine.eval("Java.to(str.match(" + regex + "),\"java.lang.String[]\" );");
        return value;
    } catch (ScriptException e) {
        e.printStackTrace();
    }
    return null;
}
RNPathUtilTest.java 文件源码 项目:react-native-console 阅读 17 收藏 0 点赞 0 评论 0
@Test
    public void testJS() {
        // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
            engine.put("line", "刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]");
//            engine.put("regex", )
            String regex = "/(.*?) \\((.*?)\\) \\[(.*?)\\]/";
            String[] value = (String[])engine.eval("Java.to(line.match(" + regex + "),\"java.lang.String[]\" );");
            System.out.println(value.length);
            System.out.println(value[1]);
            String[] result = {"刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]",
                    "刘长炯 微信号weblogic", "10.3.2", "46a5432f8fdea99a6186a927e8da5db7a51854ac"};
            Assert.assertArrayEquals("result shold match", result, value);
//            Collection<Object> val = value.values();
//            if(value.isArray()) {
//                System.out.println(value.getMember("1"));
//            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 23 收藏 0 点赞 0 评论 0
@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]");
}
JtSqlEngine.java 文件源码 项目:JtSQL 阅读 17 收藏 0 点赞 0 评论 0
public JtSqlEngine(){
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    jsEngine = scriptEngineManager.getEngineByName("nashorn");

    jtapi = new JTAPI();

    jsEngine.put("JTAPI",jtapi);

    try {
        jsEngine.eval("var jtapi_global={};");
        jsEngine.eval("function require(url){var lib=md5(url);if(!jtapi_global[lib]){var code=http({url:url});jtapi_global[lib]=eval(code)};return jtapi_global[lib]};");

        jsEngine.eval("function guid(){return JTAPI.guid()};");
        jsEngine.eval("function md5(txt){return JTAPI.md5(txt)};");
        jsEngine.eval("function sha1(txt){return JTAPI.sha1(txt)};");

        jsEngine.eval("function set(key,obj){JTAPI.set(key,JSON.stringify(obj))};");
        jsEngine.eval("function get(key){var txt=JTAPI.get(key);if(txt){return JSON.parse(txt)}else{return null}};");

        jsEngine.eval("function log(txt){JTAPI.log(txt)};");
        jsEngine.eval("function http(obj){return JTAPI.http(JSON.stringify(obj))};"); //obj:{url:'xxx', form:{}, header:{}}
        jsEngine.eval("function sql(txt){var _d=JTAPI.sql(txt);if(_d&&typeof(_d)=='object'&&_d.getRow){var item=_d.getRow(0);var keys=item.keys();if(_d.getRowCount()==1){var obj={};for(var i in keys){var k1=keys.get(i);obj[k1]=item.get(k1)};return obj}else{var ary=[];if(item.count()==1){var list=_d.toArray(0);for(var i in list){ary.push(list[i])}}else{var rows=_d.getRows();for(var j in rows){var m1=rows.get(j);var obj={};for(var i in keys){var k1=keys.get(i);obj[k1]=m1.get(k1)};ary.push(obj)}};return ary}}else{return _d}};");
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
ArduinoBuilderRunner.java 文件源码 项目:chipKIT-importer 阅读 16 收藏 0 点赞 0 评论 0
private List<Path> findMainLibraryPaths() throws ScriptException, FileNotFoundException {
    LOGGER.info("Looking for main library paths");

    Path includesCachePath = Paths.get(preprocessDirPath.toAbsolutePath().toString(), "includes.cache");
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
    ScriptObjectMirror mirror = (ScriptObjectMirror) scriptEngine.eval(new FileReader(includesCachePath.toString()));
    List<Path> libraryPaths = new ArrayList<>();
    mirror.entrySet().forEach(e -> {
        if (e.getValue() instanceof ScriptObjectMirror) {
            ScriptObjectMirror m = (ScriptObjectMirror) e.getValue();
            Object sourceFile = m.get("Sourcefile");
            if (sourceFile != null && !sourceFile.toString().trim().isEmpty()) {
                String entry = m.get("Includepath").toString();
                if ( !entry.trim().isEmpty() ) {
                    LOGGER.log( Level.INFO, "Found library path: {0}", entry );
                    libraryPaths.add( Paths.get(entry) );
                }
            }
        }
    });
    return libraryPaths;
}
Scripts.java 文件源码 项目:neoscada 阅读 17 收藏 0 点赞 0 评论 0
/**
 * Create a new script engine manager
 * <p>
 * <em>Note:</em> The context class loader will be set during the creation
 * of the script engine. However the constructor
 * {@link ScriptEngineManager#ScriptEngineManager(ClassLoader)} with the
 * parameter <code>null</code> will still be used in order to look up the
 * default script languages of the JRE.
 * </p>
 *
 * @param contextClassLoader
 *            the context class loader to use
 * @return a new instanceof a {@link ScriptEngineManager}
 */
public static ScriptEngineManager createManager ( final ClassLoader contextClassLoader )
{
    try
    {
        return executeWithClassLoader ( contextClassLoader, new Callable<ScriptEngineManager> () {

            @Override
            public ScriptEngineManager call ()
            {
                return new ScriptEngineManager ( null );
            }
        } );
    }
    catch ( final Exception e )
    {
        // should never happen
        throw new RuntimeException ( e );
    }
}
Test8.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
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");
}
ScriptEngineSecurityTest.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void fakeProxySubclassAccessCheckTest() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    e.put("name", ScriptEngineSecurityTest.class.getName());
    e.put("cl", ScriptEngineSecurityTest.class.getClassLoader());
    e.put("intfs", new Class[] { Runnable.class });

    final String getClass = "Java.type(name + '$FakeProxy').getProxyClass(cl, intfs);";

    // Should not be able to call static methods of Proxy via fake subclass
    try {
        e.eval(getClass);
        fail("should have thrown SecurityException");
    } catch (final Exception exp) {
        if (! (exp instanceof SecurityException)) {
            fail("SecurityException expected, got " + exp);
        }
    }
}
ScriptVisibilityProviderImpl.java 文件源码 项目:neoscada 阅读 36 收藏 0 点赞 0 评论 0
public ScriptVisibilityProviderImpl ( final ScriptEngineManager scriptEngineManager, final ScriptContext scriptContext, String engineName, final String scriptCode )
{
    fireChange ( false );

    if ( engineName == null || engineName.isEmpty () )
    {
        engineName = "JavaScript";
    }

    try
    {
        final ScriptExecutor executor = new ScriptExecutor ( scriptEngineManager, engineName, scriptCode, Activator.class.getClassLoader () );
        fireChange ( makeResult ( executor.execute ( scriptContext ) ) );
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to eval visibility", e );
    }
}
DetailViewImpl.java 文件源码 项目:neoscada 阅读 22 收藏 0 点赞 0 评论 0
private void loadScriptModule ( final ScriptEngineManager engineManager, final ScriptContext scriptContext, final ScriptModule module ) throws Exception
{
    String engineName = module.getScriptLanguage ();

    if ( engineName == null || engineName.isEmpty () )
    {
        engineName = "JavaScript"; //$NON-NLS-1$
    }

    if ( module.getCode () != null && !module.getCode ().isEmpty () )
    {
        new ScriptExecutor ( engineManager, engineName, module.getCode (), Activator.class.getClassLoader () ).execute ( scriptContext );
    }
    if ( module.getCodeUri () != null && !module.getCodeUri ().isEmpty () )
    {
        new ScriptExecutor ( engineManager, engineName, new URL ( module.getCodeUri () ), Activator.class.getClassLoader () ).execute ( scriptContext );
    }
}
ScriptEngineTest.java 文件源码 项目:openjdk-jdk10 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void argumentsWithTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    final String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        final Object arg0 = e.eval("var imports = new JavaImporter(java.io); " +
                " with(imports) { arguments[0] }");
        final Object arg1 = e.eval("var imports = new JavaImporter(java.util, java.io); " +
                " with(imports) { arguments[1] }");
        assertEquals(args[0], arg0);
        assertEquals(args[1], arg1);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
ModbusExporterInterceptorHandler.java 文件源码 项目:neoscada 阅读 16 收藏 0 点赞 0 评论 0
@Override
protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties )
{
    final ModbusExporterInterceptor interceptor = (ModbusExporterInterceptor)interceptorElement;

    final Script script = interceptor.getScript ();

    final ScriptEngineManager manager = new ScriptEngineManager ();
    try
    {
        final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null );
        final ScriptContext context = new SimpleScriptContext ();
        final ModbusProcessor modbus = new ModbusProcessor ( this, interceptor, masterContext, item );
        context.setAttribute ( "MODBUS", modbus, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE );
        executor.execute ( context );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( "Failed to process script", e );
    }
    return true;
}
ScriptRouter.java 文件源码 项目:dubbo2 阅读 21 收藏 0 点赞 0 评论 0
public ScriptRouter(URL url) {
    this.url = url;
    String type = url.getParameter(Constants.TYPE_KEY);
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
    if (type == null || type.length() == 0){
        type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
    }
    if (rule == null || rule.length() == 0){
        throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule));
    }
    ScriptEngine engine = engines.get(type);
    if (engine == null){
        engine = new ScriptEngineManager().getEngineByName(type);
        if (engine == null) {
            throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule));
        }
        engines.put(type, engine);
    }
    this.engine = engine;
    this.rule = rule;
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 41 收藏 0 点赞 0 评论 0
@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);
        }
    }
}
MultiScopes.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}


问题


面经


文章

微信
公众号

扫码关注公众号