List of usage examples for javax.script SimpleBindings SimpleBindings
public SimpleBindings()
From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java
@Test public void shouldFailUntilImportExecutes() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> { });/*from w w w . j a v a 2 s . c o m*/ engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); final Set<String> imports = new HashSet<String>() { { add("import java.awt.Color"); } }; final AtomicInteger successes = new AtomicInteger(0); final AtomicInteger failures = new AtomicInteger(0); final Thread threadImport = new Thread(() -> { engines.addImports(imports); }); // issue 1000 scripts in one thread using a class that isn't imported. this will result in failure. // while that thread is running start a new thread that issues an addImports to include that class. // this should block further evals in the first thread until the import is complete at which point // evals in the first thread will resume and start to succeed final Thread threadEvalAndTriggerImport = new Thread(() -> IntStream.range(0, 1000).forEach(i -> { try { engines.eval("Color.BLACK", new SimpleBindings(), "gremlin-groovy"); successes.incrementAndGet(); } catch (Exception ex) { if (failures.incrementAndGet() == 500) threadImport.start(); Thread.yield(); } })); threadEvalAndTriggerImport.start(); threadEvalAndTriggerImport.join(); threadImport.join(); assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(), successes.intValue() > 0); assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(), failures.intValue() >= 500); engines.close(); }
From source file:org.apache.nifi.reporting.script.ScriptedReportingTask.java
@Override public void onTrigger(final ReportingContext context) { synchronized (scriptingComponentHelper.isInitialized) { if (!scriptingComponentHelper.isInitialized.get()) { scriptingComponentHelper.createResources(); }/* www . j a v a2s.co m*/ } 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); } }
From source file:com.tussle.script.StackedBindings.java
public Bindings pop() { //Get the top map SimpleBindings topValue = bindingStack.pop(); if (bindingStack.isEmpty()) bindingStack.push(new SimpleBindings()); for (Map.Entry<String, Object> entry : topValue.entrySet()) { Object val = bindingMap.get(entry.getKey()).pop(); if (bindingMap.get(entry.getKey()).isEmpty()) bindingMap.remove(entry.getKey()); assert val == entry.getValue(); }/*from w w w. j a v a2 s . com*/ return topValue; }
From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java
private SimpleBindings createBindings(GraphMLEdge edge) { SimpleBindings bindings = new SimpleBindings(); bindings.put("edge", edge); bindings.put("sourceNode", getNodeForEdgeVertexConnector(edge.getSource())); bindings.put("targetNode", getNodeForEdgeVertexConnector(edge.getTarget())); bindings.put("measurements", new MeasurementsWrapper(serviceAccessor.getMeasurementsService())); bindings.put("nodeDao", serviceAccessor.getNodeDao()); bindings.put("snmpInterfaceDao", serviceAccessor.getSnmpInterfaceDao()); return bindings; }
From source file:org.apache.nifi.processors.script.ExecuteScript.java
/** * Evaluates the given script body (or file) using the current session, context, and flowfile. The script * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a * FlowFile, the original FlowFile will be routed to no-flowfile * * @param context the current process context * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which * can be used for accessing FlowFiles, etc. * @throws ProcessException if the scripted processor's onTrigger() method throws an exception *///from w w w . ja va 2 s .com @Override public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException { 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; } ProcessSession session = sessionFactory.createSession(); try { try { Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { bindings = new SimpleBindings(); } bindings.put("session", session); bindings.put("context", context); bindings.put("log", log); bindings.put("REL_SUCCESS", REL_SUCCESS); bindings.put("REL_FAILURE", REL_FAILURE); // 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); } // Commit this session for the user. This plus the outermost catch statement mimics the behavior // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base // class with InvokeScriptedProcessor session.commit(); } 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 }); session.rollback(true); throw t; } finally { scriptingComponentHelper.engineQ.offer(scriptEngine); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldEvalScriptWithGlobalBindings() throws Exception { final Bindings b = new SimpleBindings(); b.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create(); assertEquals(2, gremlinExecutor.eval("1+x").get()); gremlinExecutor.close();//from w w w . j a va2 s. co m }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldGetGlobalBindings() throws Exception { final Bindings b = new SimpleBindings(); final Object bound = new Object(); b.put("x", bound); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create(); assertEquals(bound, gremlinExecutor.getGlobalBindings().get("x")); gremlinExecutor.close();/* ww w . j ava 2s . co m*/ }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldEvalScriptWithGlobalAndLocalBindings() throws Exception { final Bindings g = new SimpleBindings(); g.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create(); final Bindings b = new SimpleBindings(); b.put("y", 1); assertEquals(2, gremlinExecutor.eval("y+x", b).get()); gremlinExecutor.close();//from w w w . j av a2s.c o m }