Search in sources :

Example 31 with SimpleBindings

use of javax.script.SimpleBindings in project cas by apereo.

the class ScriptingUtils method executeGroovyScriptEngine.

/**
 * Execute inline groovy script engine.
 *
 * @param <T>       the type parameter
 * @param script    the script
 * @param variables the variables
 * @param clazz     the clazz
 * @return the t
 */
public static <T> T executeGroovyScriptEngine(final String script, final Map<String, Object> variables, final Class<T> clazz) {
    try {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
        if (engine == null) {
            LOGGER.warn("Script engine is not available for Groovy");
            return null;
        }
        final Bindings binding = new SimpleBindings();
        if (variables != null && !variables.isEmpty()) {
            binding.putAll(variables);
        }
        if (!binding.containsKey("logger")) {
            binding.put("logger", LOGGER);
        }
        final Object result = engine.eval(script, binding);
        if (result != null && !clazz.isAssignableFrom(result.getClass())) {
            throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
        }
        return (T) result;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : SimpleBindings(javax.script.SimpleBindings) ScriptEngineManager(javax.script.ScriptEngineManager) GroovyObject(groovy.lang.GroovyObject) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine)

Example 32 with SimpleBindings

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

the class TomEEEmbeddedMojo method scriptCustomization.

private void scriptCustomization(final List<String> customizers, final String ext, final String base) {
    if (customizers == null || customizers.isEmpty()) {
        return;
    }
    final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(ext);
    if (engine == null) {
        throw new IllegalStateException("No engine for " + ext + ". Maybe add the JSR223 implementation as plugin dependency.");
    }
    for (final String js : customizers) {
        try {
            final SimpleBindings bindings = new SimpleBindings();
            bindings.put("catalinaBase", base);
            engine.eval(new StringReader(js), bindings);
        } catch (final ScriptException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) ScriptEngineManager(javax.script.ScriptEngineManager) StringReader(java.io.StringReader) ScriptEngine(javax.script.ScriptEngine)

Example 33 with SimpleBindings

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

the class AbstractTomEEMojo method scriptCustomization.

private void scriptCustomization(final List<String> customizers, final String ext) throws MojoExecutionException {
    if (customizers != null) {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(ext);
        if (engine == null) {
            throw new IllegalStateException("No engine for " + ext + ". Maybe add the JSR223 implementation as plugin dependency.");
        }
        for (final String js : customizers) {
            try {
                final SimpleBindings bindings = new SimpleBindings();
                bindings.put("catalinaBase", catalinaBase.getAbsolutePath());
                bindings.put("resolver", new Resolver() {

                    @Override
                    public File resolve(final String group, final String artifact, final String version, final String classifier, final String type) {
                        try {
                            return AbstractTomEEMojo.this.resolve(group, artifact, version, classifier, type).resolved;
                        } catch (final ArtifactResolutionException | ArtifactNotFoundException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }

                    @Override
                    public File resolve(final String group, final String artifact, final String version) {
                        try {
                            return AbstractTomEEMojo.this.resolve(group, artifact, version, null, "jar").resolved;
                        } catch (final ArtifactResolutionException | ArtifactNotFoundException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }

                    @Override
                    public File resolve(final String group, final String artifact, final String version, final String type) {
                        try {
                            return AbstractTomEEMojo.this.resolve(group, artifact, version, null, type).resolved;
                        } catch (final ArtifactResolutionException | ArtifactNotFoundException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                });
                engine.eval(new StringReader(js), bindings);
            } catch (final ScriptException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) ArtifactResolver(org.apache.maven.artifact.resolver.ArtifactResolver) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SimpleBindings(javax.script.SimpleBindings) ScriptEngineManager(javax.script.ScriptEngineManager) StringReader(java.io.StringReader) ZipFile(java.util.zip.ZipFile) File(java.io.File) ScriptEngine(javax.script.ScriptEngine)

Example 34 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 35 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)

Aggregations

SimpleBindings (javax.script.SimpleBindings)73 Bindings (javax.script.Bindings)50 Test (org.junit.Test)20 ScriptContext (javax.script.ScriptContext)15 SimpleScriptContext (javax.script.SimpleScriptContext)13 Test (org.testng.annotations.Test)11 ScriptException (javax.script.ScriptException)10 ScriptEngine (javax.script.ScriptEngine)8 ScriptEngineManager (javax.script.ScriptEngineManager)7 SlingBindings (org.apache.sling.api.scripting.SlingBindings)7 StringWriter (java.io.StringWriter)6 PrintWriter (java.io.PrintWriter)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 StringReader (java.io.StringReader)4 CompiledScript (javax.script.CompiledScript)4 RenderContext (org.apache.sling.scripting.sightly.render.RenderContext)4 List (java.util.List)3 Resource (org.apache.sling.api.resource.Resource)3 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)3