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: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;/*from www . j a va 2s .c om*/ 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:org.metamorphosis.core.ModuleManager.java
public Object buildAction(String url) throws Exception { Module module = getCurrentModule();//from w w w .j a v a 2 s .c o m if (module != null) { Action action = module.getAction(url); if (action != null && action.getScript() != null) { File script = new File(module.getFolder() + "/scripts/" + action.getScript()); if (script.exists()) { String name = script.getName(); String extension = name.substring(name.indexOf(".") + 1); ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(extension); return engine.eval(new FileReader(script)); } } } return null; }
From source file:de.hasait.genesis.scriptgen.ScriptGenProcessor.java
private void processScriptGen(final ScriptGen pScriptGenAnnotation, final GeneratorEnv pGeneratorEnv) throws Exception { final String scriptResourcePath = pScriptGenAnnotation.script(); if (StringUtils.isBlank(scriptResourcePath)) { pGeneratorEnv.printError("Parameter \"script\" must not be blank"); return;// w w w .j a v a2s .c om } final ClassLoader classLoader = getClass().getClassLoader(); URL scriptFileURL = classLoader.getResource(scriptResourcePath); if (scriptFileURL == null) { for (final String scriptLocationString : _locations) { scriptFileURL = classLoader.getResource(scriptLocationString + "/" + scriptResourcePath); if (scriptFileURL != null) { break; } } } if (scriptFileURL == null) { pGeneratorEnv.printError("Script \"%s\" not found", scriptResourcePath); return; } final int indexOfDot = scriptResourcePath.indexOf('.'); if (indexOfDot <= 1) { pGeneratorEnv.printError("Script name \"%s\" must have an extension", scriptResourcePath); return; } final String scriptFileExtension = scriptResourcePath.substring(indexOfDot + 1); final ScriptEngine engine = determineScriptEngine(scriptFileExtension, classLoader); if (engine == null) { pGeneratorEnv.printError("Script extension \"%s\" unsupported", scriptFileExtension); return; } try (InputStream scriptFileIn = scriptFileURL.openStream(); Reader scriptFileR = new InputStreamReader(scriptFileIn)) { engine.eval(scriptFileR); final ScriptEnv scriptEnv = new ScriptEnv(pGeneratorEnv, scriptFileURL, pScriptGenAnnotation.args()); ((Invocable) engine).invokeFunction("generate", scriptEnv); } }
From source file:org.okj.im.model.Member.java
/** * QQ//from w w w . j a v a 2 s . c om * @return */ public String getEncodePassword(AuthToken token) { if (StringUtils.isNotBlank(account.getPassword())) { InputStream in = null; try { in = ClassLoaderUtils.getResourceAsStream("encodePass.js", this.getClass()); Reader inreader = new InputStreamReader(in); ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine se = m.getEngineByName("javascript"); se.eval(inreader); Object t = se .eval("passwordEncoding(\"" + account.getPassword() + "\",\"" + token.getVerifycodeHex() + "\",\"" + StringUtils.upperCase(token.getVerifycode()) + "\");"); return t.toString(); } catch (Exception ex) { LogUtils.error(LOGGER, "", ex); } return account.getPassword(); } return account.getPassword(); }
From source file:net.mindengine.galen.suite.actions.GalenPageActionRunJavascript.java
@Override public List<ValidationError> execute(Browser browser, GalenPageTest pageTest, ValidationListener validationListener) throws Exception { File file = GalenUtils.findFile(javascriptPath); Reader scriptFileReader = new FileReader(file); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); ScriptContext context = engine.getContext(); context.setAttribute("name", "JavaScript", ScriptContext.ENGINE_SCOPE); engine.put("global", new ScriptExecutor(engine, file.getParent())); engine.put("browser", browser); provideWrappedWebDriver(engine, browser); importAllMajorClasses(engine);// ww w . j a v a 2 s. co m engine.eval("var arg = " + jsonArguments); engine.eval(scriptFileReader); return NO_ERRORS; }
From source file:org.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java
@Override public String[] findPacProxies(String url) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); ScriptContext context = new SimpleScriptContext(); engine.setContext(context); // set as default context, for invokeFunctino SimpleBindings bindings = new SimpleBindings(); context.setBindings(bindings, ScriptContext.ENGINE_SCOPE); try {/*from ww w .j a va2 s.c o m*/ // Register internet functions as Java upcalls engine.eval("var NashornProxyPacResolver = Java.type('" + getClass().getName() + "');" + "var dnsResolve = NashornProxyPacResolver.dnsResolve;" + "var myIpAddress = NashornProxyPacResolver.myIpAddress"); // Register others pac methods engine.eval(getFileReader(PAC_FUNCTIONS_FILE)); // Register remote pac function engine.eval(getRemotePacBodyReader()); // Call and return pac resolution function String proxies = (String) ((Invocable) engine).invokeFunction(EXEC_PAC_FUNC, url, getHost(url)); return proxies.split(";"); } catch (IOException | ScriptException | NoSuchMethodException e) { log.warn(e, e); } return null; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testGroovy() throws ScriptException { String engineName = "groovy"; ScriptEngineManager mgr = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = mgr.getEngineByName(engineName); assertNotNull("Can't find engine '" + engineName + "'", engine); ScriptEngineFactory sef = engine.getFactory(); System.out.println("FACTORY for " + engineName + ": " + "'" + sef.getEngineName() + "' " + "'" + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' "); // evaluate code from String engine.eval("println \"hello, groovy\""); }
From source file:com.amalto.core.util.Util.java
public static void updateUserPropertyCondition(List conditions, String userXML) { for (int i = conditions.size() - 1; i >= 0; i--) { if (conditions.get(i) instanceof WhereCondition) { WhereCondition condition = (WhereCondition) conditions.get(i); if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0 && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) { String rightCondition = condition.getRightValueOrPath(); String userExpression = rightCondition.substring(rightCondition.indexOf("{") + 1, //$NON-NLS-1$ rightCondition.indexOf("}"));//$NON-NLS-1$ try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Groovy engine evaluating " + userExpression + ".");//$NON-NLS-1$ //$NON-NLS-2$ }/*from w w w. j a va2 s .co m*/ ScriptEngine scriptEngine = SCRIPT_FACTORY.getEngineByName("groovy"); //$NON-NLS-1$ User user = User.parse(userXML); scriptEngine.put("user_context", user);//$NON-NLS-1$ Object expressionValue = scriptEngine.eval(userExpression); if (expressionValue != null) { String result = String.valueOf(expressionValue); if (!"".equals(result.trim())) { condition.setRightValueOrPath(result); } else { conditions.remove(i); } } else { conditions.remove(i); } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(e.getMessage(), e); } LOGGER.warn("No such property " + userExpression); conditions.remove(i); } } } } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldLoadImports() throws Exception { final ScriptEngine engineNoImports = new GremlinGroovyScriptEngine( (CompilerCustomizerProvider) NoImportCustomizerProvider.INSTANCE); try {// www . j a v a 2 s . c o m engineNoImports.eval("Vertex.class.getName()"); fail("Should have thrown an exception because no imports were supplied"); } catch (Exception se) { assertTrue(se instanceof ScriptException); } final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine( (CompilerCustomizerProvider) new DefaultImportCustomizerProvider()); engineWithImports.put("g", g); assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()")); assertEquals(2l, engineWithImports.eval("g.V().has('age',gt(30)).count().next()")); assertEquals(Direction.IN, engineWithImports.eval("Direction.IN")); assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT")); assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH")); }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testGetEngineByExt() throws ScriptException { String engineExt = "js"; ScriptEngineManager mgr = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = mgr.getEngineByExtension(engineExt); assertNotNull("Can't find engine '" + engineExt + "'", engine); ScriptEngineFactory sef = engine.getFactory(); System.out.println("FACTORY for " + engineExt + ": " + "'" + sef.getEngineName() + "' " + "'" + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' "); // evaluate JavaScript code from String engine.eval("print('Hello, World')"); }