List of usage examples for javax.script ScriptEngine eval
public Object eval(Reader reader) throws ScriptException;
eval(String)
except that the source of the script is provided as a Reader
From source file:org.rhq.enterprise.server.plugins.alertCli.CliSender.java
public SenderResult send(Alert alert) { SenderResult result = new SenderResult(); BufferedReader reader = null; ScriptEngine engine = null;/*from w w w . jav a 2 s . c o m*/ Subject subjectWithSession = null; final SessionManager sessionManager = SessionManager.getInstance(); try { final Config config = getConfig(); // simulate the login by getting a session ID config.subject = sessionManager.put(config.subject, pluginComponent.getScriptTimeout() * 1000); subjectWithSession = config.subject; result.setSummary(createSummary(config, SUMMARY_TEMPLATE)); ByteArrayOutputStream scriptOutputStream = new ByteArrayOutputStream(); PrintWriter scriptOut = new PrintWriter(scriptOutputStream); engine = getScriptEngine(alert, scriptOut, config); InputStream packageBits = getPackageBits(config.packageId, config.repoId); reader = new BufferedReader(new InputStreamReader(packageBits)); final BufferedReader rdr = reader; final ExceptionHolder exceptionHolder = new ExceptionHolder(); final ScriptEngine e = engine; Thread scriptRunner = new Thread(new Runnable() { @Override public void run() { try { e.eval(rdr); } catch (ScriptException e) { exceptionHolder.scriptException = e; } catch (Throwable e) { exceptionHolder.throwable = e; } } }, "Script Runner for alert " + alert); scriptRunner.setDaemon(true); scriptRunner.start(); if (pluginComponent.getScriptTimeout() <= 0) { scriptRunner.join(); } else { scriptRunner.join(pluginComponent.getScriptTimeout() * 1000); } scriptRunner.interrupt(); if (exceptionHolder.scriptException != null) { LOG.info("The script execution for CLI notification of alert [" + alert + "] failed.", exceptionHolder.scriptException); //make things pretty for the UI ScriptEngineInitializer initializer = ScriptEngineFactory.getInitializer(ENGINE_NAME); String message = initializer.extractUserFriendlyErrorMessage(exceptionHolder.scriptException); int col = exceptionHolder.scriptException.getColumnNumber(); int line = exceptionHolder.scriptException.getLineNumber(); String scriptName = createSummary(config, "script $packageName ($packageVersion) in repo $repoName"); throw new ScriptException(message, scriptName, line, col); } else if (exceptionHolder.throwable != null) { LOG.info("The script execution for CLI notification of alert [" + alert + "] failed.", exceptionHolder.throwable); throw exceptionHolder.throwable; } scriptOut.flush(); String scriptOutput = scriptOutputStream.toString(Charset.defaultCharset().name()); if (scriptOutput.length() == 0) { scriptOutput = "Script generated no output."; } if (scriptOutput.length() > remainingResultSize(result)) { scriptOutput = scriptOutput.substring(0, remainingResultSize(result)); } result.addSuccessMessage(scriptOutput); return result; } catch (IllegalArgumentException e) { return SenderResult.getSimpleFailure(e.getMessage()); //well, let's just hope the message doesn't exceed 4k. } catch (Throwable e) { result.addFailureMessage(ThrowableUtil.getAllMessages(e, true, remainingResultSize(result))); return result; } finally { if (subjectWithSession != null) { sessionManager.invalidate(subjectWithSession.getSessionId()); } if (engine != null) { returnEngine(engine); } if (reader != null) { try { reader.close(); } catch (IOException e) { LOG.error("Failed to close the script reader.", e); } } } }
From source file:org.quackbot.hooks.loaders.JSHookLoader.java
protected void evalResource(ScriptEngine jsEngine, Map<String, String> sourceMap, String fileLocation) throws QuackbotException { BufferedReader reader = null; try {//w w w. j a v a2s . co m InputStream stream = getClass().getClassLoader().getResourceAsStream(fileLocation); if (stream == null) //Try opening it as a file reader = new BufferedReader(new FileReader(fileLocation)); else reader = new BufferedReader(new InputStreamReader(stream)); jsEngine.eval(reader); //Dump contents StringBuilder contentBuilder = new StringBuilder(); String curLine = ""; while ((curLine = reader.readLine()) != null) contentBuilder.append(curLine); sourceMap.put(fileLocation, contentBuilder.toString()); } catch (Exception e) { throw new QuackbotException("Can't load Javascript file at " + fileLocation, e); } }
From source file:com.seajas.search.contender.scripting.FeedScriptsTestBase.java
/** * Evaluates the script.//from w w w . j ava 2 s.co m */ protected SyndFeed run(final String feedUri, final String scriptFile) throws Exception { final ScriptEngine engine = engineManager.getEngineByMimeType("text/javascript"); injectionService = new MockInjectionService(); subject = new FeedScriptEvaluation(new WebResolverSettings()); subject.setScriptResolver(new ScriptCacheResolver<FeedScript>() { @Override public FeedScript resolve(final Bindings bindings) throws ScriptException { try { for (Map.Entry<String, Object> entry : bindings.entrySet()) engine.put(entry.getKey(), entry.getValue()); engine.eval(readFileToString(new File("src/main/scripts/feed/" + scriptFile), "UTF-8")); return ((Invocable) engine).getInterface(FeedScript.class); } catch (IOException e) { throw new IllegalArgumentException("Invalid script", e); } } }); if (scriptFile.endsWith(".js")) subject.setEngine(engine); else throw new IllegalArgumentException("Unknown script file extension."); subject.setFeedContent(samples.values().iterator().next()); subject.setWebPages(new WebPages()); subject.setWebResolver(new WebResolver() { @Override public String retrieveText(URI resource) { return samples.get(resource.toString()); } }); subject.setFeedURI(new URI(feedUri)); subject.setCacheResolver(new FeedScriptCacheResolver() { @Override public boolean isCached(String resource) { return false; } }); subject.setInjectionService(injectionService); subject.init(); subject.run(); SyndFeed feed = subject.getFeed(); assertNotNull("feed", feed); // The validated feed must be serializable: SyndFeed result = (SyndFeed) feed.clone(); WebFeeds.validate(result, new URI(feedUri)); new SyndFeedOutput().outputString(result, true); return feed; }
From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the Sass Compilation Ruby Script. * * @param sassScript//from w w w.java 2 s . com * the sass script * @throws MojoExecutionException * the mojo execution exception * @throws MojoFailureException * the mojo failure exception */ protected void executeSassScript(final String sassScript) throws MojoExecutionException, MojoFailureException { if (this.skip) { return; } final Log log = this.getLog(); System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe"); log.debug("Execute Sass Ruby script:\n\n" + sassScript + "\n\n"); final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby"); try { final CompilerCallback compilerCallback = new CompilerCallback(log); jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback); jruby.eval(sassScript); if (this.failOnError && compilerCallback.hadError()) { throw new MojoFailureException("Sass compilation encountered errors (see above for details)."); } } catch (final ScriptException e) { throw new MojoExecutionException("Failed to execute Sass ruby script:\n" + sassScript, e); } log.debug("\n"); }
From source file:mrf.Graficar.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); ArrayList<Integer> Datosx = new ArrayList<Integer>(); ArrayList<Double> Datosy = new ArrayList<Double>(); int in = Integer.parseInt(jTextField2.getText()); int sup = Integer.parseInt(jTextField3.getText()); try {/* ww w. ja va 2 s . c om*/ XYSeries series = new XYSeries(""); int inferior = in, superior = sup; while (inferior <= superior) { Datosx.add(inferior); engine.put("X", inferior); String a = jTextField1.getText(); Object operation = engine.eval(a); Datosy.add(Double.parseDouble("" + operation)); jTextArea1.append("Parejas ordenadas " + inferior + ":" + operation + "\n"); series.add(inferior, Double.parseDouble("" + operation)); inferior++; } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart("Grafica del polinomio ingresado", // Ttulo "Eje x", // Etiqueta Coordenada X "Eje y", // Etiqueta Coordenada Y dataset, // Datos PlotOrientation.VERTICAL, true, // Muestra la leyenda de los productos (Producto A) false, false); // Mostramos la grafica en pantalla ChartFrame frame = new ChartFrame("GRAFICA POLINOMIO", chart); frame.pack(); frame.setVisible(true); } catch (ScriptException e) { e.printStackTrace(); } }
From source file:org.rhq.bindings.ScriptEngineFactory.java
/** * Goes through the methods of the object found in the <code>scriptEngine</code>'s ENGINE_SCOPE * and for each of them generates a top-level function that is called the same name and accepts the same * parameters./* w ww . j ava 2 s. com*/ * * @param scriptEngine the script engine to generate the top-level functions in * @param bindingName the name of the object in the script engine to generate the functions from * * @see ScriptEngineInitializer#generateIndirectionMethod(String, Method) * @see NoTopLevelIndirection */ public static void bindIndirectionMethods(ScriptEngine scriptEngine, String bindingName) { Object object = scriptEngine.get(bindingName); if (object == null) { LOG.debug("The script engine doesn't contain a binding called '" + bindingName + "'. No indirection functions will be generated."); return; } ScriptEngineInitializer initializer = getInitializer(scriptEngine.getFactory().getLanguageName()); try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), Object.class); MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors(); Map<String, Set<Method>> overloadsPerMethodName = new HashMap<String, Set<Method>>(); for (MethodDescriptor methodDescriptor : methodDescriptors) { Method method = methodDescriptor.getMethod(); if (shouldIndirect(method)) { Set<Method> overloads = overloadsPerMethodName.get(method.getName()); if (overloads == null) { overloads = new HashSet<Method>(); overloadsPerMethodName.put(method.getName(), overloads); } overloads.add(method); } } for (Set<Method> overloads : overloadsPerMethodName.values()) { Set<String> methodDefs = initializer.generateIndirectionMethods(bindingName, overloads); for (String methodDef : methodDefs) { try { scriptEngine.eval(methodDef); } catch (ScriptException e) { LOG.warn("Unable to define global function declared as:\n" + methodDef, e); } } } } catch (IntrospectionException e) { LOG.debug("Could not inspect class " + object.getClass().getName() + ". No indirection methods for variable '" + bindingName + "' will be generated.", e); } }
From source file:com.intuit.karate.Script.java
public static ScriptValue evalInNashorn(String exp, ScriptContext context, ScriptValue selfValue, ScriptValue parentValue) {// ww w . j av a 2s . c o m ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine nashorn = manager.getEngineByName("nashorn"); Bindings bindings = nashorn.getBindings(javax.script.ScriptContext.ENGINE_SCOPE); if (context != null) { Map<String, Object> map = context.getVariableBindings(); for (Map.Entry<String, Object> entry : map.entrySet()) { bindings.put(entry.getKey(), entry.getValue()); } bindings.put(ScriptContext.KARATE_NAME, new ScriptBridge(context)); } if (selfValue != null) { bindings.put(VAR_SELF, selfValue.getValue()); } if (parentValue != null) { bindings.put(VAR_DOLLAR, parentValue.getAfterConvertingFromJsonOrXmlIfNeeded()); } try { Object o = nashorn.eval(exp); ScriptValue result = new ScriptValue(o); logger.trace("nashorn returned: {}", result); return result; } catch (Exception e) { throw new RuntimeException("script failed: " + exp, e); } }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testLoop() throws ScriptException { String engineName = "groovy"; ScriptEngine foundEngine = null; // create a script engine manager ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> factories = mgr.getEngineFactories(); System.out.println("FOUND " + factories.size() + " factories"); for (ScriptEngineFactory sef : factories) { System.out.println("FACTORY: " + "'" + sef.getEngineName() + "' " + "'" + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' "); if (sef.getEngineName().contains(engineName)) { foundEngine = sef.getScriptEngine(); }/* w ww. j a v a 2 s.c o m*/ } assertNotNull("Can't find engine '" + engineName + "'", foundEngine); foundEngine.eval("print('Hello, World')"); }
From source file:com.esri.gpt.catalog.search.SearchEngineRest.java
@Override public void doSearch() throws SearchException { Exception ex = null;//w w w. j a v a2s . co m try { URI uri = this.getConnectionUri(); URL url = uri.toURL(); HttpClientRequest clientRequest = HttpClientRequest.newRequest(HttpClientRequest.MethodName.GET, url.toExternalForm()); clientRequest.setConnectionTimeMs(getConnectionTimeoutMs()); clientRequest.setResponseTimeOutMs(getResponseTimeoutMs()); Map map = (Map) this.getRequestContext().extractFromSession(SEARCH_CREDENTIAL_MAP); if (map != null) { CredentialProvider credProvider = (CredentialProvider) map.get(this.getKey()); if (credProvider != null) { clientRequest.setCredentialProvider(credProvider); } } clientRequest.execute(); String response = clientRequest.readResponseAsCharacters(); InputStream is = null; try { SearchXslProfile profile = this.readXslProfile(); String js = Val.chkStr(profile.getResponsexslt()); //String js = Val.chkStr(this.getFactoryAttributes().get("searchResponseJsT")); String xml = null; if (js.toLowerCase().endsWith(".js")) { try { ResourcePath rPath = new ResourcePath(); URL fileUrl = rPath.makeUrl(js); is = fileUrl.openStream(); String jsTransFile = IOUtils.toString(is, "UTF-8"); jsTransFile = "var jsGptInput =" + response + ";" + jsTransFile; HttpServletRequest servletRequest = (HttpServletRequest) this.getRequestContext() .getServletRequest(); if (servletRequest != null) { jsTransFile = "var jsGptQueryString = '" + servletRequest.getQueryString() + "';" + jsTransFile; } jsTransFile = "var jsGptEndpointSearchQuery = '" + url.toExternalForm() + "';" + jsTransFile; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); //manager.put("jsGptInput", response); Object obj = engine.eval(jsTransFile); xml = obj.toString(); parseResponse(xml);// has to work before the finally. dont move } catch (Exception e) { throw new SearchException( e.getMessage() + ":" + "Error when doing transformation from javascript", e); } } else { xml = XmlIoUtil.jsonToXml(response, "gptJsonXml"); parseResponse(xml); } checkPagination(); } catch (SearchException e) { throw e; } catch (Exception e) { parseResponse(response); checkPagination(); } finally { if (is != null) { IOUtils.closeQuietly(is); } } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } finally { } if (ex != null) { throw new SearchException(ex.getMessage() + ": Could not perform search", ex); } }
From source file:com.github.safrain.remotegsh.server.RgshFilter.java
private void performShellExecute(HttpServletRequest request, HttpServletResponse response) throws IOException { ShellSession session = getSession(request.getParameter("sid")); if (session == null) { response.setStatus(410);// Http status GONE return;/* ww w. j av a 2 s . com*/ } ScriptEngine engine = session.getEngine(); String action = request.getParameter("action"); if (action == null) { StringWriter responseWriter = new StringWriter(); engine.getContext().setWriter(responseWriter); engine.getContext().setErrorWriter(response.getWriter()); String script = toString(request.getInputStream(), charset); JSONObject json = new JSONObject(); try { try { Object result = engine.eval(script); json.put("result", String.valueOf(result)); response.setStatus(200); json.put("response", responseWriter.getBuffer().toString()); } catch (ScriptException e) { log.log(Level.SEVERE, "Error while running shell command:" + script, e); response.setStatus(500); e.getCause().printStackTrace(response.getWriter()); return; } } catch (JSONException e) { log.log(Level.SEVERE, "Error while running shell command:" + script, e); response.setStatus(500); e.printStackTrace(response.getWriter()); return; } response.getWriter().write(json.toString()); } else { Invocable invocable = (Invocable) engine; try { invocable.invokeFunction("shellAction", action); } catch (ScriptException e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } catch (NoSuchMethodException e) { response.setStatus(500); response.getWriter().println("Action not supported"); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } } }