@SuppressWarnings("unchecked") public AnimatorCore(File file) throws FileNotFoundException { Beans.setDesignTime(false); rootContext = new BeanContextServicesSupport(); try { URL specURL = new URL("file:///E:/czt/zml/examples/z/birthdaybook_unfolded.tex"); history = new ZLiveHistory("BirthdayBook", "InitBirthdayBook", specURL); } catch (MalformedURLException ex) { ex.printStackTrace(); } XMLDecoder decoder; decoder = new XMLDecoder(new FileInputStream(file), this); try { while (true) { final Form newForm; newForm = (Form) decoder.readObject(); final JFrame frame = new JFrame() { /** */ private static final long serialVersionUID = 4731706062562233200L; public void setVisible(boolean b) { super.setVisible(b); if (newForm.isVisible() != b) newForm.setVisible(b); }; }; newForm.addComponentListener( new ComponentAdapter() { public void componentHidden(ComponentEvent e) { // If the last form was closed, then quit. Vector<Form> visibleForms = new Vector<Form>(forms_); for (Iterator<Form> i = visibleForms.iterator(); i.hasNext(); ) if (!i.next().isVisible()) i.remove(); visibleForms.remove(e.getComponent()); if (visibleForms.isEmpty()) System.exit(0); }; }); newForm.addPropertyChangeListener( "title", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { frame.setTitle((String) evt.getNewValue()); }; }); if (!newForm.isPreferredSizeSet()) newForm.setPreferredSize(newForm.getSize()); newForm.setLocation(0, 0); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(newForm, BorderLayout.CENTER); frame.pack(); frame.setTitle(newForm.getTitle()); // XXX URGENT setVisible should be moved after the init scripts. // If somebody starts using the interface before the init script // finishes it can have `weird and fun' side-effects // frame.setVisible(newForm.getStartsVisible()); forms_.add(newForm); decoder.readObject(); // beanWrappers // unchecked Vector<BeanLink> beanLinks = (Vector<BeanLink>) decoder.readObject(); // eventLinks for (Iterator<BeanLink> iter = beanLinks.iterator(); iter.hasNext(); ) { BeanLink bl = iter.next(); IntrospectionHelper.addBeanListener(bl.source, bl.listenerType, bl.listener); } rootContext.add(newForm); // unchecked } } catch (ArrayIndexOutOfBoundsException ex) { } finally { decoder.close(); } // XXX Load Z specification. // XXX Display appropriate forms. BSFManager bsfm = new BSFManager(); // XXX (register any new scripting languages) // XXX register and declare beans in bsfm try { bsfm.declareBean("History", history, history.getClass()); bsfm.declareBean("AnimatorCore", this, this.getClass()); bsfm.declareBean("Forms", forms_, forms_.getClass()); bsfm.declareBean("err", System.err, System.err.getClass()); bsfm.declareBean("out", System.out, System.out.getClass()); } catch (BSFException ex) { throw new Error( "History,AnimatorCore, or Forms couldn't be declared " + "with the Scripting Engine. " + ex); } rootContext.addService(BSFManager.class, new BSFServiceProvider(bsfm)); rootContext.addService(History.class, new HistoryServiceProvider(history)); try { bsfm.exec(initScriptLanguage_, "init", 1, 1, initScript_); } catch (BSFException ex) { // XXX Do something? // error dialog? // send message back? // make it settable? System.err.println("Init Script caught BSFException:"); System.err.println(ex); ex.printStackTrace(); System.err.println("------"); ex.getTargetException().printStackTrace(); } ; for (Iterator<Form> it = forms_.iterator(); it.hasNext(); ) { Form form = it.next(); boolean v = form.getStartsVisible(); form.setVisible(v); System.err.println("Setting visible " + form.getName() + " = " + v); } };
@Test public void testVarAccess() { Configuration config = Configuration.instance(); try { config.load(); } catch (ConfigurationException e1) { e1.printStackTrace(); fail(); } BSFManager bsfManager = new BSFManager(); BSFEngine engine = null; try { engine = bsfManager.loadScriptingEngine("BeanShell"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } assertNotNull(engine); try { // ObjectRegistry registry = bsfManager.getObjectRegistry(); // registry.register("mmm", new Integer(3)); // engine.exec("source", 1, 1, "print( mmm );"); engine.exec("source", 1, 1, "mmm = 1000;"); engine.exec("source", 1, 1, "print( mmm );"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } engine.terminate(); }
/** Test of eval method, of class JRubyEngine. */ @Test public void testEval() throws Exception { System.out.println("eval"); BSFManager.registerScriptingEngine( "jruby", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); BSFManager manager = new BSFManager(); JRubyEngine instance = new JRubyEngine(); instance.initialize(manager, "jruby", null); String file = ""; int line = 0; int col = 0; Object expr = null; Object expResult = null; Object result = instance.eval(file, line, col, expr); assertEquals(expResult, result); expResult = "HELLO WORLD!"; result = instance.eval("<script>", 0, 0, "message=\"Hello \" + \"World!\"\nmessage.upcase"); assertEquals(expResult, result); manager.declareBean("greet", "Heeey", String.class); result = manager.eval("jruby", "<script>", 0, 0, "message=$greet + \" World!\""); expResult = "Heeey World!"; assertEquals(expResult, result); }
/** * Registers script engines needed for language support. * * <p>When adding support to this class for a new engine, this method must be modified to support * that language */ private static void registerScriptEngines() { if (!BSFManager.isLanguageRegistered(Language.RUBY.name())) { BSFManager.registerScriptingEngine( Language.RUBY.name(), "org.jruby.javasupport.bsf.JRubyEngine", //$NON-NLS-1$ new String[] {"rb"}); // $NON-NLS-1$ } }
/** Test of undeclareBean method, of class JRubyEngine. */ @Test public void testUndeclareBean() throws Exception { System.out.println("undeclareBean"); BSFManager manager = new BSFManager(); JRubyEngine instance = new JRubyEngine(); instance.initialize(manager, "jruby", null); manager.declareBean("abc", "aaabbbccc", String.class); BSFDeclaredBean bean = (BSFDeclaredBean) manager.getObjectRegistry().lookup("abc"); instance.undeclareBean(bean); }
static { BSFManager.registerScriptingEngine( "jexl", //$NON-NLS-1$ "org.apache.commons.jexl.bsf.JexlEngine", //$NON-NLS-1$ new String[] {"jexl"}); // $NON-NLS-1$ log.info("Registering JMeter version of JavaScript engine as work-round for BSF-22"); BSFManager.registerScriptingEngine( "javascript", //$NON-NLS-1$ "org.apache.jmeter.util.BSFJavaScriptEngine", //$NON-NLS-1$ new String[] {"js"}); // $NON-NLS-1$ }
protected void configureBsf() { String[] bshExtensions = {"bsh"}; BSFManager.registerScriptingEngine( "beanshell", "org.ofbiz.base.util.OfbizBshBsfEngine", bshExtensions); String[] jsExtensions = {"js"}; BSFManager.registerScriptingEngine( "javascript", "org.ofbiz.base.util.OfbizJsBsfEngine", jsExtensions); String[] smExtensions = {"sm"}; BSFManager.registerScriptingEngine( "simplemethod", "org.ofbiz.minilang.SimpleMethodBsfEngine", smExtensions); }
// public Object getValue(String nameField,Index indexRow,SelectableDataSource sds) { // try { // int index=sds.getFieldIndexByName(nameField); // Value value=sds.getFieldValue(indexRow.get(),index); // if (value instanceof NumericValue) { // double dv=((NumericValue)value).doubleValue(); // return new Double(dv); // }else if (value instanceof DateValue) { // Date date=((DateValue)value).getValue(); // return date; // }else if (value instanceof BooleanValue){ // boolean b=((BooleanValue)value).getValue(); // return new Boolean(b); // }else { // return value.toString(); // } // } catch (ReadDriverException e) { // throw new RuntimeException(e.getMessage()); // } // } public void eval(BSFManager interpreter) throws BSFException { if (!isEval) { interpreter.declareBean("jfield", this, Field.class); interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def field(nameField):\n" + " return jfield.getValue(featureContainer.getFeature(), nameField)"); isEval = true; } }
private void init() { try { sds = ies.getRecordset(); fieldDescriptors = sds.getFieldsDescription(); fieldDescriptor = fieldDescriptors[selectedIndex]; interpreter.declareBean("sds", sds, SelectableDataSource.class); indexRow = new Index(); interpreter.declareBean("indexRow", indexRow, Index.class); } catch (BSFException e) { e.printStackTrace(); } catch (ReadDriverException e) { e.printStackTrace(); } }
/** * Loads the declarations of the script engines declared in a property set * * @param props property set containing the configuration * @throws ConfigurationException if the scripting languages cannot be loaded */ private void loadScriptingLanguages(Properties props) throws ConfigurationException { String strEngineList = loadProperty(props, SCRIPT_ENGINE_LIST_P); for (StringTokenizer engineTokenizer = new StringTokenizer(strEngineList); engineTokenizer.hasMoreTokens(); ) { String engineBaseItem = engineTokenizer.nextToken(); String engineName = props.getProperty(engineBaseItem + ".name"); // $NON-NLS-1$ String engineClass = props.getProperty(engineBaseItem + ".class"); // $NON-NLS-1$ String engineExtProps = props.getProperty(engineBaseItem + ".extensions"); // $NON-NLS-1$ String[] extArray = null; if (engineExtProps != null) { List<String> extList = new ArrayList<String>(); for (StringTokenizer extTokenizer = new StringTokenizer(engineExtProps); extTokenizer.hasMoreTokens(); ) { String extension = extTokenizer.nextToken(); ext = extension; extList.add(extension); } extArray = extList.toArray(new String[0]); } BSFManager.registerScriptingEngine(engineName, engineClass, extArray); System.out.println("Script " + engineName + " loaded"); // $NON-NLS-1$ //$NON-NLS-2$ } defaultEngineName = loadProperty(props, DFLT_SCRIPT_ENGINE_P); }
/** Initialize the engine. */ public void initialize(final BSFManager mgr, String lang, Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); ClassLoader parent = mgr.getClassLoader(); if (parent == null) parent = GroovyShell.class.getClassLoader(); final ClassLoader finalParent = parent; this.loader = (GroovyClassLoader) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setClasspath(mgr.getClassPath()); return new GroovyClassLoader(finalParent, configuration); } }); execScripts = new HashMap(); evalScripts = new HashMap(); context = shell.getContext(); // create a shell // register the mgr with object name "bsf" context.setVariable("bsf", new BSFFunctions(mgr, this)); int size = declaredBeans.size(); for (int i = 0; i < size; i++) { declareBean((BSFDeclaredBean) declaredBeans.elementAt(i)); } }
public void eval(BSFManager interpreter) throws BSFException { // interpreter.eval(ExpressionFieldExtension.BEANSHELL,null,-1,-1,"String // toString(java.lang.Object value){" // + // "if (value instanceof java.util.Date)" + // "return ((java.util.Date)value).toString();" + // "return String.valueOf(value);};"); interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "import java.util.Date as Date\n" + "import java.text.DateFormat as DateFormat\n" + "import java.text.SimpleDateFormat as SimpleDateFormat\n" + "import java.text.NumberFormat as NumberFormat\n" + "dateFormat = DateFormat.getInstance()\n" + "myDateFormat = SimpleDateFormat()\n" + "def dateToString(value, format=None):\n" + " if value == None:\n" + " return None\n" + " if value == '':\n" + " return ''\n" + " if isinstance(value,Date):\n" + " if format != None:\n" + " myDateFormat.applyPattern(format)\n" + " return myDateFormat.format(value)\n" + " else:\n" + " return dateFormat.format(value)\n" + " else:\n" + " raise InputError\n" + " return str(value)"); }
@Test public void testPathTyp() throws BSFException { System.out.println("PathType"); BSFManager.registerScriptingEngine( "jruby", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); BSFManager manager = new BSFManager(); JRubyEngine instance = (JRubyEngine) manager.loadScriptingEngine("jruby"); Object receiver = instance.eval("org/jruby/embed/ruby/radioactive_decay.rb", 0, 0, PathType.CLASSPATH); String method = "amount_after_years"; Object[] args = new Object[2]; args[0] = 10.0; args[1] = 1000; // Plutonium manager.declareBean("h", 24100, Long.class); Object result = instance.call(receiver, method, args); assertEquals(9.716, (Double) result, 0.001); }
@Test public void testRubyVersion() throws BSFException { System.out.println("RubyVersion"); BSFManager.registerScriptingEngine( "jruby", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); BSFManager manager = new BSFManager(); JRubyEngine instance = (JRubyEngine) manager.loadScriptingEngine("jruby"); Object result = instance.eval("org/jruby/embed/ruby/block-param-scope.rb", 0, 0, PathType.CLASSPATH); String expResult = "cat"; assertEquals(expResult, ((String) result).trim()); // Ruby 1.9 mode is somehow broken in 1.5.0dev BSFManager.registerScriptingEngine( "jruby19", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); instance = (JRubyEngine) manager.loadScriptingEngine("jruby19"); result = instance.eval("org/jruby/embed/ruby/block-param-scope.rb", 0, 0, PathType.CLASSPATH); expResult = "bear"; assertEquals(expResult, ((String) result).trim()); }
@Test public void testLoad() { Configuration config = Configuration.instance(); try { config.load(); } catch (ConfigurationException e) { e.printStackTrace(); fail(); } assertTrue(BSFManager.isLanguageRegistered("BeanShell")); }
@Test public void testLVar() throws BSFException { BSFManager.registerScriptingEngine( "jruby", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); BSFManager bsf = new BSFManager(); bsf.eval("jruby", "(java)", 1, 1, "$x='GVar'"); bsf.eval("jruby", "(java)", 1, 1, "puts \"$x = #{$x}\""); bsf.eval("jruby", "(java)", 1, 1, "x='LVar'"); bsf.eval("jruby", "(java)", 1, 1, "at_exit { puts \"#{x} and #{$x} in an at_exit block\" }"); bsf.eval("jruby", "(java)", 1, 1, "puts \"x = #{x}\""); bsf.terminate(); }
/** Test of call method, of class JRubyEngine. */ @Test public void testCall() throws Exception { System.out.println("call"); BSFManager.registerScriptingEngine( "jruby", "org.jruby.embed.bsf.JRubyEngine", new String[] {"rb"}); BSFManager manager = new BSFManager(); JRubyEngine instance = (JRubyEngine) manager.loadScriptingEngine("jruby"); instance.initialize(manager, "jruby", null); Object recv = null; String method = ""; Object[] args = null; Object expResult = null; Object result = instance.call(recv, method, args); assertEquals(expResult, result); String script = "# Radioactive decay\n" + "def amount_after_years(q0, t)\n" + "q0 * Math.exp(1.0 / $h * Math.log(1.0/2.0) * t)\n" + "end\n" + "def years_to_amount(q0, q)\n" + "$h * (Math.log(q) - Math.log(q0)) / Math.log(1.0/2.0)\n" + "end"; recv = manager.eval("jruby", "radioactive_decay", 0, 0, script); method = "amount_after_years"; args = new Object[2]; args[0] = 10.0; args[1] = 1000; // Radium manager.declareBean("h", 1599, Long.class); result = instance.call(recv, method, args); assertEquals(6.482, (Double) result, 0.001); method = "years_to_amount"; args[0] = 10.0; args[1] = 1.0; result = instance.call(recv, method, args); assertEquals(5311.8, (Double) result, 0.1); }
public void eval(BSFManager interpreter) throws BSFException { // interpreter.eval(ExpressionFieldExtension.BEANSHELL,null,-1,-1,"String // toString(java.lang.Object value){" + // "if (value instanceof java.util.Date)" + // "return ((java.util.Date)value).toString();" + // "return String.valueOf(value);};"); interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def toString(value):\n" + " return str(value)"); }
public AssertionResult getResult(SampleResult response) { AssertionResult result = new AssertionResult(getName()); try { BSFManager mgr = getManager(); if (mgr == null) { result.setFailure(true); result.setError(true); result.setFailureMessage("BSF Manager not found"); return result; } mgr.declareBean("SampleResult", response, SampleResult.class); mgr.declareBean("AssertionResult", result, AssertionResult.class); processFileOrScript(mgr); mgr.terminate(); result.setError(false); } catch (BSFException e) { log.warn("Problem in BSF script " + e); result.setError(true); result.setFailureMessage(e.toString()); } return result; }
/* (non-Javadoc) * @see org.marketcetera.strategy.ExecutionEngine#prepare(org.marketcetera.strategy.Strategy, java.lang.String) */ @Override public void prepare(Strategy inStrategy, String inProcessedScript) throws StrategyException { strategy = inStrategy; processedScript = inProcessedScript; SLF4JLoggerProxy.debug( this, "Preparing {}", //$NON-NLS-1$ inStrategy); registerScriptEngines(); String languageString = inStrategy.getLanguage().name(); try { synchronized (scriptManager) { if (scriptEngine == null) { String classpath = System.getProperty(Strategy.CLASSPATH_PROPERTYNAME); SLF4JLoggerProxy.debug( this, "Setting classpath to {}", //$NON-NLS-1$ classpath); scriptManager.setClassPath(classpath); scriptEngine = scriptManager.loadScriptingEngine(languageString); SLF4JLoggerProxy.debug(this, "Initializing engine..."); // $NON-NLS-1$ scriptEngine.initialize(scriptManager, languageString, new Vector<Object>()); } else { SLF4JLoggerProxy.debug(this, "Reusing intialized engine..."); // $NON-NLS-1$ } } } catch (BSFException e) { StrategyModule.log( LogEventBuilder.error() .withMessage(NO_SUPPORT_FOR_LANGUAGE, languageString) .withException(e) .create(), strategy); throw new StrategyException( e, new I18NBoundMessage1P(NO_SUPPORT_FOR_LANGUAGE, languageString)); } }
protected void processFileOrScript(BSFManager mgr) throws BSFException { BSFEngine bsfEngine = mgr.loadScriptingEngine(getScriptLanguage()); final String scriptFile = getFilename(); if (scriptFile.length() == 0) { bsfEngine.exec("[script]", 0, 0, getScript()); } else { // we have a file, read and process it try { String script = FileUtils.readFileToString(new File(scriptFile)); bsfEngine.exec(scriptFile, 0, 0, script); } catch (IOException e) { log.warn(e.getLocalizedMessage()); throw new BSFException(BSFException.REASON_IO_ERROR, "Problem reading script file", e); } } }
/** Initialize the engine. */ public void initialize(final BSFManager mgr, String lang, Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); ClassLoader parent = mgr.getClassLoader(); if (parent == null) parent = GroovyShell.class.getClassLoader(); setLoader(mgr, parent); execScripts = new HashMap<Object, Class>(); evalScripts = new HashMap<Object, Class>(); context = shell.getContext(); // create a shell // register the mgr with object name "bsf" context.setVariable("bsf", new BSFFunctions(mgr, this)); int size = declaredBeans.size(); for (int i = 0; i < size; i++) { declareBean((BSFDeclaredBean) declaredBeans.elementAt(i)); } }
/** * Loads the BSF engine. * * @param engineName name of the engine * @see #getEngine() */ private void loadEngine(String engineName) throws ConfigurationException { System.out.println("Loading script engine " + engineName); try { engine = bsfManager.loadScriptingEngine(engineName.trim()); } catch (BSFException bsfEx) { String msg = "Could not find script engine " + engineName; // $NON-NLS-1$ System.err.println(msg + " " + bsfEx); throw new ConfigurationException(msg, bsfEx); } // import the initial packages for (String pkgName : scriptImportPkgList) { System.out.println("Loading package " + pkgName); importPkgToScriptEngine(pkgName); } System.out.println("Script engine " + engineName + " loaded"); }
/* (non-Javadoc) * @see org.opennms.netmgt.notifd.NotificationStrategy#send(java.util.List) */ @Override public int send(List<Argument> arguments) { m_arguments = arguments; String fileName = getFileName(); String lang = getLangClass(); String engine = getBsfEngine(); String extensions[] = getFileExtensions(); LogUtils.infof(this, "Loading notification script from file '%s'", fileName); File scriptFile = new File(fileName); BSFManager bsfManager = new BSFManager(); int returnCode = -1; try { if (lang == null) lang = BSFManager.getLangFromFilename(fileName); // Declare some beans that can be used inside the script HashMap<String, String> results = new HashMap<String, String>(); bsfManager.declareBean("results", results, HashMap.class); declareBeans(bsfManager); if (engine != null && lang != null && extensions != null && extensions.length > 0) { BSFManager.registerScriptingEngine(lang, engine, extensions); } if (scriptFile.exists() && scriptFile.canRead()) { String code = IOUtils.getStringFromReader( new InputStreamReader(new FileInputStream(scriptFile), "UTF-8")); // Check foot before firing checkAberrantScriptBehaviors(code); // Execute the script bsfManager.exec(lang, "BSFNotificationStrategy", 0, 0, code); // Check whether the script finished successfully if ("OK".equals(results.get("status"))) { LogUtils.infof( this, "Execution succeeded and successful status passed back for script '%s'", scriptFile); returnCode = 0; } else { LogUtils.warnf( this, "Execution succeeded for script '%s', but script did not indicate successful notification by putting an entry into the 'results' bean with key 'status' and value 'OK'", scriptFile); returnCode = -1; } } else { LogUtils.warnf( this, "Cannot locate or read BSF script file '%s'. Returning failure indication.", fileName); returnCode = -1; } } catch (BSFException e) { LogUtils.warnf( this, e, "Execution of script '%s' failed with BSFException: %s", scriptFile, e.getMessage()); returnCode = -1; } catch (FileNotFoundException e) { LogUtils.warnf(this, "Could not find BSF script file '%s'.", fileName); returnCode = -1; } catch (IOException e) { LogUtils.warnf( this, e, "Execution of script '%s' failed with IOException: %s", scriptFile, e.getMessage()); returnCode = -1; } catch (Throwable e) { // Catch any RuntimeException throws LogUtils.warnf( this, e, "Execution of script '%s' failed with unexpected throwable: %s", scriptFile, e.getMessage()); returnCode = -1; } finally { bsfManager.terminate(); } return returnCode; }
private void declareBeans(BSFManager bsfManager) throws BSFException { NodeDao nodeDao = Notifd.getInstance().getNodeDao(); Integer nodeId; try { nodeId = Integer.valueOf(m_notifParams.get(NotificationManager.PARAM_NODE)); } catch (NumberFormatException nfe) { nodeId = null; } OnmsNode node = null; OnmsAssetRecord assets = null; List<String> categories = new ArrayList<String>(); String nodeLabel = null; String foreignSource = null; String foreignId = null; if (nodeId != null) { node = nodeDao.get(nodeId); nodeLabel = node.getLabel(); assets = node.getAssetRecord(); for (OnmsCategory cat : node.getCategories()) { categories.add(cat.getName()); } foreignSource = node.getForeignSource(); foreignId = node.getForeignId(); } bsfManager.declareBean("bsf_notif_strategy", this, BSFNotificationStrategy.class); retrieveParams(); bsfManager.declareBean("notif_params", m_notifParams, Map.class); bsfManager.declareBean("node_label", nodeLabel, String.class); bsfManager.declareBean("foreign_source", foreignSource, String.class); bsfManager.declareBean("foreign_id", foreignId, String.class); bsfManager.declareBean("node_assets", assets, OnmsAssetRecord.class); bsfManager.declareBean("node_categories", categories, List.class); bsfManager.declareBean("node", node, OnmsNode.class); for (Argument arg : m_arguments) { if (NotificationManager.PARAM_TEXT_MSG.equals(arg.getSwitch())) bsfManager.declareBean("text_message", arg.getValue(), String.class); if (NotificationManager.PARAM_NUM_MSG.equals(arg.getSwitch())) bsfManager.declareBean("numeric_message", arg.getValue(), String.class); if (NotificationManager.PARAM_NODE.equals(arg.getSwitch())) bsfManager.declareBean("node_id", arg.getValue(), String.class); if (NotificationManager.PARAM_INTERFACE.equals(arg.getSwitch())) bsfManager.declareBean("ip_addr", arg.getValue(), String.class); if (NotificationManager.PARAM_SERVICE.equals(arg.getSwitch())) bsfManager.declareBean("svc_name", arg.getValue(), String.class); if (NotificationManager.PARAM_SUBJECT.equals(arg.getSwitch())) bsfManager.declareBean("subject", arg.getValue(), String.class); if (NotificationManager.PARAM_EMAIL.equals(arg.getSwitch())) bsfManager.declareBean("email", arg.getValue(), String.class); if (NotificationManager.PARAM_PAGER_EMAIL.equals(arg.getSwitch())) bsfManager.declareBean("pager_email", arg.getValue(), String.class); if (NotificationManager.PARAM_XMPP_ADDRESS.equals(arg.getSwitch())) bsfManager.declareBean("xmpp_address", arg.getValue(), String.class); if (NotificationManager.PARAM_TEXT_PAGER_PIN.equals(arg.getSwitch())) bsfManager.declareBean("text_pin", arg.getValue(), String.class); if (NotificationManager.PARAM_NUM_PAGER_PIN.equals(arg.getSwitch())) bsfManager.declareBean("numeric_pin", arg.getValue(), String.class); if (NotificationManager.PARAM_WORK_PHONE.equals(arg.getSwitch())) bsfManager.declareBean("work_phone", arg.getValue(), String.class); if (NotificationManager.PARAM_HOME_PHONE.equals(arg.getSwitch())) bsfManager.declareBean("home_phone", arg.getValue(), String.class); if (NotificationManager.PARAM_MOBILE_PHONE.equals(arg.getSwitch())) bsfManager.declareBean("mobile_phone", arg.getValue(), String.class); if (NotificationManager.PARAM_TUI_PIN.equals(arg.getSwitch())) bsfManager.declareBean("phone_pin", arg.getValue(), String.class); if (NotificationManager.PARAM_MICROBLOG_USERNAME.equals(arg.getSwitch())) bsfManager.declareBean("microblog_username", arg.getValue(), String.class); } }
public PNutsTagLibrary() { BSFManager.registerScriptingEngine("pnuts", "pnuts.ext.PnutsBSFEngine", new String[] {"pnut"}); setLanguage("pnuts"); }
protected void initManager(BSFManager mgr) throws BSFException { 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()); mgr.declareBean("log", logger, Logger.class); // $NON-NLS-1$ mgr.declareBean("Label", label, String.class); // $NON-NLS-1$ mgr.declareBean("FileName", fileName, String.class); // $NON-NLS-1$ mgr.declareBean("Parameters", scriptParameters, String.class); // $NON-NLS-1$ String[] args = JOrphanUtils.split(scriptParameters, " "); // $NON-NLS-1$ mgr.declareBean("args", args, args.getClass()); // $NON-NLS-1$ // Add variables for access to context and variables JMeterContext jmctx = JMeterContextService.getContext(); JMeterVariables vars = jmctx.getVariables(); Properties props = JMeterUtils.getJMeterProperties(); mgr.declareBean("ctx", jmctx, jmctx.getClass()); // $NON-NLS-1$ mgr.declareBean("vars", vars, vars.getClass()); // $NON-NLS-1$ mgr.declareBean("props", props, props.getClass()); // $NON-NLS-1$ // For use in debugging: mgr.declareBean("OUT", System.out, PrintStream.class); // $NON-NLS-1$ // Most subclasses will need these: Sampler sampler = jmctx.getCurrentSampler(); mgr.declareBean("sampler", sampler, Sampler.class); SampleResult prev = jmctx.getPreviousResult(); mgr.declareBean("prev", prev, SampleResult.class); }
/** * Evaluate the expression. * * @throws ReadDriverException * @throws BSFException */ public boolean evalExpression(String expression) throws ReadDriverException, BSFException { long rowCount = sds.getRowCount(); byte[] expressionBytes; String encoding = System.getProperty("file.encoding"); try { expressionBytes = expression.getBytes(encoding); expression = new String(expressionBytes, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } expression = expression.replaceAll("\\[", "field(\"").replaceAll("\\]", "\")"); interpreter.declareBean("ee", this, EvalExpression.class); interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def expression():\n" + " return " + expression + ""); if (rowCount > 0) { try { interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def isCorrect():\n" + " ee.isCorrectValue(expression())\n"); interpreter.exec(ExpressionFieldExtension.JYTHON, null, -1, -1, "isCorrect()"); } catch (BSFException ee) { String message = ee.getMessage(); if (message.length() > 200) { message = message.substring(0, 200); } int option = JOptionPane.showConfirmDialog( (Component) PluginServices.getMainFrame(), PluginServices.getText(this, "error_expression") + "\n" + message + "\n" + PluginServices.getText(this, "continue?")); if (option != JOptionPane.OK_OPTION) { return false; } } } ies.startComplexRow(); ArrayList exceptions = new ArrayList(); interpreter.declareBean("exceptions", exceptions, ArrayList.class); FBitSet selection = sds.getSelection(); if (selection.cardinality() > 0) { interpreter.declareBean("selection", selection, FBitSet.class); interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def p():\n" + " i=selection.nextSetBit(0)\n" + " while i >=0:\n" + " indexRow.set(i)\n" + " obj=expression()\n" + " ee.setValue(obj,i)\n" + " ee.saveEdits(i)\n" + " i=selection.nextSetBit(i+1)\n"); } else { interpreter.exec( ExpressionFieldExtension.JYTHON, null, -1, -1, "def p():\n" + " for i in xrange(" + rowCount + "):\n" + " indexRow.set(i)\n" + // " print i , expression() , repr (expression())\n" + " ee.setValue(expression(),i)\n" + " ee.saveEdits(i)\n"); } try { interpreter.eval(ExpressionFieldExtension.JYTHON, null, -1, -1, "p()"); } catch (BSFException ee) { JOptionPane.showMessageDialog( (Component) PluginServices.getMainFrame(), PluginServices.getText(this, "evaluate_expression_with_errors") + " " + (rowCount - indexRow.get()) + "\n" + ee.getMessage()); } ies.endComplexRow(PluginServices.getText(this, "expression")); return true; }
@Test public void testEval() { Configuration config = Configuration.instance(); try { config.load(); } catch (ConfigurationException ex) { ex.printStackTrace(); fail(); } BSFManager bsfManager = new BSFManager(); Integer i = new Integer(5); try { bsfManager.declareBean("i", i, Integer.class); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } BSFEngine engine = null; try { engine = bsfManager.loadScriptingEngine("BeanShell"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } assertNotNull(engine); Integer j = new Integer(7); try { bsfManager.declareBean("j", j, Integer.class); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } try { engine.exec("source", 1, 1, "a=3;\nprint(a);"); engine.exec("source", 1, 1, "a=a+1;\nprint(a);"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } try { engine.exec("source", 1, 1, "print(\"i=\"+i);"); engine.exec("source", 1, 1, "j=j*10; print(\"j=\"+j);"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } // BSFDeclaredBean toto = new BSFDeclaredBean(); // toto.beannew BSFDeclaredBean("i", i, Integer.class); ObjectRegistry registry = bsfManager.getObjectRegistry(); Object jValue = registry.lookup("j"); if (jValue != null) { System.out.println("j-value = " + jValue.toString()); } registry.register("k", new Integer(1000)); Object kValue = registry.lookup("k"); assertNotNull(kValue); System.out.println("k=" + kValue.toString()); try { engine.exec("source", 1, 1, "print(\"k=\"+k);"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } try { bsfManager.declareBean("k", kValue, Integer.class); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } try { engine.exec("source", 1, 1, "print(\"k=\"+k);"); } catch (BSFException e) { e.printStackTrace(); fail(e.getMessage()); } engine.terminate(); }