List of usage examples for javax.script Bindings put
public Object put(String name, Object value);
From source file:org.apache.ranger.plugin.conditionevaluator.RangerScriptConditionEvaluator.java
@Override public boolean isMatched(RangerAccessRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("==> RangerScriptConditionEvaluator.isMatched()"); }/*from w ww. jav a 2 s .c om*/ boolean result = true; if (scriptEngine != null) { String script = getScript(); if (StringUtils.isNotBlank(script)) { RangerAccessRequest readOnlyRequest = request.getReadOnlyCopy(); RangerScriptExecutionContext context = new RangerScriptExecutionContext(readOnlyRequest); Bindings bindings = scriptEngine.createBindings(); bindings.put("ctx", context); if (LOG.isDebugEnabled()) { LOG.debug("RangerScriptConditionEvaluator.isMatched(): script={" + script + "}"); } try { Object ret = scriptEngine.eval(script, bindings); if (ret == null) { ret = context.getResult(); } if (ret instanceof Boolean) { result = (Boolean) ret; } } catch (NullPointerException nullp) { LOG.error("RangerScriptConditionEvaluator.isMatched(): eval called with NULL argument(s)"); } catch (ScriptException exception) { LOG.error("RangerScriptConditionEvaluator.isMatched(): failed to evaluate script," + " exception=" + exception); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== RangerScriptConditionEvaluator.isMatched(), result=" + result); } return result; }
From source file:org.apache.jmeter.functions.Groovy.java
/** {@inheritDoc} */ @Override// w ww .j av a 2 s. c o m public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, 1, 2); values = parameters.toArray(); scriptEngine = JSR223TestElement.getInstance().getEngineByName(GROOVY_ENGINE_NAME); //$NON-NLS-N$ String fileName = JMeterUtils.getProperty(INIT_FILE); if (!StringUtils.isEmpty(fileName)) { File file = new File(fileName); if (!(file.exists() && file.canRead())) { // File maybe relative to JMeter home File oldFile = file; file = new File(JMeterUtils.getJMeterHome(), fileName); if (!(file.exists() && file.canRead())) { throw new InvalidVariableException("Cannot read file, neither from:" + oldFile.getAbsolutePath() + ", nor from:" + file.getAbsolutePath() + ", check property '" + INIT_FILE + "'"); } } try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) { Bindings bindings = scriptEngine.createBindings(); bindings.put("log", log); scriptEngine.eval(reader, bindings); } catch (Exception ex) { throw new InvalidVariableException("Failed loading script:" + file.getAbsolutePath(), ex); } } }
From source file:de.ingrid.iplug.dscmapclient.index.mapper.ScriptedWmsDocumentMapper.java
@Override public ElasticDocument map(SourceRecord record, ElasticDocument doc) throws Exception { if (mappingScript == null) { log.error("Mapping script is not set!"); throw new IllegalArgumentException("Mapping script is not set!"); }/*from www. j ava2 s .co m*/ try { if (engine == null) { String scriptName = mappingScript.getFilename(); String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length()); ScriptEngineManager mgr = new ScriptEngineManager(); engine = mgr.getEngineByExtension(extension); if (compile) { if (engine instanceof Compilable) { Compilable compilable = (Compilable) engine; compiledScript = compilable.compile(new InputStreamReader(mappingScript.getInputStream())); } } } // create utils for script CapabilitiesUtils capabilitiesUtils = new CapabilitiesUtils(); capabilitiesUtils.setUrlStr((String) record.get(SourceRecord.ID)); if (log.isDebugEnabled()) { log.debug("Requesting " + capabilitiesUtils.getUrlStr()); } org.w3c.dom.Document wmsDoc = capabilitiesUtils.requestCaps(); // we check for null and return -> NO Exception, so oncoming URLs are processed if (wmsDoc == null) { log.warn("!!! Problems requesting " + capabilitiesUtils.getUrlStr() + " !!! We return null Document so will not be indexed !"); return null; } //we put the xmlDoc(WMS doc) into the record and thereby pass it to the idf-mapper record.put("WmsDoc", wmsDoc); IndexUtils idxUtils = new IndexUtils(doc); XPathUtils xPathUtils = new XPathUtils(new IDFNamespaceContext()); Bindings bindings = engine.createBindings(); bindings.put("wmsDoc", wmsDoc); bindings.put("log", log); bindings.put("CAP", capabilitiesUtils); bindings.put("IDX", idxUtils); bindings.put("XPATH", xPathUtils); bindings.put("javaVersion", System.getProperty("java.version")); if (compiledScript != null) { compiledScript.eval(bindings); } else { engine.eval(new InputStreamReader(mappingScript.getInputStream()), bindings); } return doc; } catch (Exception e) { log.error("Error mapping source record to lucene document.", e); e.printStackTrace(); throw e; } }
From source file:org.jahia.modules.googleAnalytics.GoogleAnalyticsFilter.java
@Override public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain) throws Exception { String out = previousOut;/*w ww .ja va 2 s. c om*/ String webPropertyID = renderContext.getSite().hasProperty("webPropertyID") ? renderContext.getSite().getProperty("webPropertyID").getString() : null; if (StringUtils.isNotEmpty(webPropertyID)) { String script = getResolvedTemplate(); if (script != null) { Source source = new Source(previousOut); OutputDocument outputDocument = new OutputDocument(source); List<Element> headElementList = source.getAllElements(HTMLElementName.HEAD); for (Element element : headElementList) { final EndTag headEndTag = element.getEndTag(); String extension = StringUtils.substringAfterLast(template, "."); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension); ScriptContext scriptContext = new GoogleScriptContext(); final Bindings bindings = scriptEngine.createBindings(); bindings.put("webPropertyID", webPropertyID); String url = resource.getNode().getUrl(); if (renderContext.getRequest().getAttribute("analytics-path") != null) { url = (String) renderContext.getRequest().getAttribute("analytics-path"); } bindings.put("resourceUrl", url); bindings.put("resource", resource); bindings.put("gaMap", renderContext.getRequest().getAttribute("gaMap")); scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptEngine.eval(script, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); final String googleAnalyticsScript = writer.toString(); if (StringUtils.isNotBlank(googleAnalyticsScript)) { outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1, "\n" + AggregateCacheFilter.removeEsiTags(googleAnalyticsScript) + "\n<"); } break; // avoid to loop if for any reasons multiple body in the page } out = outputDocument.toString().trim(); } } return out; }
From source file:de.ingrid.iplug.dscmapclient.index.mapper.ScriptedIdfDocumentMapper.java
/** * map in this case means, map the sourcerecord to * an idf document and store it as xml-string *//*from w w w .jav a 2 s. c o m*/ public ElasticDocument map(SourceRecord record, ElasticDocument luceneDoc) throws Exception { if (luceneDoc.get("id") == null || luceneDoc.get("serviceUnavailable") != null) { log.warn("!!! No 'id' set in index document (id=" + luceneDoc.get("id") + ") or 'serviceUnavailable' set (serviceUnavailable=" + luceneDoc.get("serviceUnavailable") + ") !!! No IDF possible, we return null Document so will not be indexed !"); return null; } if (mappingScript == null) { log.error("Mapping script is not set!"); throw new IllegalArgumentException("Mapping script is not set!"); } org.w3c.dom.Document w3cDoc = docBuilder.newDocument(); try { if (engine == null) { String scriptName = mappingScript.getFilename(); String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length()); ScriptEngineManager mgr = new ScriptEngineManager(); engine = mgr.getEngineByExtension(extension); if (compile) { if (engine instanceof Compilable) { Compilable compilable = (Compilable) engine; compiledScript = compilable.compile(new InputStreamReader(mappingScript.getInputStream())); } } } IndexUtils idxUtils = new IndexUtils(luceneDoc); CapabilitiesUtils capUtils = new CapabilitiesUtils(); XPathUtils xPathUtils = new XPathUtils(new IDFNamespaceContext()); DOMUtils domUtils = new DOMUtils(w3cDoc, xPathUtils); XMLUtils xmlUtils = new XMLUtils(); org.w3c.dom.Document wmsDoc = (org.w3c.dom.Document) record.get("WmsDoc"); Bindings bindings = engine.createBindings(); bindings.put("wmsDoc", wmsDoc); bindings.put("CAP", capUtils); bindings.put("XML", xmlUtils); bindings.put("sourceRecord", record); bindings.put("luceneDoc", luceneDoc); bindings.put("w3cDoc", w3cDoc); bindings.put("log", log); bindings.put("IDX", idxUtils); bindings.put("XPATH", xPathUtils); bindings.put("DOM", domUtils); bindings.put("javaVersion", System.getProperty("java.version")); if (compiledScript != null) { compiledScript.eval(bindings); } else { engine.eval(new InputStreamReader(mappingScript.getInputStream()), bindings); } } catch (Exception e) { log.error("Error mapping source record to lucene document."); //e.printStackTrace(); throw e; } return luceneDoc; }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java
@Test public void shouldMergeBindingsFromLocalAndGlobal() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> { });/*w ww. j av a 2s . co m*/ engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); engines.loadPlugins(Arrays.asList(new GremlinPlugin() { @Override public String getName() { return "mock"; } @Override public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException { pluginAcceptor.addBinding("y", "here"); } })); final Bindings localBindings = new SimpleBindings(); localBindings.put("x", "there"); assertEquals("herethere", engines.eval("y+x", localBindings, "gremlin-groovy")); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java
@Test public void shouldMergeBindingsWhereLocalOverridesGlobal() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> { });// ww w . j av a 2s. c o m engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); engines.loadPlugins(Arrays.asList(new GremlinPlugin() { @Override public String getName() { return "mock"; } @Override public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException { pluginAcceptor.addBinding("y", "here"); } })); // the "y" below should override the global variable setting. final Bindings localBindings = new SimpleBindings(); localBindings.put("y", "there"); localBindings.put("z", "where"); assertEquals("therewhere", engines.eval("y+z", localBindings, "gremlin-groovy")); }
From source file:de.ingrid.interfaces.csw.index.impl.ScriptedIDFRecordLuceneMapper.java
@Override public Document map(Record record, Map<String, Object> utils) throws Exception { Document document = new Document(); if (this.mappingScript == null) { log.error("Mapping script is not set!"); throw new IllegalArgumentException("Mapping script is not set!"); }// www . j av a 2 s . c o m InputStream input = null; try { org.w3c.dom.Document idfDoc = IdfUtils.getIdfDocument(record); Bindings bindings = this.engine.createBindings(); bindings.put("recordId", IdfUtils.getRecordId(idfDoc)); bindings.put("recordNode", idfDoc); bindings.put("document", document); document.add(new Field("docid", ((Integer) utils.get("docid")).toString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); bindings.put("log", log); bindings.put("XPATH", xpathUtils); bindings.put("luceneTools", luceneTools); bindings.put("javaVersion", JAVA_VERSION); for (Entry<String, Object> entry : utils.entrySet()) { bindings.put(entry.getKey(), entry.getValue()); } if (this.compiledScript != null) { this.compiledScript.eval(bindings); } else { input = new FileInputStream(this.mappingScript); this.engine.eval(new InputStreamReader(input), bindings); } } catch (Exception ex) { log.error("Error mapping InGrid record to lucene document.", ex); throw ex; } finally { if (input != null) { input.close(); } } return document; }
From source file:com.qwazr.webapps.transaction.ControllerManager.java
private void handleJavascript(WebappTransaction transaction, File controllerFile) throws IOException, ScriptException, PrivilegedActionException { WebappHttpResponse response = transaction.getResponse(); response.setHeader("Cache-Control", "max-age=0, no-cache, no-store"); Bindings bindings = scriptEngine.createBindings(); IOUtils.CloseableList closeables = new IOUtils.CloseableList(); bindings.put("console", new ScriptConsole()); bindings.put("request", transaction.getRequest()); bindings.put("response", transaction.getResponse()); bindings.put("session", transaction.getRequest().getSession()); bindings.putAll(transaction.getRequest().getAttributes()); FileReader fileReader = new FileReader(controllerFile); try {/*from ww w .j av a2 s .c o m*/ ScriptUtils.evalScript(scriptEngine, RestrictedAccessControlContext.INSTANCE, fileReader, bindings); } finally { fileReader.close(); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java
@Test public void shouldNotPreserveInstantiatedVariablesBetweenEvals() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> { });// ww w . jav a2 s . co m engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); final Bindings localBindingsFirstRequest = new SimpleBindings(); localBindingsFirstRequest.put("x", "there"); assertEquals("herethere", engines.eval("z = 'here' + x", localBindingsFirstRequest, "gremlin-groovy")); try { final Bindings localBindingsSecondRequest = new SimpleBindings(); engines.eval("z", localBindingsSecondRequest, "gremlin-groovy"); fail("Should not have knowledge of z"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } }