Example usage for javax.script Bindings putAll

List of usage examples for javax.script Bindings putAll

Introduction

In this page you can find the example usage for javax.script Bindings putAll.

Prototype

public void putAll(Map<? extends String, ? extends Object> toMerge);

Source Link

Document

Adds all the mappings in a given Map to this Bindings .

Usage

From source file:org.apache.sling.scripting.sightly.js.impl.jsapi.ProxyAsyncScriptableFactory.java

public void registerProxies(Bindings bindings) {
    slyBindingsValuesProvider.initialise(bindings);
    Bindings bindingsCopy = new SimpleBindings();
    for (String factoryName : slyBindingsValuesProvider.getScriptPaths().keySet()) {
        ShadowScriptableObject shadowScriptableObject = new ShadowScriptableObject(factoryName, bindingsCopy);
        bindings.put(factoryName, shadowScriptableObject);
    }/*from   w  ww.j a  v a2s  .  com*/
    bindingsCopy.putAll(bindings);
}

From source file:org.apache.sling.scripting.sightly.js.impl.JsEnvironment.java

private Bindings buildBindings(Resource scriptResource, Bindings local, Bindings arguments,
        CommonJsModule commonJsModule) {
    Bindings bindings = new SimpleBindings();
    bindings.putAll(engineBindings);
    DependencyResolver dependencyResolver = new DependencyResolver(scriptResource, this, local);
    UseFunction useFunction = new UseFunction(dependencyResolver, arguments);
    bindings.put(Variables.JS_USE, useFunction);
    bindings.put(Variables.MODULE, commonJsModule);
    bindings.put(Variables.EXPORTS, commonJsModule.getExports());
    bindings.put(Variables.CONSOLE, new Console(LoggerFactory.getLogger(scriptResource.getName())));
    bindings.putAll(local);/*w w  w  . j  a  v a  2s .c om*/
    return bindings;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

/**
 * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle.
 *
 * @param script the script to evaluate/*from  www . jav  a 2 s  . co  m*/
 * @param language the language to evaluate it in
 * @param boundVars the bindings to evaluate in the context of the script
 * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process
 */
public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars,
        final LifeCycle lifeCycle) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug("Preparing to evaluate script - {} - in thread [{}]", script,
            Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> f = new FutureTask<>(() -> {
        try {
            lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings);

            logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName());

            final Object o = scriptEngines.eval(script, bindings, lang);

            // apply a transformation before sending back the result - useful when trying to force serialization
            // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some
            // transactional constraints
            final Object result = lifeCycle.getTransformResult().isPresent()
                    ? lifeCycle.getTransformResult().get().apply(o)
                    : o;

            // a mechanism for taking the final result and doing something with it in the same thread, but
            // AFTER the eval and transform are done and that future completed.  this provides a final means
            // for working with the result in the same thread as it was eval'd
            if (lifeCycle.getWithResult().isPresent())
                lifeCycle.getWithResult().get().accept(result);

            lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings);

            // the evaluationFuture must be completed after all processing as an exception in lifecycle events
            // that must raise as an exception to the caller who has the returned evaluationFuture. in other words,
            // if it occurs before this point, then the handle() method won't be called again if there is an
            // exception that ends up below trying to completeExceptionally()
            evaluationFuture.complete(result);
        } catch (Throwable ex) {
            final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

            // thread interruptions will typically come as the result of a timeout, so in those cases,
            // check for that situation and convert to TimeoutException
            if (root instanceof InterruptedException)
                evaluationFuture.completeExceptionally(new TimeoutException(String.format(
                        "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s",
                        scriptEvaluationTimeout, script, root.getMessage())));
            else {
                lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root);
                evaluationFuture.completeExceptionally(root);
            }
        }

        return null;
    });

    executorService.execute(f);

    if (scriptEvaluationTimeout > 0) {
        // Schedule a timeout in the thread pool for future execution
        final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> {
            logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName());
            if (!f.isDone()) {
                lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings);
                f.cancel(true);
            }
        }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS);

        // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed
        // with exception
        evaluationFuture.handleAsync((v, t) -> {
            logger.debug(
                    "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception).");
            return sf.cancel(true);
        });
    }

    return evaluationFuture;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

