/** * Invokes a function defined in the script. * * @param funcName The function name. * @param params The parameter array. * @return A boolean value representing whether the function is executed correctly. If the * function cannot be found, or parameters don't match, {@code false} is returned. */ public boolean invokeFunction(String funcName, Object[] params) { // Run script if it is dirty. This makes sure the script is run // on the same thread as the caller (suppose the caller is always // calling from the same thread). checkDirty(); String statement = getInvokeStatement(funcName, params); Bindings localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (localBindings == null) { localBindings = mLocalEngine.createBindings(); mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE); } fillBindings(localBindings, params); try { mLocalEngine.eval(statement); } catch (ScriptException e) { return false; } finally { removeBindings(localBindings, params); } return true; }
public void testMethodIndirection() throws Exception { PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer(); ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null); Bindings bindings = engine.createBindings(); Tester tester = new Tester(); bindings.put("tester", tester); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.eval("tester.increment()"); Assert.assertEquals(tester.getInvocationCoung(), 1, "Unexpected number of tester invocations."); Map<String, Set<Method>> methods = getMethodsByName(Tester.class); for (Set<Method> ms : methods.values()) { Set<String> fns = initializer.generateIndirectionMethods("tester", ms); for (String fn : fns) { engine.eval(fn); } } engine.eval("increment()"); Assert.assertEquals( tester.getInvocationCoung(), 2, "Unexpected number of tester invocations after calling an indirected method."); }
public double[] fitfunc(double[] fitparams) { Bindings b = engine.createBindings(); for (int i = 0; i < 10; i++) b.put("P" + (i + 1), fitparams[i]); /*String script1="P1="+fitparams[0]+"; "+ "P2="+fitparams[1]+"; "+ "P3="+fitparams[2]+"; "+ "P4="+fitparams[3]+"; "+ "P5="+fitparams[4]+"; "+ "P6="+fitparams[5]+"; "+ "P7="+fitparams[6]+"; "+ "P8="+fitparams[7]+"; "+ "P9="+fitparams[8]+"; "+ "P10="+fitparams[9]+"; "+ exdef+"; x="; String script2="; retval="+function+";";*/ try { double[] temp = new double[tempx.length]; for (int i = 0; i < tempx.length; i++) { // temp[i]=((Double)engine.eval(script1+(double)tempx[i]+script2)).doubleValue(); b.put("x", tempx[i]); b.put("y", tempdata[i]); temp[i] = (Double) cs.eval(b); } return temp; } catch (Exception e) { IJ.log(e.getMessage()); return null; } }
/** Test of createBindings method, of class Jsr223JRubyEngine. */ @Test public void testCreateBindings() { logger1.info("createBindings"); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine instance = manager.getEngineByName("jruby"); Bindings bindings = instance.getBindings(ScriptContext.ENGINE_SCOPE); Bindings result = instance.createBindings(); assertNotSame(bindings, result); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
private Bindings createBindings(Entity entity, Version version) { Bindings bindings = engine.createBindings(); Set<Metric> metrics = entity.getMetrics(); for (Metric metric : metrics) { Double metricValue = entity.getMetricValue(version, metric); bindings.put(metric.getNickname(), metricValue); } return bindings; }
@Test public void testScript() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); manager.put("welcome", "hello"); // 设置全局变量 ScriptEngine engine = manager.getEngineByName("httl"); engine.put("page", "test"); // 设置引擎变量 Bindings bindings = engine.createBindings(); bindings.put("user", "liangfei"); // 设置执行变量 String result = (String) engine.eval( "#set(String welcome, String page, String user)${welcome}, ${user}, this is ${page} page."); // 执行表达式 assertEquals("hello, liangfei, this is test page.", result); }
private static Bindings createBindings( final Graph graph, final Vertex vertex, final Edge edge, final ScriptEngine scriptEngine) { final Bindings bindings = scriptEngine.createBindings(); bindings.put(GRAPH_VARIABLE, graph); if (vertex != null) { bindings.put(VERTEX_VARIABLE, vertex); } if (edge != null) { bindings.put(EDGE_VARIABLE, edge); } return bindings; }
/** * Perform mediation with static inline script of the given scripting language * * @param synCtx message context * @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; }
private ScriptManager() { dialog = new JDialog(); panel = new ScriptEditorPanel(dialog); dialog.setTitle("Script Editor - Wonderland Client"); // 2. Optional: What happens when the frame closes? dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); // 3. Create component and put them in the frame. dialog.setContentPane(panel); // 4. Size the frame. dialog.pack(); // Next, acquire the scripting magicry engineManager = new ScriptEngineManager(LoginManager.getPrimary().getClassloader()); scriptEngine = engineManager.getEngineByName("JavaScript"); scriptBindings = scriptEngine.createBindings(); // Add the necessary script bindings scriptBindings.put("Client", ClientContextJME.getClientMain()); stringToCellID = new HashMap<String, CellID>(); // Load the methods into the library ScannedClassLoader loader = LoginManager.getPrimary().getClassloader(); Iterator<ScriptMethodSPI> iter = loader.getInstances(ScriptMethod.class, ScriptMethodSPI.class); // grab all global void methods while (iter.hasNext()) { final ScriptMethodSPI method = iter.next(); addFunctionBinding(method); SwingUtilities.invokeLater( new Runnable() { public void run() { panel.addLibraryEntry(method); } }); } // grab all returnablesa Iterator<ReturnableScriptMethodSPI> returnables = loader.getInstances(ReturnableScriptMethod.class, ReturnableScriptMethodSPI.class); while (returnables.hasNext()) { ReturnableScriptMethodSPI method = returnables.next(); addFunctionBinding(method); panel.addLibraryEntry(method); } }
public Traversal.Admin<S, E> apply(final Graph graph) { try { final ScriptEngine engine = SingleGremlinScriptEngineManager.get(this.scriptEngineName); final Bindings engineBindings = engine.createBindings(); engineBindings.put("g", this.traversalSourceFactory.createTraversalSource(graph)); for (int i = 0; i < this.bindings.length; i = i + 2) { engineBindings.put((String) this.bindings[i], this.bindings[i + 1]); } final Traversal.Admin<S, E> traversal = (Traversal.Admin<S, E>) engine.eval(this.traversalScript, engineBindings); if (!traversal.isLocked()) traversal.applyStrategies(); return traversal; } catch (final ScriptException e) { throw new IllegalStateException(e.getMessage(), e); } }
/** * Executes the specified {@code script} with the {@code ScriptEngine} that is registered for * {@code language} and {@code languageVersion}. * * <p>The default {@link ScriptContext} for the {@link ScriptEngine} is used. It uses {@code * bindings} as the {@link ScriptContext#ENGINE_SCOPE} Bindings of the ScriptEngine during the * script execution. Three new attributes are added to the bindings: contentGraphProvider, * contentHandler, and tcManager. The Reader, Writer and non-ENGINE_SCOPE Bindings of the default * ScriptContext are used. The ENGINE_SCOPE Bindings of the ScriptEngine is not changed, and its * mappings are unaltered by the script execution. * * @param script The script language source to be executed. * @param bindings The Bindings of attributes to be used for script execution. * @param language The script language. It is used to determine the ScriptEngine. * @param languageVersion The version of the script language. It is used to determine the * ScriptEngine. * @return The value returned from the execution of {@code script}. * @throws ScriptException If an error occurrs in the script. * @throws NoEngineException If no engine can be found for the specified language * @see javax.script.ScriptEngine#eval(java.lang.String, javax.script.Bindings) */ public Object execute(String script, Bindings bindings, String language, String languageVersion) throws ScriptException, NoEngineException { ScriptEngine engine = getScriptEngine(language, languageVersion); if (engine == null) { logger.warn( "Cannot execute script: " + "No engine available for language {}({})", language, languageVersion); throw new NoEngineException(new ScriptLanguageDescription(language, languageVersion)); } if (bindings == null) { bindings = engine.createBindings(); } addBindings(bindings); return engine.eval(script, bindings); }
public static void main(String[] args) throws ScriptException, FileNotFoundException { // 脚本引擎管理器 // ScriptEngineManager manager = new ScriptEngineManager(); /*List<ScriptEngineFactory> list = manager.getEngineFactories(); for(ScriptEngineFactory engine : list) { System.out.println(engine.getEngineName()); }*/ // 脚本引擎管理器 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // 向引擎中添加变量绑定 engine.eval("n=1728"); Object result = engine.eval("n+1"); // 1729.0 System.out.println(result); // 获取由脚本语句绑定的变量 engine.put("k", 100); result = engine.eval("k+1"); // 101 System.out.println(result); // 除了向引擎或全局作用域添加绑定外,还可以将绑定收集到一个类型为 Bindings 的对象中, // 然后将其传递给 eval 方法: Bindings scope = engine.createBindings(); scope.put("a", "hello, "); result = engine.eval("a+ 'world!'", scope); // hello, world! System.out.println(result); // 重定向输入和输出 // 任何用 js 的 print 和 println函数产生的输出都会发送到 writer StringWriter writer = new StringWriter(); engine.getContext().setWriter(new PrintWriter(new File("com/corejava/chapter10/output.txt"))); engine.eval("print('hello world, this msg is from java app')"); }
/** * Invokes a function defined in the script. * * @param funcName The function name. * @param params The parameter array. * @return A boolean value representing whether the function is executed correctly. If the * function cannot be found, or parameters don't match, {@code false} is returned. */ public boolean invokeFunction(String funcName, Object[] params) { // Run script if it is dirty. This makes sure the script is run // on the same thread as the caller (suppose the caller is always // calling from the same thread). checkDirty(); // Skip bad functions if (isBadFunction(funcName)) { return false; } String statement = getInvokeStatementCached(funcName, params); Bindings localBindings = null; synchronized (mEngineLock) { localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (localBindings == null) { localBindings = mLocalEngine.createBindings(); mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE); } } fillBindings(localBindings, params); try { mLocalEngine.eval(statement); } catch (ScriptException e) { // The function is either undefined or throws, avoid invoking it later addBadFunction(funcName); return false; } finally { removeBindings(localBindings, params); } return true; }
@Override protected PicoContainer createContainerFromScript( final PicoContainer parentContainer, final Object assemblyScope) { Reader reader = null; ScriptEngine engine = null; final ScriptEngineManager mgr = new ScriptEngineManager(); final ClassLoader oldClassLoader = AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); final ClassLoader newClassLoader = this.getClassLoader(); try { if (applyCustomClassLoader()) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { Thread.currentThread().setContextClassLoader(newClassLoader); return null; } }); } engine = mgr.getEngineByName(engineName); if (engine == null) { final StringBuilder message = new StringBuilder( "Could not find a script engine named: '" + engineName + "' all script engines in your classpath are:\n"); for (final ScriptEngineFactory eachFactory : mgr.getEngineFactories()) { message.append( "\t Engine named '" + eachFactory.getEngineName() + "' which supports the language '" + eachFactory.getLanguageName() + "' with short names '" + Arrays.toString(eachFactory.getNames().toArray()) + "'\n"); } throw new PicoCompositionException(message.toString()); } final Bindings bindings = engine.createBindings(); bindings.put("parent", parentContainer); bindings.put("assemblyScope", assemblyScope); applyOtherBindings(bindings); reader = this.getScriptReader(); PicoContainer result = (PicoContainer) engine.eval(reader, bindings); if (result == null) { result = (PicoContainer) bindings.get("pico"); if (result == null) { // Todo: remove as a deprecated variable name result = (PicoContainer) bindings.get("nano"); if (result == null) { throw new PicoCompositionException( "Script completed successfully, but did not return any value, nor did it declare a variable named 'pico'"); } } } return result; } catch (final ClassCastException e) { throw new ScriptedPicoContainerMarkupException( "The return type of the script must be of type PicoContainer", e); } catch (final IOException e) { throw new ScriptedPicoContainerMarkupException( "IOException encountered, message -'" + e.getMessage() + "'", e); } catch (final ScriptException e) { throw new ScriptedPicoContainerMarkupException( "Error executing composition script under engine '" + engine.getFactory().getEngineName() + "'", e); } finally { if (applyCustomClassLoader()) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { Thread.currentThread().setContextClassLoader(oldClassLoader); return null; } }); } if (reader != null) { try { reader.close(); } catch (final IOException e) { // Ignore } } } }