Package javax.script

Examples of javax.script.ScriptEngine


    private Invocable invokable_;
   
    private CalloutManager()
    {
        ScriptEngineManager scriptManager = new ScriptEngineManager();
        ScriptEngine groovyEngine = scriptManager.getEngineByName("groovy");
        compiler_ = (Compilable)groovyEngine;
        invokable_ = (Invocable)groovyEngine;
    }
View Full Code Here


public class GremlinGroovyScriptEngineTest extends AbstractGremlinTest {

    @Test
    @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
    public void shouldDoSomeGremlin() throws Exception {
        final ScriptEngine engine = new GremlinGroovyScriptEngine();
        final List list = new ArrayList();
        engine.put("g", g);
        engine.put("list", list);
        assertEquals(list.size(), 0);
        engine.eval("g.v(1).out().fill(list)");
        assertEquals(list.size(), 3);
    }
View Full Code Here

    }

    @Test
    @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
    public void shouldLoadImports() throws Exception {
        final ScriptEngine engineNoImports = new GremlinGroovyScriptEngine(new NoImportCustomizerProvider());
        try {
            engineNoImports.eval("Vertex.class.getName()");
            fail("Should have thrown an exception because no imports were supplied");
        } catch (Exception se) {
            assertTrue(se instanceof ScriptException);
        }

        final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine(new DefaultImportCustomizerProvider());
        engineWithImports.put("g", g);
        assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()"));
        assertEquals(2l, engineWithImports.eval("g.V().has('age',Compare.gt,30).count().next()"));
        assertEquals(Direction.IN, engineWithImports.eval("Direction.IN"));
        assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT"));
        assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH"));
    }