private ScriptEngines createScriptEngines() {
    // plugins already on the path - ones static to the classpath
    final List<GremlinPlugin> globalPlugins = new ArrayList<>();
    ServiceLoader.load(GremlinPlugin.class).forEach(globalPlugins::add);

    return new ScriptEngines(se -> {
        // this first part initializes the scriptengines Map
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();
            se.reload(language, new HashSet<>(config.getValue().getImports()),
                    new HashSet<>(config.getValue().getStaticImports()), config.getValue().getConfig());
        }/*from w  ww  . java2  s  .c o  m*/

        // use grabs dependencies and returns plugins to load
        final List<GremlinPlugin> pluginsToLoad = new ArrayList<>(globalPlugins);
        use.forEach(u -> {
            if (u.size() != 3)
                logger.warn(
                        "Could not resolve dependencies for [{}].  Each entry for the 'use' configuration must include [groupId, artifactId, version]",
                        u);
            else {
                logger.info("Getting dependencies for [{}]", u);
                pluginsToLoad.addAll(se.use(u.get(0), u.get(1), u.get(2)));
            }
        });

        // now that all dependencies are in place, the imports can't get messed up if a plugin tries to execute
        // a script (as the script engine appends the import list to the top of all scripts passed to the engine).
        // only enable those plugins that are configured to be enabled.
        se.loadPlugins(pluginsToLoad.stream().filter(plugin -> enabledPlugins.contains(plugin.getName()))
                .collect(Collectors.toList()));

        // initialization script eval can now be performed now that dependencies are present with "use"
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();

            // script engine initialization files that fail will only log warnings - not fail server initialization
            final AtomicBoolean hasErrors = new AtomicBoolean(false);
            config.getValue().getScripts().stream().map(File::new).filter(f -> {
                if (!f.exists()) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file does not exist", language,
                            f);
                    hasErrors.set(true);
                }

                return f.exists();
            }).map(f -> {
                try {
                    return Pair.with(f, Optional.of(new FileReader(f)));
                } catch (IOException ioe) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file could not be read - {}",
                            language, f, ioe.getMessage());
                    hasErrors.set(true);
                    return Pair.with(f, Optional.<FileReader>empty());
                }
            }).filter(p -> p.getValue1().isPresent()).map(p -> Pair.with(p.getValue0(), p.getValue1().get()))
                    .forEachOrdered(p -> {
                        try {
                            final Bindings bindings = new SimpleBindings();
                            bindings.putAll(globalBindings);

                            // evaluate init scripts with hard reference so as to ensure it doesn't get garbage collected
                            bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE,
                                    GremlinGroovyScriptEngine.REFERENCE_TYPE_HARD);

                            // the returned object should be a Map of initialized global bindings
                            final Object initializedBindings = se.eval(p.getValue1(), bindings, language);
                            if (initializedBindings != null && initializedBindings instanceof Map)
                                globalBindings.putAll((Map) initializedBindings);
                            else
                                logger.warn(
                                        "Initialization script {} did not return a Map - no global bindings specified",
                                        p.getValue0());

                            logger.info("Initialized {} ScriptEngine with {}", language, p.getValue0());
                        } catch (ScriptException sx) {
                            hasErrors.set(true);
                            logger.warn(
                                    "Could not initialize {} ScriptEngine with {} as script could not be evaluated - {}",
                                    language, p.getValue0(), sx.getMessage());
                        }
                    });
        }
    });
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

