Search in sources :

Example 61 with ScriptEngine

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

the class SlingScriptAdapterFactory method getAdapter.

// ---------- AdapterFactory -----------------------------------------------
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
    Resource resource = (Resource) adaptable;
    String path = resource.getPath();
    String ext = path.substring(path.lastIndexOf('.') + 1);
    ScriptEngine engine = scriptEngineManager.getEngineByExtension(ext);
    if (engine != null) {
        final Collection<BindingsValuesProvider> bindingsValuesProviders = bindingsValuesProviderTracker.getBindingsValuesProviders(engine.getFactory(), BINDINGS_CONTEXT);
        // unchecked cast
        return (AdapterType) new DefaultSlingScript(this.bundleContext, resource, engine, bindingsValuesProviders, this.serviceCache, scriptCache);
    }
    return null;
}
Also used : BindingsValuesProvider(org.apache.sling.scripting.api.BindingsValuesProvider) Resource(org.apache.sling.api.resource.Resource) ScriptEngine(javax.script.ScriptEngine)

Example 62 with ScriptEngine

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

the class SlingScriptAdapterFactory method getMimeType.

// ---------- MimeTypeProvider
/**
     * Returns the first MIME type entry of the supported MIME types of a
     * ScriptEngineFactory which is registered for the extension of the given
     * name. If no ScriptEngineFactory is registered for the given extension or
     * the registered ScriptEngineFactory is not registered for a MIME type,
     * this method returns <code>null</code>.
     *
     * @param name The name whose extension is to be mapped to a MIME type. The
     *            extension is the string after the last dot in the name. If the
     *            name contains no dot, the entire name is considered the
     *            extension.
     */
@Override
public String getMimeType(String name) {
    name = name.substring(name.lastIndexOf('.') + 1);
    ScriptEngine se = scriptEngineManager.getEngineByExtension(name);
    if (se != null) {
        List<?> mimeTypes = se.getFactory().getMimeTypes();
        if (mimeTypes != null && mimeTypes.size() > 0) {
            return String.valueOf(mimeTypes.get(0));
        }
    }
    return null;
}
Also used : ScriptEngine(javax.script.ScriptEngine)

Example 63 with ScriptEngine

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

the class RhinoJavaScriptEngineTest method testPreserveScopeBetweenEvals.

public void testPreserveScopeBetweenEvals() throws ScriptException {
    MockRhinoJavaScriptEngineFactory factory = new MockRhinoJavaScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine();
    Bindings context = new SimpleBindings();
    engine.eval("var f = 1", context);
    Object result = null;
    try {
        result = engine.eval("f += 1", context);
    } catch (ScriptException e) {
        TestCase.fail(e.getMessage());
    }
    assertTrue(result instanceof Double);
    assertEquals(2.0, result);
}
Also used : ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Example 64 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 65 with ScriptEngine

use of javax.script.ScriptEngine in project java8-tutorial by winterbe.

the class Nashorn2 method main.

public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval(new FileReader("res/nashorn2.js"));
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) FileReader(java.io.FileReader) ScriptEngine(javax.script.ScriptEngine)

Aggregations

ScriptEngine (javax.script.ScriptEngine)147 ScriptEngineManager (javax.script.ScriptEngineManager)49 ScriptException (javax.script.ScriptException)38 Test (org.junit.Test)26 IOException (java.io.IOException)16 Bindings (javax.script.Bindings)15 Map (java.util.Map)13 Invocable (javax.script.Invocable)12 FileReader (java.io.FileReader)9 HashMap (java.util.HashMap)9 ScriptContext (javax.script.ScriptContext)9 ScriptEngineFactory (javax.script.ScriptEngineFactory)9 GroovyTest (org.enumerable.lambda.support.groovy.GroovyTest)9 ScalaTest (org.enumerable.lambda.support.scala.ScalaTest)9 SimpleBindings (javax.script.SimpleBindings)7 JavaScriptTest (org.enumerable.lambda.support.javascript.JavaScriptTest)7 JRubyTest (org.enumerable.lambda.support.jruby.JRubyTest)7 File (java.io.File)6 InputStreamReader (java.io.InputStreamReader)6 ClojureTest (org.enumerable.lambda.support.clojure.ClojureTest)6