Search in sources :

Example 66 with ScriptEngine

use of javax.script.ScriptEngine in project sling by apache.

the class SightlyCompiledScriptTest method testEvalSlingBindings.

/**
     * Tests that SlingBindings are correctly handled by compiled scripts, by setting them from the script context to the request
     * attributes.
     * @throws ScriptException
     */
@Test
public void testEvalSlingBindings() throws ScriptException {
    ScriptEngine scriptEngine = mock(ScriptEngine.class);
    final RenderUnit renderUnit = mock(RenderUnit.class);
    Whitebox.setInternalState(renderUnit, "subTemplates", new HashMap<String, Object>());
    final BundleContext bundleContext = MockOsgi.newBundleContext();
    bundleContext.registerService(ExtensionRegistryService.class.getName(), mock(ExtensionRegistryService.class), new Hashtable<String, Object>());
    ResourceResolver resourceResolver = MockSling.newResourceResolver(bundleContext);
    final MockSlingHttpServletRequest request = spy(new MockSlingHttpServletRequest(resourceResolver, bundleContext));
    SightlyCompiledScript compiledScript = spy(new SightlyCompiledScript(scriptEngine, renderUnit));
    ScriptContext scriptContext = mock(ScriptContext.class);
    StringWriter writer = new StringWriter();
    when(scriptContext.getWriter()).thenReturn(writer);
    Bindings scriptContextBindings = new SimpleBindings() {

        {
            put("test", "testValue");
            put(SlingBindings.REQUEST, request);
            put(SlingBindings.SLING, MockSling.newSlingScriptHelper(bundleContext));
        }
    };
    SlingBindings oldBindings = new SlingBindings();
    oldBindings.put("old", "oldValue");
    request.setAttribute(SlingBindings.class.getName(), oldBindings);
    when(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE)).thenReturn(scriptContextBindings);
    compiledScript.eval(scriptContext);
    ArgumentCaptor<SlingBindings> slingBindingsArgumentCaptor = ArgumentCaptor.forClass(SlingBindings.class);
    ArgumentCaptor<String> attributeNameArgumentCaptor = ArgumentCaptor.forClass(String.class);
    // request.setAttribute should have been invoked 3 times: once here, twice in the compiled script
    verify(request, times(3)).setAttribute(attributeNameArgumentCaptor.capture(), slingBindingsArgumentCaptor.capture());
    List<SlingBindings> slingBindingsValues = slingBindingsArgumentCaptor.getAllValues();
    int invocation = 1;
    for (SlingBindings bindings : slingBindingsValues) {
        switch(invocation) {
            case 1:
                assertEquals(oldBindings, bindings);
                break;
            case 2:
                assertEquals(3, bindings.size());
                for (Map.Entry<String, Object> entry : scriptContextBindings.entrySet()) {
                    assertEquals(entry.getValue(), bindings.get(entry.getKey()));
                }
                break;
            case 3:
                assertEquals(oldBindings, bindings);
        }
        invocation++;
    }
    for (String key : attributeNameArgumentCaptor.getAllValues()) {
        assertEquals(SlingBindings.class.getName(), key);
    }
}
Also used : SlingBindings(org.apache.sling.api.scripting.SlingBindings) RenderUnit(org.apache.sling.scripting.sightly.java.compiler.RenderUnit) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) StringWriter(java.io.StringWriter) MockSlingHttpServletRequest(org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest) SimpleBindings(javax.script.SimpleBindings) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) HashMap(java.util.HashMap) Map(java.util.Map) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 67 with ScriptEngine

use of javax.script.ScriptEngine in project spring-framework by spring-projects.

the class ScriptTemplateView method createEngineFromName.

protected ScriptEngine createEngineFromName() {
    if (this.scriptEngineManager == null) {
        this.scriptEngineManager = new ScriptEngineManager(getApplicationContext().getClassLoader());
    }
    ScriptEngine engine = StandardScriptUtils.retrieveEngineByName(this.scriptEngineManager, this.engineName);
    loadScripts(engine);
    return engine;
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 68 with ScriptEngine

use of javax.script.ScriptEngine in project spring-framework by spring-projects.

the class ScriptTemplateViewTests method customEngineAndRenderFunction.

@Test
public void customEngineAndRenderFunction() throws Exception {
    ScriptEngine engine = mock(InvocableScriptEngine.class);
    given(engine.get("key")).willReturn("value");
    this.view.setEngine(engine);
    this.view.setRenderFunction("render");
    this.view.setApplicationContext(this.context);
    engine = this.view.getEngine();
    assertNotNull(engine);
    assertEquals("value", engine.get("key"));
    DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
    assertNull(accessor.getPropertyValue("renderObject"));
    assertEquals("render", accessor.getPropertyValue("renderFunction"));
    assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("defaultCharset"));
}
Also used : DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ScriptEngine(javax.script.ScriptEngine) Test(org.junit.Test)