@Override
public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource)
        throws ScriptException {
    // these validations occur before merging in bytecode bindings which will override existing ones. need to
    // extract the named traversalsource prior to that happening so that bytecode bindings can share the same
    // namespace as global bindings (e.g. traversalsources and graphs).
    if (traversalSource.equals(HIDDEN_G))
        throw new IllegalArgumentException(
                "The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved");

    if (bindings.containsKey(HIDDEN_G))
        throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved");

    if (!bindings.containsKey(traversalSource))
        throw new IllegalArgumentException(
                "The bindings available to the ScriptEngine do not contain a traversalSource named: "
                        + traversalSource);

    final Object b = bindings.get(traversalSource);
    if (!(b instanceof TraversalSource))
        throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName()
                + " and is not an instance of TraversalSource");

    final Bindings inner = new SimpleBindings();
    inner.putAll(bindings);
    inner.putAll(bytecode.getBindings());
    inner.put(HIDDEN_G, b);// w w  w.j  a va2s . com

    return (Traversal.Admin) this.eval(GroovyTranslator.of(HIDDEN_G).translate(bytecode), inner);
}

From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java

private Bindings createBindings(final Map<String, Object> bindingMap, final Map<String, String> rebindingMap) {
    final Bindings bindings = new SimpleBindings();

    // rebind any global bindings to a different variable.
    if (!rebindingMap.isEmpty()) {
        for (Map.Entry<String, String> kv : rebindingMap.entrySet()) {
            boolean found = false;
            final Map<String, Graph> graphs = this.graphManager.getGraphs();
            if (graphs.containsKey(kv.getValue())) {
                bindings.put(kv.getKey(), graphs.get(kv.getValue()));
                found = true;/*from   w  w  w .  ja v a 2 s .c  o m*/
            }

            if (!found) {
                final Map<String, TraversalSource> traversalSources = this.graphManager.getTraversalSources();
                if (traversalSources.containsKey(kv.getValue())) {
                    bindings.put(kv.getKey(), traversalSources.get(kv.getValue()));
                    found = true;
                }
            }

            if (!found) {
                final String error = String.format(
                        "Could not rebind [%s] to [%s] as [%s] not in the Graph or TraversalSource global bindings",
                        kv.getKey(), kv.getValue(), kv.getValue());
                throw new IllegalStateException(error);
            }
        }
    }

    bindings.putAll(bindingMap);

    return bindings;
}

From source file:org.craftercms.engine.scripting.impl.Jsr233CompiledScript.java

@Override
public Object execute(Map<String, Object> variables) throws ScriptException {
    Bindings bindings = new SimpleBindings();
    if (MapUtils.isNotEmpty(globalVariables)) {
        bindings.putAll(globalVariables);
    }//from  w  w w. ja  v a2 s  .c  om
    if (MapUtils.isNotEmpty(variables)) {
        bindings.putAll(variables);
    }

    try {
        return script.eval(bindings);
    } catch (Exception e) {
        throw new ScriptException(e.getMessage(), e);
    }
}

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

private static Object evaluateJSR233Expression(RuntimeContext rtCtx, Expression fireflowExpression,
        Map<String, Object> contextObjects) {
    ScriptEngine scriptEngine = rtCtx.getScriptEngine(fireflowExpression.getLanguage());

    ScriptContext scriptContext = new SimpleScriptContext();
    Bindings engineScope = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.putAll(contextObjects);
    try {// w  ww.ja v a2s.c  o  m
        Object result = scriptEngine.eval(fireflowExpression.getBody(), scriptContext);
        return result;
    } catch (ScriptException e) {
        throw new RuntimeException("Can NOT evaluate the expression. ", e);
    }
}

From source file:org.freeplane.plugin.script.GenericScript.java

private Bindings createBinding(final NodeModel node) {
    final Bindings binding = engine.createBindings();
    binding.put("c", ProxyFactory.createController(scriptContext));
    binding.put("node", ProxyFactory.createNode(node, scriptContext));
    binding.putAll(ScriptingConfiguration.getStaticProperties());
    return binding;
}

From source file:org.gatherdata.alert.detect.bsf.internal.BsfEventDetector.java

private Bindings adaptToScriptContext(Map<String, Object> attributes) {
    Bindings scriptBindings = new SimpleBindings();
    scriptBindings.putAll(attributes);
    return scriptBindings;
}