View Full Code Here

    }

    @Test
    @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
    public void shouldProperlyHandleBindings() throws Exception {
        final ScriptEngine engine = new GremlinGroovyScriptEngine();
        engine.put("g", g);
        Assert.assertEquals(g.v(1), engine.eval("g.v(1)"));

        final Bindings bindings = engine.createBindings();
        bindings.put("g", g);
        bindings.put("s", "marko");
        bindings.put("f", 0.5f);
        bindings.put("i", 1);
        bindings.put("b", true);
        bindings.put("l", 100l);
        bindings.put("d", 1.55555d);

        Assert.assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.e(7));
        Assert.assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.v(1));
        Assert.assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.v(1));
        Assert.assertEquals(engine.eval("g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.v(1));
        Assert.assertEquals(engine.eval("g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.v(1));
        Assert.assertEquals(engine.eval("g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.v(1));
    }
View Full Code Here

        try {
            if (scriptEngines.containsKey(language))
                scriptEngines.remove(language);

            final ScriptEngine scriptEngine = createScriptEngine(language, imports, staticImports, config)
                    .orElseThrow(() -> new IllegalArgumentException("Language [%s] not supported"));
            scriptEngines.put(language, scriptEngine);

            logger.info("Loaded {} ScriptEngine", language);
        } finally {
View Full Code Here

    }

    @Test
    @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
    public void shouldBeThreadSafe() throws Exception {
        final ScriptEngine engine = new GremlinGroovyScriptEngine();

        int runs = 500;
        final CountDownLatch latch = new CountDownLatch(runs);
        final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias");
        final Random random = new Random();

        for (int i = 0; i < runs; i++) {
            new Thread() {
                public void run() {
                    String name = names.get(random.nextInt(names.size() - 1));
                    try {
                        final Bindings bindings = engine.createBindings();
                        bindings.put("g", g);
                        bindings.put("name", name);
                        final Object result = engine.eval("t = g.V().has('name',name); if(t.hasNext()) { t } else { null }", bindings);
                        if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias"))
                            assertNull(result);
                        else
                            assertNotNull(result);
                    } catch (ScriptException e) {
View Full Code Here

        }
    }

    @Test
    public void shouldProcessScriptWithUTF8Characters() throws Exception {
        final ScriptEngine engine = new GremlinGroovyScriptEngine();
        assertEquals("轉注", engine.eval("'轉注'"));
    }
View Full Code Here

    @FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
    public void shouldProcessUTF8Query() throws Exception {
        final Vertex nonUtf8 = g.addVertex(T.id, "1", "name", "marko", "age", 29);
        final Vertex utf8Name = g.addVertex(T.id, "2", "name", "轉注", "age", 32);

        final ScriptEngine engine = new GremlinGroovyScriptEngine();

        engine.put("g", g);
        Traversal eval = (Traversal) engine.eval("g.V().has('name', 'marko')");
        assertEquals(nonUtf8, eval.next());
        eval = (Traversal) engine.eval("g.V().has('name','轉注')");
        assertEquals(utf8Name, eval.next());
    }
View Full Code Here

    public void testScripts() throws Exception {
        Stream.of(
            new File(getClass().getResource("/org/jooq/example/test").toURI()).listFiles((dir, name) -> name.endsWith(".js"))
        ).forEach(file -> {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("nashorn");

            Bindings bindings = engine.getBindings(ENGINE_SCOPE);
            bindings.put("connection", connection);

            try {
                engine.eval(new FileReader(file));
            }
            catch (Exception e) {
                throw new RuntimeException("Error while running " + file, e);
            }
        });
View Full Code Here

                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            }

                            // Don't pollute the engine namespace with the listener functions
                            ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(language);
                            scriptEngine.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);

                            // Create an invocation handler for this listener
                            AttributeInvocationHandler handler =
                                new AttributeInvocationHandler(scriptEngine,
                                    attribute.localName.substring(attribute.localName.lastIndexOf(".") + 1),
                                    attribute.value);

                            Object listener = Proxy.newProxyInstance(ThreadUtilities.getClassLoader(),
                                new Class<?>[]{propertyClass}, handler);

                            // Add the listener
                            Class<?> listenerListClass = listenerList.getClass();
                            Method addMethod;
                            try {
                                addMethod = listenerListClass.getMethod("add", Object.class);
                            } catch (NoSuchMethodException exception) {
                                throw new RuntimeException(exception);
                            }

                            try {
                                addMethod.invoke(listenerList, listener);
                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            } catch (InvocationTargetException exception) {
                                throw new SerializationException(exception);
                            }
                        } else {
                            // The attribute reprsents a static setter
                            Object value = resolve(attribute.value);

                            Class<?> objectType = element.value.getClass();

                            String propertyName = attribute.localName.substring(attribute.localName.lastIndexOf(".") + 1);
                            propertyName = Character.toUpperCase(propertyName.charAt(0)) +
                            propertyName.substring(1);

                            Method setterMethod = null;
                            if (value != null) {
                                setterMethod = getStaticSetterMethod(propertyClass, propertyName,
                                    objectType, value.getClass());
                            }

                            if (setterMethod == null) {
                                Method getterMethod = getStaticGetterMethod(propertyClass, propertyName, objectType);

                                if (getterMethod != null) {
                                    Class<?> propertyType = getterMethod.getReturnType();
                                    setterMethod = getStaticSetterMethod(propertyClass, propertyName,
                                        objectType, propertyType);

                                    if (value instanceof String) {
                                        value = BeanDictionary.coerce((String)value, propertyType);
                                    }
                                }
                            }

                            if (setterMethod == null) {
                                throw new SerializationException(attribute.localName + " is not valid static property.");
                            }

                            // Invoke the setter
                            try {
                                setterMethod.invoke(null, element.value, value);
                            } catch (Exception exception) {
                                throw new SerializationException(exception);
                            }
                        }
                    }
                }

                // If the parent element is a writable property, set this as its
                // value; it will be applied later in the parent's closing tag
                if (element.parent != null
                    && element.parent.type == Element.Type.WRITABLE_PROPERTY) {
                    element.parent.value = element.value;
                }

                break;
            }

            case READ_ONLY_PROPERTY: {
                if (element.value instanceof Dictionary<?, ?>) {
                    // Process attributes looking for instance property setters
                    for (Attribute attribute : element.attributes) {
                        if (Character.isUpperCase(attribute.localName.charAt(0))) {
                            throw new SerializationException("Static setters are not supported"
                                + " for read-only properties.");
                        }

                        Dictionary<String, Object> dictionary =
                            (Dictionary<String, Object>)element.value;
                        dictionary.put(attribute.localName, resolve(attribute.value));
                    }
                }

                break;
            }

            case WRITABLE_PROPERTY: {
                BeanDictionary beanDictionary = new BeanDictionary(element.parent.value);
                beanDictionary.put(localName, element.value);
                break;
            }

            case SCRIPT: {
                // Process attributes looking for src and language
                String src = null;
                String language = this.language;
                for (Attribute attribute : element.attributes) {
                    if (attribute.localName.equals(SCRIPT_SRC_ATTRIBUTE)) {
                        src = attribute.value;
                    } else if (attribute.localName.equals(SCRIPT_LANGUAGE_ATTRIBUTE)) {
                        language = attribute.value;
                    } else {
                        throw new SerializationException(attribute.localName + " is not a valid"
                            + " attribute for the " + WTKX_PREFIX + ":" + SCRIPT_TAG + " tag.");
                    }
                }

                Bindings bindings;
                if (element.parent.value instanceof ListenerList<?>) {
                    // Don't pollute the engine namespace with the listener functions
                    bindings = new SimpleBindings();
                } else {
                    bindings = scriptEngineManager.getBindings();
                }

                // Execute script
                final ScriptEngine scriptEngine;

                if (src != null) {
                    // The script is located in an external file
                    int i = src.lastIndexOf(".");
                    if (i == -1) {
                        throw new SerializationException("Cannot determine type of script \""
                            + src + "\".");
                    }

                    String extension = src.substring(i + 1);
                    scriptEngine = scriptEngineManager.getEngineByExtension(extension);

                    if (scriptEngine == null) {
                        throw new SerializationException("Unable to find scripting engine for"
                            + " extension " + extension + ".");
                    }

                    scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

                    try {
                        URL scriptLocation;
                        if (src.charAt(0) == '/') {
                            ClassLoader classLoader = ThreadUtilities.getClassLoader();
                            scriptLocation = classLoader.getResource(src);
                        } else {
                            scriptLocation = new URL(location, src);
                        }

                        BufferedReader scriptReader = null;
                        try {
                            scriptReader = new BufferedReader(new InputStreamReader(scriptLocation.openStream()));
                            scriptEngine.eval(scriptReader);
                        } catch(ScriptException exception) {
                            exception.printStackTrace();
                        } finally {
                            if (scriptReader != null) {
                                scriptReader.close();
                            }
                        }
                    } catch (IOException exception) {
                        throw new SerializationException(exception);
                    }
                } else {
                    // The script is inline
                    scriptEngine = scriptEngineManager.getEngineByName(language);

                    if (scriptEngine == null) {
                        throw new SerializationException("Unable to find scripting engine for"
                            + " language \"" + language + "\".");
                    }

                    scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

                    String script = (String)element.value;
                    if (script != null) {
                        try {
                            scriptEngine.eval(script);
                        } catch (ScriptException exception) {
                            System.err.println(exception);
                            System.err.println(script);
                        }
                    }
View Full Code Here

TOP

Related Classes of javax.script.ScriptEngine

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.