Search in sources :

Example 11 with CompiledScript

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

the class RenderUnitProvider method provide.

@Override
public ProviderOutcome provide(String identifier, RenderContext renderContext, Bindings arguments) {
    if (identifier.endsWith("." + SightlyScriptEngineFactory.EXTENSION)) {
        Bindings globalBindings = renderContext.getBindings();
        SlingScriptHelper sling = BindingsUtils.getHelper(globalBindings);
        SlingHttpServletRequest request = BindingsUtils.getRequest(globalBindings);
        final Resource renderUnitResource = ScriptUtils.resolveScript(scriptingResourceResolverProvider.getRequestScopedResourceResolver(), renderContext, identifier);
        if (renderUnitResource == null) {
            Resource caller = ResourceResolution.getResourceForRequest(request.getResourceResolver(), request);
            if (caller != null) {
                String resourceSuperType = caller.getResourceSuperType();
                StringBuilder errorMessage = new StringBuilder("Cannot find resource ");
                errorMessage.append(identifier).append(" for base path ").append(caller.getPath());
                if (StringUtils.isNotEmpty(resourceSuperType)) {
                    errorMessage.append(" with resource super type ").append(resourceSuperType);
                }
                errorMessage.append(".");
                return ProviderOutcome.failure(new SightlyException(errorMessage.toString()));
            } else {
                return ProviderOutcome.failure(new SightlyException("Cannot resolve template " + identifier + " for script " + sling.getScript().getScriptResource().getPath()));
            }
        }
        RenderUnit renderUnit;
        try {
            CachedScript cachedScript = scriptCache.getScript(renderUnitResource.getPath());
            final SightlyCompiledScript compiledScript;
            if (cachedScript != null) {
                compiledScript = (SightlyCompiledScript) cachedScript.getCompiledScript();
            } else {
                SightlyScriptEngine sightlyScriptEngine = (SightlyScriptEngine) scriptEngineManager.getEngineByName(SightlyScriptEngineFactory.SHORT_NAME);
                String encoding = renderUnitResource.getResourceMetadata().getCharacterEncoding();
                if (StringUtils.isEmpty(encoding)) {
                    encoding = "UTF-8";
                }
                InputStream inputStream = renderUnitResource.adaptTo(InputStream.class);
                if (inputStream == null) {
                    return ProviderOutcome.failure();
                }
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
                ScriptNameAwareReader reader = new ScriptNameAwareReader(inputStreamReader, renderUnitResource.getPath());
                compiledScript = (SightlyCompiledScript) sightlyScriptEngine.compile(reader);
                scriptCache.putScript(new CachedScript() {

                    @Override
                    public String getScriptPath() {
                        return renderUnitResource.getPath();
                    }

                    @Override
                    public CompiledScript getCompiledScript() {
                        return compiledScript;
                    }
                });
            }
            renderUnit = compiledScript.getRenderUnit();
            return ProviderOutcome.success(renderUnit);
        } catch (Exception e) {
            return ProviderOutcome.failure(e);
        }
    }
    return ProviderOutcome.failure();
}
Also used : SightlyCompiledScript(org.apache.sling.scripting.sightly.impl.engine.SightlyCompiledScript) CompiledScript(javax.script.CompiledScript) RenderUnit(org.apache.sling.scripting.sightly.java.compiler.RenderUnit) InputStreamReader(java.io.InputStreamReader) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) InputStream(java.io.InputStream) CachedScript(org.apache.sling.scripting.api.CachedScript) Resource(org.apache.sling.api.resource.Resource) SightlyScriptEngine(org.apache.sling.scripting.sightly.impl.engine.SightlyScriptEngine) Bindings(javax.script.Bindings) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) SightlyException(org.apache.sling.scripting.sightly.SightlyException) ScriptNameAwareReader(org.apache.sling.scripting.core.ScriptNameAwareReader) SightlyException(org.apache.sling.scripting.sightly.SightlyException) SightlyCompiledScript(org.apache.sling.scripting.sightly.impl.engine.SightlyCompiledScript)

Example 12 with CompiledScript

use of javax.script.CompiledScript in project openhab1-addons by openhab.

the class EBusConfigurationProvider method transformDataTypes.

/**
     * @param configurationEntry
     */
