List of usage examples for javax.script ScriptEngineManager ScriptEngineManager
public ScriptEngineManager()
ScriptEngineManager(Thread.currentThread().getContextClassLoader())
. From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java
public DownloadServiceImpl() { scriptEngineManager = new ScriptEngineManager(); }
From source file:org.siphon.d2js.jshttp.ServerUnitManager.java
protected void createEngine(D2jsInitParams initParams) throws Exception { engine = new ScriptEngineManager().getEngineByName("JavaScript"); engine.put("allD2js", allD2js); engine.put("servletContext", this.servletContext); engine.put("logger", logger); engine.put("application", initParams.getApplication()); JsEngineUtil.initEngine(engine, initParams.getLibs()); }
From source file:net.sf.keystore_explorer.utilities.net.PacProxySelector.java
private Invocable compilePacScript(String pacScript) throws PacProxyException { try {/*from w ww . j a v a2s . c om*/ ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); Invocable invocale = (Invocable) jsEngine; jsEngine.eval(pacScript); jsEngine.eval(new InputStreamReader(PacProxySelector.class.getResourceAsStream("pacUtils.js"))); return invocale; } catch (ScriptException ex) { throw new PacProxyException(res.getString("NoCompilePacScript.exception.message"), ex); } }
From source file:io.github.microcks.web.RestController.java
@RequestMapping(value = "/{service}/{version}/**") public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay, @RequestBody(required = false) String body, HttpServletRequest request) { log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version, request.getRequestURI(), request.getMethod()); log.debug("Request body: " + body); long startTime = System.currentTimeMillis(); // Extract resourcePath for matching with correct operation. String requestURI = request.getRequestURI(); String serviceAndVersion = null; String resourcePath = null;/* ww w . ja v a 2 s .c o m*/ try { // Build the encoded URI fragment to retrieve simple resourcePath. serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version; resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length()); } catch (UnsupportedEncodingException e1) { return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR); } log.info("Found resourcePath: " + resourcePath); Service service = serviceRepository.findByNameAndVersion(serviceName, version); Operation rOperation = null; for (Operation operation : service.getOperations()) { // Select operation based onto Http verb (GET, POST, PUT, etc ...) if (operation.getMethod().equals(request.getMethod().toUpperCase())) { // ... then check is we have a matching resource path. if (operation.getResourcePaths().contains(resourcePath)) { rOperation = operation; break; } } } if (rOperation != null) { log.debug("Found a valid operation {} with rules: {}", rOperation.getName(), rOperation.getDispatcherRules()); Response response = null; String uriPattern = getURIPattern(rOperation.getName()); String dispatchCriteria = null; // Depending on dispatcher, evaluate request with rules. if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) { ScriptEngineManager sem = new ScriptEngineManager(); try { // Evaluating request with script coming from operation dispatcher rules. ScriptEngine se = sem.getEngineByExtension("groovy"); SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request); dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules()); } catch (Exception e) { log.error("Error during Script evaluation", e); } } // New cases related to services/operations/messages coming from a postman collection file. else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) { String fullURI = request.getRequestURL() + "?" + request.getQueryString(); dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(), fullURI); } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); String fullURI = request.getRequestURL() + "?" + request.getQueryString(); dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(), fullURI); } log.debug("Dispatch criteria for finding response is {}", dispatchCriteria); List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria( IdBuilder.buildOperationId(service, rOperation), dispatchCriteria); if (!responses.isEmpty()) { response = responses.get(0); } if (response != null) { // Setting delay to default one if not set. if (delay == null && rOperation.getDefaultDelay() != null) { delay = rOperation.getDefaultDelay(); } if (delay != null && delay > -1) { log.debug("Mock delay is turned on, waiting if necessary..."); long duration = System.currentTimeMillis() - startTime; if (duration < delay) { Object semaphore = new Object(); synchronized (semaphore) { try { semaphore.wait(delay - duration); } catch (Exception e) { log.debug("Delay semaphore was interrupted"); } } } log.debug("Delay now expired, releasing response !"); } // Publish an invocation event before returning. MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version, response.getName(), new Date(startTime), startTime - System.currentTimeMillis()); applicationContext.publishEvent(event); log.debug("Mock invocation event has been published"); HttpStatus status = (response.getStatus() != null ? HttpStatus.valueOf(Integer.parseInt(response.getStatus())) : HttpStatus.OK); // Deal with specific headers (content-type and redirect directive). HttpHeaders responseHeaders = new HttpHeaders(); if (response.getMediaType() != null) { responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8")); } // Adding other generic headers (caching directives and so on...) if (response.getHeaders() != null) { for (Header header : response.getHeaders()) { if ("Location".equals(header.getName())) { // We should process location in order to make relative URI specified an absolute one from // the client perspective. String location = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/rest" + serviceAndVersion + header.getValues().iterator().next(); responseHeaders.add(header.getName(), location); } else { if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) { responseHeaders.put(header.getName(), new ArrayList<>(header.getValues())); } } } } return new ResponseEntity<Object>(response.getContent(), responseHeaders, status); } return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<Object>(HttpStatus.NOT_FOUND); }
From source file:com.intuit.tank.script.LogicStepEditor.java
public void testScript() { StringOutputLogger outputLogger = new StringOutputLogger(); Map<String, Object> inputs = new HashMap<String, Object>(); Variables vars = new Variables(); for (Entry<String, String> entry : logicTestData.getVariables()) { vars.addVariable(entry.getKey(), entry.getValue()); }//from ww w .j a va 2 s. co m inputs.put("variables", vars); inputs.put("request", createRequest()); inputs.put("response", createResponse()); try { String scriptToRun = new LogicScriptUtil().buildScript(script); logMap("Variables", vars.getVaribleValues(), outputLogger); outputLogger.logLine(DASHES + " script " + DASHES); ScriptIOBean ioBean = new ScriptRunner().runScript(name, scriptToRun, new ScriptEngineManager().getEngineByExtension("js"), inputs, outputLogger); logMap("Outputs", ioBean.getOutputs(), outputLogger); logMap("Variables", vars.getVaribleValues(), outputLogger); } catch (Exception e) { outputLogger.logLine("\nException thrown: " + e); } this.output = outputLogger.getOutput(); }
From source file:io.stallion.tools.ScriptExecBase.java
public void executeJavascript(String source, URL url, String scriptPath, String folder, List<String> args, String plugin) throws Exception { ScriptEngine scriptEngine = null; if (plugin.equals("js") || plugin.equals("stallion")) { JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine("main.js"); if (pluginEngine != null) { scriptEngine = pluginEngine.getScriptEngine(); }//from w w w .j a va2s . com } else if (!empty(plugin)) { JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine(plugin); if (pluginEngine != null) { scriptEngine = pluginEngine.getScriptEngine(); } } if (scriptEngine == null) { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = scriptEngineManager.getEngineByName("nashorn"); scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/jvm-npm.js"), UTF8)); scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/stallion_shared.js"), UTF8)); String nodePath = folder + "/node_modules"; scriptEngine.eval("require.NODE_PATH = \"" + nodePath + "\""); scriptEngine.put("myContext", new SandboxedContext(plugin, Sandbox.allPermissions(), new JsPluginSettings())); } if (true || newCommandOptions().isDevMode()) { Scanner in = new Scanner(System.in); while (true) { source = IOUtils.toString(url, UTF8); try { scriptEngine.eval("load(" + JSON.stringify(map(val("script", source), val("name", url.toString()))) + ");"); //scriptEngine.eval(IOUtils.) } catch (Exception e) { ExceptionUtils.printRootCauseStackTrace(e); } finally { } System.out.println("Hit enter to re-run the script. Type quit and hit enter to stop."); String line = in.nextLine().trim(); if (empty(line)) { continue; } else { break; } } } else { scriptEngine.eval(source); } }
From source file:de.ingrid.interfaces.csw.index.impl.ScriptedIDFRecordLuceneMapper.java
/** * Load mapping script from filesystem and compile it if needed. This is * only done once when data is being indexed. */// w ww. j av a 2s . c o m @Override public void init() { // read mapping file from disk if (configurationProvider != null) { this.mappingScript = configurationProvider.getMappingScript(); } // also compile it again (just once per index generation) String scriptName = this.mappingScript.getName(); String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length()); ScriptEngineManager mgr = new ScriptEngineManager(); this.engine = mgr.getEngineByExtension(extension); if (this.engine instanceof Compilable) { Compilable compilable = (Compilable) this.engine; try { this.compiledScript = compilable .compile(new InputStreamReader(new FileInputStream(this.mappingScript))); } catch (FileNotFoundException ex) { log.error("Mapping script was not found!", ex); } catch (ScriptException ex) { log.error("Error compiling mapping script!", ex); } } }
From source file:org.archive.modules.deciderules.ScriptedDecideRule.java
/** * Create a new ScriptEngine instance, preloaded with any supplied * source file and the variables 'self' (this ScriptedDecideRule) * and 'context' (the ApplicationContext). * /*ww w.j a va 2s . co m*/ * @return the new Interpreter instance */ protected ScriptEngine newEngine() { ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName); interpreter.put("self", this); interpreter.put("context", appCtx); Reader reader = null; try { reader = getScriptSource().obtainReader(); interpreter.eval(reader); } catch (ScriptException e) { logger.log(Level.SEVERE, "script problem", e); } finally { IOUtils.closeQuietly(reader); } return interpreter; }
From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java
private String extractKey(String jk) throws ScriptException { final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine scriptEngine = scriptEngineManager.getEngineByMimeType("text/javascript"); scriptEngine.eval(jk + "\nvar result = f();"); return scriptEngine.get("result").toString(); }
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;//from 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); } }