Search in sources :

Example 76 with SimpleBindings

use of javax.script.SimpleBindings in project nifi by apache.

the class ScriptedReportingTask method onTrigger.

@Override
public void onTrigger(final ReportingContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }
    try {
        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("vmMetrics", vmMetrics);
            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }
            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap.get(scriptingComponentHelper.getScriptEngineName().toLowerCase());
            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }
}
Also used : PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ScriptEngineConfigurator(org.apache.nifi.processors.script.ScriptEngineConfigurator) ComponentLog(org.apache.nifi.logging.ComponentLog) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) SimpleBindings(javax.script.SimpleBindings) Map(java.util.Map)

Example 77 with SimpleBindings

use of javax.script.SimpleBindings in project janusgraph by JanusGraph.

the class JanusGraphManager method getAsBindings.

@Override
public Bindings getAsBindings() {
    final Bindings bindings = new SimpleBindings();
    graphs.forEach(bindings::put);
    return bindings;
}
Also used : SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings)

Example 78 with SimpleBindings

use of javax.script.SimpleBindings in project opennms by OpenNMS.

the class GraphMLScriptVertexStatusProvider method getStatusForVertices.

@Override
public Map<? extends VertexRef, ? extends Status> getStatusForVertices(final VertexProvider vertexProvider, final Collection<VertexRef> vertices, final Criteria[] criteria) {
    // All vertices for the current vertexProvider
    final List<GraphMLVertex> graphMLVertices = vertices.stream().filter(eachVertex -> contributesTo(eachVertex.getNamespace()) && eachVertex instanceof GraphMLVertex).map(eachVertex -> (GraphMLVertex) eachVertex).collect(Collectors.toList());
    // Alarm summary for each node id
    final Map<Integer, AlarmSummary> nodeIdToAlarmSummaryMap = alarmSummaryWrapper.getAlarmSummaries(Lists.transform(graphMLVertices, AbstractVertex::getNodeID)).stream().collect(Collectors.toMap(AlarmSummary::getNodeId, Function.identity()));
    // Calculate status via scripts
    return serviceAccessor.getTransactionOperations().execute(t -> this.scripting.compute(graphMLVertices.stream(), (vertex) -> {
        final SimpleBindings bindings = new SimpleBindings();
        bindings.put("vertex", vertex);
        if (vertex.getNodeID() != null) {
            bindings.put("node", serviceAccessor.getNodeDao().get(vertex.getNodeID()));
            bindings.put("alarmSummary", nodeIdToAlarmSummaryMap.get(vertex.getNodeID()));
        }
        bindings.put("measurements", new MeasurementsWrapper(serviceAccessor.getMeasurementsService()));
        bindings.put("nodeDao", serviceAccessor.getNodeDao());
        bindings.put("snmpInterfaceDao", serviceAccessor.getSnmpInterfaceDao());
        return bindings;
    }));
}
Also used : MeasurementsWrapper(org.opennms.features.topology.api.info.MeasurementsWrapper) Scripting(org.opennms.features.topology.plugins.topo.graphml.internal.Scripting) AlarmSummary(org.opennms.netmgt.model.alarm.AlarmSummary) Collection(java.util.Collection) ScriptEngineManager(javax.script.ScriptEngineManager) AbstractVertex(org.opennms.features.topology.api.topo.AbstractVertex) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) SimpleBindings(javax.script.SimpleBindings) StatusProvider(org.opennms.features.topology.api.topo.StatusProvider) List(java.util.List) Lists(com.google.common.collect.Lists) VertexProvider(org.opennms.features.topology.api.topo.VertexProvider) Paths(java.nio.file.Paths) AlarmSummaryWrapper(org.opennms.features.topology.plugins.topo.graphml.internal.AlarmSummaryWrapper) Criteria(org.opennms.features.topology.api.topo.Criteria) Map(java.util.Map) Status(org.opennms.features.topology.api.topo.Status) VertexRef(org.opennms.features.topology.api.topo.VertexRef) GraphMLServiceAccessor(org.opennms.features.topology.plugins.topo.graphml.internal.GraphMLServiceAccessor) Path(java.nio.file.Path) GraphMLVertex(org.opennms.features.topology.plugins.topo.graphml.GraphMLVertex) GraphMLVertex(org.opennms.features.topology.plugins.topo.graphml.GraphMLVertex) AlarmSummary(org.opennms.netmgt.model.alarm.AlarmSummary) SimpleBindings(javax.script.SimpleBindings) MeasurementsWrapper(org.opennms.features.topology.api.info.MeasurementsWrapper)

Example 79 with SimpleBindings

use of javax.script.SimpleBindings in project opennms by OpenNMS.

the class ScriptedCollectionSetBuilder method build.

/**
 * Builds a collection set from the given message.
 *
 * WARNING: This method is not necessarily thread safe. This depends on the
 * script, and the script engine that is being used.
 *
 * @param agent
 *            the agent associated with the collection set
 * @param message
 *            the messaged passed to script containing the metrics
 * @return a collection set
 * @throws ScriptException
 */
public CollectionSet build(CollectionAgent agent, Object message) throws ScriptException {
    final CollectionSetBuilder builder = new CollectionSetBuilder(agent);
    final SimpleBindings globals = new SimpleBindings();
    globals.put("agent", agent);
    globals.put("builder", builder);
    globals.put("msg", message);
    compiledScript.eval(globals);
    return builder.build();
}
Also used : CollectionSetBuilder(org.opennms.netmgt.collection.support.builder.CollectionSetBuilder) SimpleBindings(javax.script.SimpleBindings)

Example 80 with SimpleBindings

use of javax.script.SimpleBindings in project vcell by virtualcell.

the class ScriptingPanel method run.

private void run() {
    // create scripting engine
    ScriptEngineManager manager = new ScriptEngineManager();
    // ScriptEngine engine = manager.getEngineByName("JavaScript");
    ScriptEngine engine = manager.getEngineByName("jython");
    // create environment for the script to run in.
    // 1) capture stdout and send to the resultsTextField
    // 2) predefine variables for windowManager, bioModel, model, and current selections
    // 
    ScriptContext scriptContext = new SimpleScriptContext();
    scriptContext.setBindings(new SimpleBindings(), ScriptContext.GLOBAL_SCOPE);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    scriptContext.setWriter(printWriter);
    Bindings globals = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
    // }
    if (getBioModel() != null) {
        globals.put("biomodel", getBioModel());
        globals.put("model", getBioModel().getModel());
    }
    engine.setContext(scriptContext);
    // 
    try {
        String fullScript = getPredefinedJythonFunctions();
        fullScript += scriptTextArea.getText();
        System.out.println(fullScript);
        engine.eval(fullScript);
        try {
            Bindings engineBindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
            printWriter.println("\n\n\nengine variable bindings: ");
            for (Map.Entry<String, Object> entry : engineBindings.entrySet()) {
                if (entry.getKey().equals("__builtins__")) {
                    continue;
                }
                printWriter.println("  " + entry.getKey() + " : " + entry.getValue());
            }
            Bindings globalBindings = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
            printWriter.println("\nglobal variable bindings: ");
            for (Map.Entry<String, Object> entry : globalBindings.entrySet()) {
                printWriter.println("  " + entry.getKey() + " : " + entry.getValue());
            }
            printWriter.flush();
            resultsTextArea.append(stringWriter.getBuffer().toString());
            // scroll to bottom.
            resultsTextArea.scrollRectToVisible(new Rectangle(0, resultsTextArea.getHeight() - 2, 1, 1));
        } catch (RuntimeException e1) {
            e1.printStackTrace();
        }
    } catch (ScriptException e1) {
        e1.printStackTrace();
    }
}
Also used : SimpleScriptContext(javax.script.SimpleScriptContext) ScriptEngineManager(javax.script.ScriptEngineManager) Rectangle(java.awt.Rectangle) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) StringWriter(java.io.StringWriter) SimpleBindings(javax.script.SimpleBindings) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

SimpleBindings (javax.script.SimpleBindings)102 Bindings (javax.script.Bindings)65 ScriptEngine (javax.script.ScriptEngine)23 Test (org.junit.Test)22 ScriptContext (javax.script.ScriptContext)17 ScriptException (javax.script.ScriptException)17 ScriptEngineManager (javax.script.ScriptEngineManager)16 SimpleScriptContext (javax.script.SimpleScriptContext)15 Test (org.testng.annotations.Test)11 CompiledScript (javax.script.CompiledScript)10 PrintWriter (java.io.PrintWriter)9 HashMap (java.util.HashMap)8 Map (java.util.Map)8 SlingBindings (org.apache.sling.api.scripting.SlingBindings)7 File (java.io.File)6 StringWriter (java.io.StringWriter)5 ArrayList (java.util.ArrayList)4 XMLEventReader (javax.xml.stream.XMLEventReader)4 XMLEventWriter (javax.xml.stream.XMLEventWriter)4 XMLInputFactory (javax.xml.stream.XMLInputFactory)4