List of usage examples for javax.script Bindings put
public Object put(String name, Object value);
From source file:org.apache.jmeter.util.JSR223TestElement.java
/** * Populate variables to be passed to scripts * @param bindings Bindings/*from w w w . j av a2s . c o m*/ */ protected void populateBindings(Bindings bindings) { final String label = getName(); final String fileName = getFilename(); final String scriptParameters = getParameters(); // Use actual class name for log final Logger logger = LoggingManager.getLoggerForShortName(getClass().getName()); bindings.put("log", logger); // $NON-NLS-1$ (this name is fixed) bindings.put("Label", label); // $NON-NLS-1$ (this name is fixed) bindings.put("FileName", fileName); // $NON-NLS-1$ (this name is fixed) bindings.put("Parameters", scriptParameters); // $NON-NLS-1$ (this name is fixed) String[] args = JOrphanUtils.split(scriptParameters, " ");//$NON-NLS-1$ bindings.put("args", args); // $NON-NLS-1$ (this name is fixed) // Add variables for access to context and variables JMeterContext jmctx = JMeterContextService.getContext(); bindings.put("ctx", jmctx); // $NON-NLS-1$ (this name is fixed) JMeterVariables vars = jmctx.getVariables(); bindings.put("vars", vars); // $NON-NLS-1$ (this name is fixed) Properties props = JMeterUtils.getJMeterProperties(); bindings.put("props", props); // $NON-NLS-1$ (this name is fixed) // For use in debugging: bindings.put("OUT", System.out); // $NON-NLS-1$ (this name is fixed) // Most subclasses will need these: Sampler sampler = jmctx.getCurrentSampler(); bindings.put("sampler", sampler); // $NON-NLS-1$ (this name is fixed) SampleResult prev = jmctx.getPreviousResult(); bindings.put("prev", prev); // $NON-NLS-1$ (this name is fixed) }
From source file:org.apache.synapse.mediators.bsf.ScriptMediator.java
/** * Perform mediation with static inline script of the given scripting language * * @param synCtx message context//w w w . j a v a 2s .com * @return true, or the script return value * @throws ScriptException For any errors , when compile , run the script */ private Object mediateForInlineScript(MessageContext synCtx) throws ScriptException { ScriptMessageContext scriptMC = new ScriptMessageContext(synCtx, xmlHelper); processJSONPayload(synCtx, scriptMC); Bindings bindings = scriptEngine.createBindings(); bindings.put(MC_VAR_NAME, scriptMC); Object response; if (compiledScript != null) { response = compiledScript.eval(bindings); } else { response = scriptEngine.eval(scriptSourceCode, bindings); } return response; }
From source file:fr.ens.transcriptome.corsen.calc.CorsenHistoryResults.java
/** * Calc the custom value.// ww w . ja va2 s . co m * @param cr CorsenResults * @return the custom value */ private double calcCustomValue(final CorsenResult cr) { if (this.script == null) return Double.NaN; Map<Particle3D, Distance> in = cr.getMinDistances(); long inCount = 0; long outCount = 0; for (Map.Entry<Particle3D, Distance> e : in.entrySet()) { final Particle3D particle = e.getKey(); final long intensity = particle.getIntensity(); final Distance distance = e.getValue(); inCount += intensity; final Bindings b = this.script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE); b.put("i", intensity); b.put("d", distance.getDistance()); try { Object o = this.script.eval(); if (o instanceof Boolean && ((Boolean) o) == true) outCount += intensity; } catch (ScriptException e1) { } } return (double) outCount / (double) inCount; }
From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptConsolePlugin.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String contentType = getContentType(req); resp.setContentType(contentType);//ww w. jav a2s.co m if (contentType.startsWith("text/")) { resp.setCharacterEncoding("UTF-8"); } final String script = getCodeValue(req); final Bindings bindings = new SimpleBindings(); final PrintWriter pw = resp.getWriter(); final ScriptHelper osgi = new ScriptHelper(getBundleContext()); final Writer errorWriter = new LogWriter(log); final Reader reader = new StringReader(script); //Populate bindings bindings.put("request", req); bindings.put("reader", reader); bindings.put("response", resp); bindings.put("out", pw); bindings.put("osgi", osgi); //Also expose the bundleContext to simplify scripts interaction with the //enclosing OSGi container bindings.put("bundleContext", getBundleContext()); final String lang = WebConsoleUtil.getParameter(req, "lang"); final boolean webClient = "webconsole".equals(WebConsoleUtil.getParameter(req, "client")); SimpleScriptContext sc = new SimpleScriptContext(); sc.setBindings(bindings, ScriptContext.ENGINE_SCOPE); sc.setWriter(pw); sc.setErrorWriter(errorWriter); sc.setReader(reader); try { log.log(LogService.LOG_DEBUG, "Executing script" + script); eval(script, lang, sc); } catch (Throwable t) { if (!webClient) { resp.setStatus(500); } pw.println(exceptionToString(t)); log.log(LogService.LOG_ERROR, "Error in executing script", t); } finally { if (osgi != null) { osgi.cleanup(); } } }
From source file:org.mule.module.scripting.component.Scriptable.java
public void populateBindings(Bindings bindings, MuleMessage message) { populateDefaultBindings(bindings);//from ww w . j a v a 2 s. com if (message == null) { message = new DefaultMuleMessage(NullPayload.getInstance(), muleContext); } populateVariablesInOrder(bindings, message); bindings.put("message", message); // This will get overwritten if populateBindings(Bindings bindings, MuleEvent event) is called // and not this method directly. bindings.put("payload", message.getPayload()); // For backward compatability bindings.put("src", message.getPayload()); populateHeadersVariablesAndException(bindings, message); }
From source file:org.onesec.raven.ivr.queue.actions.SayNumberInQueueActionTest.java
public void formWords2() throws Exception { ConversationScenarioState state = createMock(ConversationScenarioState.class); Bindings bindings = createMock(Bindings.class); QueuedCallStatus callStatus = createMock(QueuedCallStatus.class); BindingSupport bindingSupport = createMock(BindingSupport.class); expect(state.getBindings()).andReturn(bindings); expect(bindings.get(QueueCallAction.QUEUED_CALL_STATUS_BINDING)).andReturn(callStatus); String key = SayNumberInQueueAction.LAST_SAYED_NUMBER + "_" + owner.getId(); expect(bindings.get(key)).andReturn(null); expect(bindings.put(key, 10)).andReturn(null); expect(callStatus.isQueueing()).andReturn(Boolean.TRUE); expect(callStatus.getSerialNumber()).andReturn(10).anyTimes(); bindingSupport.putAll(bindings);//from www .ja v a 2 s . c o m bindingSupport.reset(); replay(state, bindings, callStatus, bindingSupport); conv.setConversationScenarioState(state); SayNumberInQueueAction action = new SayNumberInQueueAction(owner, bindingSupport, numbers, 50, preamble, resourceManager); List words = action.formWords(conv); assertNotNull(words); assertEquals(2, words.size()); assertArrayEquals(new Object[] { preamble, "10" }, words.toArray()); verify(state, bindings, callStatus, bindingSupport); }
From source file:org.onesec.raven.ivr.queue.actions.SayNumberInQueueActionTest.java
@Test(timeout = 15000) public void test() throws Exception { ConversationScenarioState state = createMock(ConversationScenarioState.class); Bindings bindings = createMock(Bindings.class); BindingSupport bindingSupport = createMock(BindingSupport.class); QueuedCallStatus callStatus = createMock(QueuedCallStatus.class); expect(state.getBindings()).andReturn(bindings); expect(bindings.get(QueueCallAction.QUEUED_CALL_STATUS_BINDING)).andReturn(callStatus); String key = SayNumberInQueueAction.LAST_SAYED_NUMBER + "_" + owner.getId(); expect(bindings.get(key)).andReturn(null); expect(bindings.put(key, 10)).andReturn(null); expect(callStatus.isQueueing()).andReturn(Boolean.TRUE); expect(callStatus.getSerialNumber()).andReturn(10).anyTimes(); bindingSupport.putAll(bindings);//from w ww . jav a 2 s. c om expectLastCall().atLeastOnce(); bindingSupport.reset(); replay(state, bindings, callStatus, bindingSupport); conv.setConversationScenarioState(state); assertTrue(conv.start()); SayNumberInQueueAction action = new SayNumberInQueueAction(owner, bindingSupport, numbers, 50, preamble, resourceManager); action.execute(conv); Thread.sleep(10000); verify(state, bindings, callStatus, bindingSupport); }
From source file:org.apache.jmeter.functions.Groovy.java
/** {@inheritDoc} */ @Override//from w ww. j a v a2s.c o m public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { Bindings bindings = scriptEngine.createBindings(); populateBindings(bindings); String script = ((CompoundVariable) values[0]).execute(); String varName = ""; //$NON-NLS-1$ if (values.length > 1) { varName = ((CompoundVariable) values[1]).execute().trim(); } String resultStr = ""; //$NON-NLS-1$ try { // Pass in some variables if (currentSampler != null) { bindings.put("sampler", currentSampler); // $NON-NLS-1$ } if (previousResult != null) { bindings.put("prev", previousResult); //$NON-NLS-1$ } bindings.put("log", log); // $NON-NLS-1$ (this name is fixed) // Add variables for access to context and variables bindings.put("threadName", Thread.currentThread().getName()); JMeterContext jmctx = JMeterContextService.getContext(); bindings.put("ctx", jmctx); // $NON-NLS-1$ (this name is fixed) JMeterVariables vars = jmctx.getVariables(); bindings.put("vars", vars); // $NON-NLS-1$ (this name is fixed) Properties props = JMeterUtils.getJMeterProperties(); bindings.put("props", props); // $NON-NLS-1$ (this name is fixed) // For use in debugging: bindings.put("OUT", System.out); // $NON-NLS-1$ (this name is fixed) // Execute the script Object out = scriptEngine.eval(script, bindings); if (out != null) { resultStr = out.toString(); } if (varName.length() > 0) {// vars will be null on TestPlan if (vars != null) { vars.put(varName, resultStr); } } } catch (Exception ex) // Mainly for bsh.EvalError { log.warn("Error running groovy script", ex); } if (log.isDebugEnabled()) { log.debug("__groovy(" + script + "," + varName + ")=" + resultStr); } return resultStr; }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
private Bindings getBindings(Execution execution, JCRSessionWrapper session) throws RepositoryException { EnvironmentImpl environment = EnvironmentImpl.getCurrent(); final Map<String, Object> vars = ((ExecutionImpl) execution).getVariables(); Locale locale = (Locale) vars.get("locale"); final Bindings bindings = new MyBindings(environment); ResourceBundle resourceBundle = JahiaResourceBundle.lookupBundle( "org.jahia.services.workflow." + ((ExecutionImpl) execution).getProcessDefinition().getKey(), locale);//from w w w . j a v a2 s . co m bindings.put("bundle", resourceBundle); JahiaUser jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService() .lookupUserByKey((String) vars.get("user")); bindings.put("user", jahiaUser); bindings.put("date", new DateTool()); bindings.put("submissionDate", Calendar.getInstance()); bindings.put("locale", locale); bindings.put("workspace", vars.get("workspace")); List<JCRNodeWrapper> nodes = new LinkedList<JCRNodeWrapper>(); @SuppressWarnings("unchecked") List<String> stringList = (List<String>) vars.get("nodeIds"); for (String s : stringList) { JCRNodeWrapper nodeByUUID = session.getNodeByUUID(s); if (!nodeByUUID.isNodeType("jnt:translation")) { nodes.add(nodeByUUID); } } bindings.put("nodes", nodes); return bindings; }
From source file:org.jahia.services.mail.MailServiceImpl.java
@Override public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail, String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName) throws RepositoryException, ScriptException { // Resolve template : ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, ".")); ScriptContext scriptContext = new SimpleScriptContext(); //try if it is multilingual String suffix = StringUtils.substringAfterLast(template, "."); String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_" + locale.toString() + "." + suffix; JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName); Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate); if (templateRealPath == null) { templateRealPath = templatePackage.getResource(template); }// w w w. ja v a2 s .com InputStream scriptInputStream = null; try { scriptInputStream = templateRealPath.getInputStream(); } catch (IOException e) { logger.error(e.getMessage(), e); } if (scriptInputStream != null) { ResourceBundle resourceBundle; if (templatePackageName == null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); resourceBundle = ResourceBundles.get(resourceBundleName, locale); } else { resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackage(templatePackageName), locale); } final Bindings bindings = new SimpleBindings(); bindings.put("bundle", resourceBundle); bindings.putAll(boundObjects); Reader scriptContent = null; // Subject String subject; try { String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, "."); InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream(); scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset) : new InputStreamReader(stream); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptEngine.eval(scriptContent, scriptContext); subject = scriptContext.getWriter().toString().trim(); } catch (Exception e) { logger.warn("Not able to render mail subject using " + StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, ".") + " template file - set org.jahia.services.mail.MailService in debug for more information"); if (logger.isDebugEnabled()) { logger.debug("generating the mail subject throw an exception : ", e); } subject = resourceBundle.getString( StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".") + ".subject"); } finally { IOUtils.closeQuietly(scriptContent); } try { try { scriptContent = templateCharset != null ? new InputStreamReader(scriptInputStream, templateCharset) : new InputStreamReader(scriptInputStream); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); // The following binding is necessary for JavaScript, which // doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); String body = writer.toString(); sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { IOUtils.closeQuietly(scriptContent); } } else { logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName + "] not found"); } }