Example 69 with ScriptEngine

use of javax.script.ScriptEngine in project JMRI by JMRI.

the class JmriScriptEngineManager method getEngine.

/**
     * Get a ScriptEngine by it's name.
     *
     * @param engineName the complete name for the ScriptEngine
     * @return a ScriptEngine or null
     */
public ScriptEngine getEngine(String engineName) {
    if (!this.engines.containsKey(engineName)) {
        if (PYTHON.equals(engineName)) {
            // Setup the default python engine to use the JMRI python properties
            this.initializePython();
        } else {
            log.debug("Create engine for {}", engineName);
            ScriptEngine engine = this.factories.get(engineName).getScriptEngine();
            engine.setContext(this.context);
            this.engines.put(engineName, engine);
        }
    }
    return this.engines.get(engineName);
}
Also used : ScriptEngine(javax.script.ScriptEngine)

Example 70 with ScriptEngine

use of javax.script.ScriptEngine in project JMRI by JMRI.

the class JmriScriptEngineManager method initializePython.

/**
     * The Python ScriptEngine can be configured using a custom
     * python.properties file and will run jmri_defaults.py if found in the
     * user's configuration profile or settings directory. See python.properties
     * in the JMRI installation directory for details of how to configure the
     * Python ScriptEngine.
     */
public void initializePython() {
    if (!this.engines.containsKey(PYTHON)) {
        // Get properties for interpreter
        // Search in user files, the settings directory, and in the program path
        InputStream is = FileUtil.findInputStream("python.properties", new String[] { FileUtil.getUserFilesPath(), FileUtil.getPreferencesPath(), FileUtil.getProgramPath() });
        boolean execJython = false;
        if (is != null) {
            Properties properties;
            try {
                properties = new Properties(System.getProperties());
                // NOI18N
                properties.setProperty("python.console.encoding", "UTF-8");
                // NOI18N
                properties.setProperty("python.cachedir", FileUtil.getAbsoluteFilename(properties.getProperty("python.cachedir", "settings:jython/cache")));
                properties.load(is);
                String path = properties.getProperty("python.path", "");
                if (path.length() != 0) {
                    path = path.concat(File.pathSeparator);
                }
                properties.setProperty("python.path", path.concat(FileUtil.getScriptsPath().concat(File.pathSeparator).concat(FileUtil.getAbsoluteFilename("program:jython"))));
                execJython = Boolean.valueOf(properties.getProperty("jython.exec", Boolean.toString(false)));
            } catch (IOException ex) {
                log.error("Found, but unable to read python.properties: {}", ex.getMessage());
                properties = null;
            }
            PySystemState.initialize(null, properties);
            log.debug("Jython path is {}", PySystemState.getBaseProperties().getProperty("python.path"));
        }
        // Create the interpreter
        try {
            log.debug("create interpreter");
            ScriptEngine python = this.manager.getEngineByName(PYTHON);
            python.setContext(this.context);
            is = FileUtil.findInputStream(JYTHON_DEFAULTS, new String[] { FileUtil.getUserFilesPath(), FileUtil.getPreferencesPath() });
            if (execJython) {
                this.jython = new PythonInterpreter();
            }
            if (is != null) {
                python.eval(new InputStreamReader(is));
                if (this.jython != null) {
                    this.jython.execfile(is);
                }
            }
            this.engines.put(PYTHON, python);
        } catch (ScriptException e) {
            log.error("Exception creating jython system objects", e);
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) PythonInterpreter(org.python.util.PythonInterpreter) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Properties(java.util.Properties) ScriptEngine(javax.script.ScriptEngine)

Aggregations

ScriptEngine (javax.script.ScriptEngine)175 ScriptEngineManager (javax.script.ScriptEngineManager)70 ScriptException (javax.script.ScriptException)46 Test (org.junit.Test)29 Bindings (javax.script.Bindings)20 IOException (java.io.IOException)19 Map (java.util.Map)14 Invocable (javax.script.Invocable)13 File (java.io.File)11 FileReader (java.io.FileReader)11 ScriptEngineFactory (javax.script.ScriptEngineFactory)11 HashMap (java.util.HashMap)10 ScriptContext (javax.script.ScriptContext)10 SimpleBindings (javax.script.SimpleBindings)10 InputStreamReader (java.io.InputStreamReader)9 GroovyTest (org.enumerable.lambda.support.groovy.GroovyTest)9 ScalaTest (org.enumerable.lambda.support.scala.ScalaTest)9 PrintWriter (java.io.PrintWriter)7 JavaScriptTest (org.enumerable.lambda.support.javascript.JavaScriptTest)7 JRubyTest (org.enumerable.lambda.support.jruby.JRubyTest)7