List of usage examples for javax.script Bindings get
public Object get(Object key);
From source file:org.onesec.raven.ivr.actions.StartRecordingActionTest.java
@Test public void test() throws Exception { MocksControl control = new MocksControl(MocksControl.MockType.NICE); IvrEndpointConversation conv = control.createMock(IvrEndpointConversation.class); ConversationScenarioState state = control.createMock(ConversationScenarioState.class); Bindings bindings = control.createMock(Bindings.class); IncomingRtpStream inRtp = control.createMock(IncomingRtpStream.class); expect(conv.getConversationScenarioState()).andReturn(state).atLeastOnce(); expect(state.getBindings()).andReturn(bindings).atLeastOnce(); expect(bindings.get(BindingNames.DATA_CONTEXT_BINDING)).andReturn(null); expect(bindings.get(StartRecordingAction.RECORDER_BINDING)).andReturn(null); expect(conv.getOwner()).andReturn(actionNode); expect(conv.getExecutorService()).andReturn(executor).atLeastOnce(); expect(conv.getIncomingRtpStream()).andReturn(inRtp); expect(inRtp.addDataSourceListener(checkRtpListener(codecManager, executor, actionNode, bufferCache), isNull(AudioFormat.class))).andReturn(true); state.setBinding(eq(StartRecordingAction.RECORDER_BINDING), isA(Recorder.class), eq(BindingScope.CONVERSATION)); expect(bindings.remove(StartRecordingAction.RECORDER_BINDING)).andReturn(null); control.replay();/*from ww w . j a v a 2s. co m*/ StartRecordingAction action = (StartRecordingAction) actionNode.createAction(); assertNotNull(action); action.doExecute(conv); Thread.sleep(1000); assertNotNull(recorder); recorder.stopRecording(false); assertEquals(1, collector.getDataListSize()); assertTrue(collector.getDataList().get(0) instanceof DataSource); DataSource ds = (DataSource) collector.getDataList().get(0); FileOutputStream out = new FileOutputStream("target/test.wav"); IOUtils.copy(ds.getInputStream(), out); out.close(); // while (action.) control.verify(); }
From source file:Engine.Lua.PlayerLua.java
public void tester(String luaFile) { Dog dog = new Dog("Rex"); Cat cat = new Cat("Felix"); ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine scriptEngine = sem.getEngineByName("luaj"); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile); InputStreamReader isr = new InputStreamReader(is); CompiledScript script;// ww w .ja va 2 s . c o m try { script = ((Compilable) scriptEngine).compile(isr); isr.close(); is.close(); Bindings sb = new SimpleBindings(); script.eval(sb); // Put the Lua functions into the sb environment LuaValue luaDog = CoerceJavaToLua.coerce(dog); // Java to Lua //CoerceLuaToJava() LuaFunction onTalk = (LuaFunction) sb.get("onTalk"); // Get Lua function LuaValue b = onTalk.call(luaDog); // Call the function System.out.println("onTalk answered: " + b); LuaFunction onWalk = (LuaFunction) sb.get("onWalk"); LuaValue[] dogs = { luaDog }; Varargs dist = onWalk.invoke(LuaValue.varargsOf(dogs)); // Alternative System.out.println("onWalk returned: " + dist); Dog retunredDog = (Dog) CoerceLuaToJava.coerce(luaDog, Dog.class); System.out.println("AAAAAAAAAa:" + retunredDog.name); } catch (ScriptException ex) { Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:be.solidx.hot.test.TestScriptExecutors.java
@SuppressWarnings("rawtypes") private Collection<Long> multiThreadedTest(final Script script, final int max, final ScriptExecutor scriptExecutor) throws InterruptedException { final int iterations = 100; ExecutorService executor = Executors.newFixedThreadPool(8); final ConcurrentHashMap<String, Long> results = new ConcurrentHashMap<String, Long>(); final ConcurrentHashMap<String, Long> avgs = new ConcurrentHashMap<String, Long>(); long benchStart = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { Runnable runnable = new Runnable() { @SuppressWarnings("unchecked") @Override/*from w w w .ja v a 2 s. c o m*/ public void run() { try { long res = 0; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("i", new Integer(max)); parameters.put("n", new Integer(0)); //long starting = System.currentTimeMillis(); Object object = scriptExecutor.execute(script, parameters); if (object instanceof Bindings) { Bindings bindings = (Bindings) object; res = (Integer) bindings.get("result"); bindings.clear(); } else if (object instanceof Double) { res = Math.round((Double) object); } else if (object instanceof Long) { res = (long) object; } else res = new Long((Integer) object); long end = System.currentTimeMillis() - avgs.get(this.toString()); results.put(UUID.randomUUID().getLeastSignificantBits() + "", res); avgs.put(this.toString(), end); } catch (Exception e) { e.printStackTrace(); } } }; avgs.put(runnable.toString(), System.currentTimeMillis()); executor.submit(runnable); } while (results.size() < iterations) { Thread.sleep(50); } //Thread.sleep(20000); double sum = 0; for (Long value : avgs.values()) { sum += value; } System.out.println((sum / (double) iterations) + ""); System.out.println("==== Time needed for all requests: " + (System.currentTimeMillis() - benchStart)); results.remove("avg"); executor = null; return results.values(); }
From source file:be.solidx.hot.test.TestScriptExecutors.java
@Test public void testGlobalContextInitExecutionPy() throws Exception { Script<CompiledScript> script = new Script<CompiledScript>( IOUtils.toByteArray(getClass().getResourceAsStream("/be/solidx/hot/test/script.py")), "script.py"); Map<String, Object> contextMap = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("toto", "titi"); contextMap.put("dbmap", map); Bindings bindings = (Bindings) pythonScriptExecutorWithGlobalInit.execute(script, contextMap); Assert.assertEquals("titi", bindings.get("result")); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java
@Test public void shouldClearEngineScopeOnReset() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(); engine.eval("x = { y -> y + 1}"); Bindings b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); assertTrue(b.containsKey("x")); assertEquals(2, ((Closure) b.get("x")).call(1)); // should clear the bindings engine.reset();/*from ww w . j a v a 2 s . co m*/ try { engine.eval("x(1)"); fail("Bindings should have been cleared."); } catch (Exception ex) { } b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); assertFalse(b.containsKey("x")); // redefine x engine.eval("x = { y -> y + 2}"); assertEquals(3, engine.eval("x(1)")); b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); assertTrue(b.containsKey("x")); assertEquals(3, ((Closure) b.get("x")).call(1)); }
From source file:org.nuxeo.ecm.webengine.security.guards.ScriptGuard.java
public boolean check(Adaptable context) { try {/* w ww .ja va2 s . c o m*/ if (engine == null) { comp = compile(type, script); } Bindings bindings = new SimpleBindings(); bindings.put("Context", context); bindings.put("doc", context.getAdapter(DocumentModel.class)); bindings.put("session", context.getAdapter(CoreSession.class)); bindings.put("principal", context.getAdapter(Principal.class)); Object result = null; if (comp != null) { result = comp.eval(bindings); if (result == null) { result = bindings.get("__result__"); } } else { result = engine.eval(new StringReader(script), bindings); } return booleanValue(result); } catch (Exception e) { log.error(e, e); return false; } }
From source file:org.siphon.common.js.JsTypeUtil.java
public JsTypeUtil(ScriptEngine jsEngine) { this.engine = (NashornScriptEngine) jsEngine; try {/*from w w w . j a v a 2s. c o m*/ Bindings b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); this.arrayConstructor = (ScriptObjectMirror) b.get("Array"); this.objectConstructor = (ScriptObjectMirror) b.get("Object"); this.newDate = this.engine.compile("new Date()"); this.global = JsEngineUtil.getGlobal(jsEngine); } catch (Exception e) { e.printStackTrace(); // logger.error("", e); } }
From source file:org.rhq.scripting.javascript.JavascriptCompletor.java
/** * Look through all available contexts to find bindings that both start with * the supplied start and match the typeFilter. * @param start/*from w ww. j a v a2 s. c o m*/ * @param typeFilter * @return */ private Map<String, Object> getContextMatches(String start, Class<?> typeFilter) { Map<String, Object> found = new HashMap<String, Object>(); if (context != null) { for (int scope : context.getScopes()) { Bindings bindings = context.getBindings(scope); for (String var : bindings.keySet()) { if (var.startsWith(start)) { if ((bindings.get(var) != null && typeFilter.isAssignableFrom(bindings.get(var).getClass())) || recomplete == 3) { found.put(var, bindings.get(var)); } } } } if (typeFilter.isEnum()) { for (Object ec : typeFilter.getEnumConstants()) { Enum<?> e = (Enum<?>) ec; String code = typeFilter.getSimpleName() + "." + e.name(); if (code.startsWith(start)) { found.put(typeFilter.getSimpleName() + "." + e.name(), e); } } } } return found; }
From source file:org.rhq.scripting.javascript.JavascriptCompletor.java
private Map<String, Object> getContextMatches(String start) { Map<String, Object> found = new HashMap<String, Object>(); if (context != null) { for (Integer scope : context.getScopes()) { Bindings bindings = context.getBindings(scope); for (String var : bindings.keySet()) { if (var.startsWith(start)) { found.put(var, bindings.get(var)); }//from www . j a v a 2 s .com } } } //this was originally part of the code completor that lived in the CLI //I don't think we need it, because the services are present under the //same names in the context. This code can never add any new matches. /* if (services != null) { for (String var : services.keySet()) { if (var.startsWith(start)) { found.put(var, services.get(var)); } } } */ return found; }
From source file:org.ow2.parserve.PARServeEngine.java
@Override public Object eval(String script, ScriptContext ctx) throws ScriptException { // Transfer all bindings from context into the rengine env if (ctx == null) { throw new ScriptException("No script context specified"); }/*from ww w . j av a2 s . c om*/ Bindings bindings = ctx.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { throw new ScriptException("No bindings specified in the script context"); } serverEval = false; Map<String, Serializable> jobVariables = (Map<String, Serializable>) bindings .get(SchedulerConstants.VARIABLES_BINDING_NAME); if (jobVariables != null) { serverEval = "true".equals(jobVariables.get(PARSERVE_SERVEREVAL)); } Map<String, String> resultMetadata = (Map<String, String>) bindings .get(SchedulerConstants.RESULT_METADATA_VARIABLE); engine = new PARServeConnection(Rsession.newInstanceTry("Script", rServeConf), serverEval); try { initializeTailer(bindings, ctx); Object resultValue = null; if (!serverEval) { prepareExecution(ctx, bindings); } // if there is an exception during the parsing, a ScriptException is immediately thrown engine.checkParsing(script, ctx); // otherwise each step is followed till the end REXP rexp = engine.engineEval(script, ctx); resultValue = retrieveResultVariable(ctx, bindings, rexp); retrieveOtherVariable(SelectionScript.RESULT_VARIABLE, ctx, bindings); retrieveOtherVariable(FlowScript.loopVariable, ctx, bindings); retrieveOtherVariable(FlowScript.branchSelectionVariable, ctx, bindings); retrieveOtherVariable(FlowScript.replicateRunsVariable, ctx, bindings); if (!serverEval) { this.updateJobVariables(jobVariables, ctx); this.updateResultMetadata(resultMetadata, ctx); } // server evaluation is for one task only, it must not be propagated if (serverEval) { jobVariables.put(PARSERVE_SERVEREVAL, "false"); } return resultValue; } catch (Exception ex) { engine.writeExceptionToError(ex, ctx); throw new ScriptException(ex.getMessage()); } finally { engine.terminateOutput(ctx); if (!serverEval) { engine.engineEval("setwd('" + Utils.toRpath(System.getProperty("java.io.tmpdir")) + "')", ctx); } engine.end(); terminateTailer(); if (!serverEval) { // PRC-32 A ScriptException() must be thrown if the script calls stop() function ScriptException toThrow = null; if (lastErrorMessage != null) { toThrow = new ScriptException(lastErrorMessage); } if (toThrow != null) { throw toThrow; } } } }