protected void transformDataTypes(TelegramConfiguration configurationEntry) {
    // Use filter property if set
    if (StringUtils.isNotEmpty(configurationEntry.getFilter())) {
        String filter = configurationEntry.getFilter();
        filter = P_PLACEHOLDER.matcher(filter).replaceAll("[0-9A-Z]{2}");
        logger.trace("Compile RegEx filter: {}", filter);
        configurationEntry.setFilterPattern(Pattern.compile(filter));
    } else {
        // Build filter string
        // Always ignore first two hex bytes
        String filter = "[0-9A-Z]{2} [0-9A-Z]{2}";
        // Add command to filter string
        if (StringUtils.isNotEmpty(configurationEntry.getCommand())) {
            filter += " " + configurationEntry.getCommand();
            filter += " [0-9A-Z]{2}";
        }
        // Add data to filter string
        if (StringUtils.isNotEmpty(configurationEntry.getData())) {
            Matcher matcher = P_BRACKETS_VALS.matcher(configurationEntry.getData());
            filter += " " + matcher.replaceAll("[0-9A-Z]{2}");
        }
        // Finally add .* to end with everything
        filter += " .*";
        logger.trace("Compile RegEx filter: {}", filter);
        configurationEntry.setFilterPattern(Pattern.compile(filter));
    }
    // remove brackets if used
    if (StringUtils.isNotEmpty(configurationEntry.getData())) {
        Matcher matcher = P_BRACKETS_CLEAN.matcher(configurationEntry.getData());
        configurationEntry.setData(matcher.replaceAll(""));
    }
    // compile scipt's if available also once
    if (configurationEntry.getValues() != null && !configurationEntry.getValues().isEmpty()) {
        Map<String, TelegramValue> values = configurationEntry.getValues();
        for (Entry<String, TelegramValue> entry : values.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue().getScript())) {
                String script = entry.getValue().getScript();
                // check if engine is available
                if (StringUtils.isNotEmpty(script) && compEngine != null) {
                    try {
                        CompiledScript compile = compEngine.compile(script);
                        entry.getValue().setCsript(compile);
                    } catch (ScriptException e) {
                        logger.error("Error while compiling JavaScript!", e);
                    }
                }
            }
        }
    }
    // compile scipt's if available
    if (configurationEntry.getComputedValues() != null && !configurationEntry.getComputedValues().isEmpty()) {
        Map<String, TelegramValue> cvalues = configurationEntry.getComputedValues();
        for (Entry<String, TelegramValue> entry : cvalues.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue().getScript())) {
                String script = entry.getValue().getScript();
                // check if engine is available
                if (StringUtils.isNotEmpty(script) && compEngine != null) {
                    try {
                        CompiledScript compile = compEngine.compile(script);
                        entry.getValue().setCsript(compile);
                    } catch (ScriptException e) {
                        logger.error("Error while compiling JavaScript!", e);
                    }
                }
            }
        }
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptException(javax.script.ScriptException) Matcher(java.util.regex.Matcher) TelegramValue(org.openhab.binding.ebus.internal.configuration.TelegramValue)

Example 13 with CompiledScript

use of javax.script.CompiledScript in project es6draft by anba.

the class CompilableTest method compileStringWithContextAndBindings.

@Test
public void compileStringWithContextAndBindings() throws ScriptException {
    CompiledScript script = compilable.compile("numberVal * 2");
    ScriptContext context = new SimpleScriptContext();
    Bindings bindings = engine.createBindings();
    bindings.put("numberVal", 8);
    context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    assertThat(script.eval(context), instanceOfWith(Number.class, is(numberCloseTo(16))));
}
Also used : CompiledScript(javax.script.CompiledScript) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) Test(org.junit.Test)

Example 14 with CompiledScript

use of javax.script.CompiledScript in project es6draft by anba.

the class CompilableTest method compileStringWithBindings.

@Test
public void compileStringWithBindings() throws ScriptException {
    CompiledScript script = compilable.compile("numberVal * 2");
    Bindings bindings = engine.createBindings();
    bindings.put("numberVal", 5);
    assertThat(script.eval(bindings), instanceOfWith(Number.class, is(numberCloseTo(10))));
}
Also used : CompiledScript(javax.script.CompiledScript) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) Test(org.junit.Test)

Example 15 with CompiledScript

use of javax.script.CompiledScript in project es6draft by anba.

the class CompilableTest method compileStringWithSimpleBindings.

@Test
public void compileStringWithSimpleBindings() throws ScriptException {
    CompiledScript script = compilable.compile("numberVal * 2");
    Bindings bindings = new SimpleBindings();
    bindings.put("numberVal", 6);
    assertThat(script.eval(bindings), instanceOfWith(Number.class, is(numberCloseTo(12))));
}
Also used : CompiledScript(javax.script.CompiledScript) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) Test(org.junit.Test)

Aggregations

CompiledScript (javax.script.CompiledScript)25 Bindings (javax.script.Bindings)14 ScriptException (javax.script.ScriptException)9 ScriptContext (javax.script.ScriptContext)8 Test (org.junit.Test)8 SimpleBindings (javax.script.SimpleBindings)6 SimpleScriptContext (javax.script.SimpleScriptContext)5 Compilable (javax.script.Compilable)4 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)3 IOException (java.io.IOException)3 StringReader (java.io.StringReader)3 CachedScript (org.apache.sling.scripting.api.CachedScript)3 BufferedReader (java.io.BufferedReader)2 InputStreamReader (java.io.InputStreamReader)2 Reader (java.io.Reader)2 ArrayList (java.util.ArrayList)2 ScriptNameAwareReader (org.apache.sling.scripting.core.ScriptNameAwareReader)2 Context (org.mozilla.javascript.Context)2 Script (org.mozilla.javascript.Script)2 Invoker (com.alibaba.dubbo.rpc.Invoker)1