use of javax.script.SimpleBindings in project sling by apache.
the class RenderUnit method callUnit.
@SuppressWarnings({ "unused", "unchecked" })
protected void callUnit(PrintWriter out, RenderContext renderContext, Object templateObj, Object argsObj) {
if (!(templateObj instanceof RenderUnit)) {
if (templateObj == null) {
throw new SightlyJavaCompilerException("data-sly-call: expression evaluates to null.");
}
if (renderContext.getObjectModel().isPrimitive(templateObj)) {
throw new SightlyJavaCompilerException("data-sly-call: primitive \"" + templateObj.toString() + "\" does not represent a HTL template.");
} else if (templateObj instanceof String) {
throw new SightlyJavaCompilerException("data-sly-call: String '" + templateObj.toString() + "' does not represent a HTL template.");
}
throw new SightlyJavaCompilerException("data-sly-call: " + templateObj.getClass().getName() + " does not represent a HTL template.");
}
RenderUnit unit = (RenderUnit) templateObj;
Map<String, Object> argumentsMap = renderContext.getObjectModel().toMap(argsObj);
Bindings arguments = new SimpleBindings(Collections.unmodifiableMap(argumentsMap));
unit.render(out, renderContext, arguments);
}
use of javax.script.SimpleBindings in project sling by apache.
the class DefaultSlingScript method call.
/**
* @see org.apache.sling.api.scripting.SlingScript#call(org.apache.sling.api.scripting.SlingBindings, java.lang.String, java.lang.Object[])
* @throws ScriptEvaluationException
*/
public Object call(SlingBindings props, String method, Object... args) {
Bindings bindings = null;
Reader reader = null;
boolean disposeScriptHelper = !props.containsKey(SLING);
ResourceResolver oldResolver = null;
try {
bindings = verifySlingBindings(props);
// use final variable for inner class!
final Bindings b = bindings;
// create script context
final ScriptContext ctx = new ScriptContext() {
private Bindings globalScope;
private Bindings engineScope = b;
private Writer writer = (Writer) b.get(OUT);
private Writer errorWriter = new LogWriter((Logger) b.get(LOG));
private Reader reader = (Reader) b.get(READER);
private Bindings slingScope = new SimpleBindings();
/**
* @see javax.script.ScriptContext#setBindings(javax.script.Bindings, int)
*/
public void setBindings(final Bindings bindings, final int scope) {
switch(scope) {
case SlingScriptConstants.SLING_SCOPE:
this.slingScope = bindings;
break;
case 100:
if (bindings == null)
throw new NullPointerException("Bindings for ENGINE scope is null");
this.engineScope = bindings;
break;
case 200:
this.globalScope = bindings;
break;
default:
throw new IllegalArgumentException("Invalid scope");
}
}
/**
* @see javax.script.ScriptContext#getBindings(int)
*/
public Bindings getBindings(final int scope) {
switch(scope) {
case SlingScriptConstants.SLING_SCOPE:
return slingScope;
case 100:
return this.engineScope;
case 200:
return this.globalScope;
}
throw new IllegalArgumentException("Invalid scope");
}
/**
* @see javax.script.ScriptContext#setAttribute(java.lang.String, java.lang.Object, int)
*/
public void setAttribute(final String name, final Object value, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
bindings.put(name, value);
}
}
/**
* @see javax.script.ScriptContext#getAttribute(java.lang.String, int)
*/
public Object getAttribute(final String name, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
return bindings.get(name);
}
return null;
}
/**
* @see javax.script.ScriptContext#removeAttribute(java.lang.String, int)
*/
public Object removeAttribute(final String name, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
return bindings.remove(name);
}
return null;
}
/**
* @see javax.script.ScriptContext#getAttribute(java.lang.String)
*/
public Object getAttribute(String name) {
if (name == null)
throw new IllegalArgumentException("Name is null");
for (final int scope : SCOPES) {
final Bindings bindings = getBindings(scope);
if (bindings != null) {
final Object o = bindings.get(name);
if (o != null) {
return o;
}
}
}
return null;
}
/**
* @see javax.script.ScriptContext#getAttributesScope(java.lang.String)
*/
public int getAttributesScope(String name) {
if (name == null)
throw new IllegalArgumentException("Name is null");
for (final int scope : SCOPES) {
if ((getBindings(scope) != null) && (getBindings(scope).containsKey(name))) {
return scope;
}
}
return -1;
}
/**
* @see javax.script.ScriptContext#getScopes()
*/
public List<Integer> getScopes() {
return Arrays.asList(SCOPES);
}
/**
* @see javax.script.ScriptContext#getWriter()
*/
public Writer getWriter() {
return this.writer;
}
/**
* @see javax.script.ScriptContext#getErrorWriter()
*/
public Writer getErrorWriter() {
return this.errorWriter;
}
/**
* @see javax.script.ScriptContext#setWriter(java.io.Writer)
*/
public void setWriter(Writer writer) {
this.writer = writer;
}
/**
* @see javax.script.ScriptContext#setErrorWriter(java.io.Writer)
*/
public void setErrorWriter(Writer writer) {
this.errorWriter = writer;
}
/**
* @see javax.script.ScriptContext#getReader()
*/
public Reader getReader() {
return this.reader;
}
/**
* @see javax.script.ScriptContext#setReader(java.io.Reader)
*/
public void setReader(Reader reader) {
this.reader = reader;
}
};
// set the current resource resolver if a request is available from the bindings
if (props.getRequest() != null) {
oldResolver = requestResourceResolver.get();
requestResourceResolver.set(props.getRequest().getResourceResolver());
}
// set the script resource resolver as an attribute
ctx.setAttribute(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER, this.scriptResource.getResourceResolver(), SlingScriptConstants.SLING_SCOPE);
reader = getScriptReader();
if (method != null && !(this.scriptEngine instanceof Invocable)) {
reader = getWrapperReader(reader, method, args);
}
// evaluate the script
final Object result;
if (method == null && this.scriptEngine instanceof Compilable) {
CachedScript cachedScript = scriptCache.getScript(scriptName);
if (cachedScript == null) {
ScriptNameAwareReader snReader = new ScriptNameAwareReader(reader, scriptName);
CompiledScript compiledScript = ((Compilable) scriptEngine).compile(snReader);
cachedScript = new CachedScriptImpl(scriptName, compiledScript);
scriptCache.putScript(cachedScript);
LOGGER.debug("Adding {} to the script cache.", scriptName);
} else {
LOGGER.debug("Script {} was already cached.", scriptName);
}
result = cachedScript.getCompiledScript().eval(ctx);
} else {
result = scriptEngine.eval(reader, ctx);
}
// call method - if supplied and script engine supports direct invocation
if (method != null && (this.scriptEngine instanceof Invocable)) {
try {
((Invocable) scriptEngine).invokeFunction(method, Arrays.asList(args).toArray());
} catch (NoSuchMethodException e) {
throw new ScriptEvaluationException(this.scriptName, "Method " + method + " not found in script.", e);
}
}
// optionall flush the output channel
Object flushObject = bindings.get(FLUSH);
if (flushObject instanceof Boolean && (Boolean) flushObject) {
ctx.getWriter().flush();
}
// allways flush the error channel
ctx.getErrorWriter().flush();
return result;
} catch (IOException ioe) {
throw new ScriptEvaluationException(this.scriptName, ioe.getMessage(), ioe);
} catch (ScriptException se) {
Throwable cause = (se.getCause() == null) ? se : se.getCause();
throw new ScriptEvaluationException(this.scriptName, se.getMessage(), cause);
} finally {
if (props.getRequest() != null) {
requestResourceResolver.set(oldResolver);
}
// close the script reader (SLING-380)
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
// don't care
}
}
// dispose of the SlingScriptHelper
if (bindings != null && disposeScriptHelper) {
final InternalScriptHelper helper = (InternalScriptHelper) bindings.get(SLING);
if (helper != null) {
helper.cleanup();
}
}
}
}
use of javax.script.SimpleBindings in project sling by apache.
the class DefaultSlingScript method verifySlingBindings.
Bindings verifySlingBindings(final SlingBindings slingBindings) throws IOException {
final Bindings bindings = new SimpleBindings();
final SlingHttpServletRequest request = slingBindings.getRequest();
// check sling object
Object slingObject = slingBindings.get(SLING);
if (slingObject == null) {
if (request != null) {
slingObject = new InternalScriptHelper(this.bundleContext, this, request, slingBindings.getResponse(), this.cache);
} else {
slingObject = new InternalScriptHelper(this.bundleContext, this, this.cache);
}
} else if (!(slingObject instanceof SlingScriptHelper)) {
throw fail(SLING, "Wrong type");
}
final SlingScriptHelper sling = (SlingScriptHelper) slingObject;
bindings.put(SLING, sling);
if (request != null) {
final SlingHttpServletResponse response = slingBindings.getResponse();
if (response == null) {
throw fail(RESPONSE, "Missing or wrong type");
}
Object resourceObject = slingBindings.get(RESOURCE);
if (resourceObject != null && !(resourceObject instanceof Resource)) {
throw fail(RESOURCE, "Wrong type");
}
Object resolverObject = slingBindings.get(RESOLVER);
if (resolverObject != null && !(resolverObject instanceof ResourceResolver)) {
throw fail(RESOLVER, "Wrong type");
}
Object writerObject = slingBindings.get(OUT);
if (writerObject != null && !(writerObject instanceof PrintWriter)) {
throw fail(OUT, "Wrong type");
}
// if there is a provided sling script helper, check arguments
if (slingBindings.get(SLING) != null) {
if (sling.getRequest() != request) {
throw fail(REQUEST, "Not the same as request field of SlingScriptHelper");
}
if (sling.getResponse() != response) {
throw fail(RESPONSE, "Not the same as response field of SlingScriptHelper");
}
if (resourceObject != null && sling.getRequest().getResource() != resourceObject) {
throw fail(RESOURCE, "Not the same as resource of the SlingScriptHelper request");
}
if (resolverObject != null && sling.getRequest().getResourceResolver() != resolverObject) {
throw fail(RESOLVER, "Not the same as the resource resolver of the SlingScriptHelper request's resolver");
}
if (writerObject != null && sling.getResponse().getWriter() != writerObject) {
throw fail(OUT, "Not the same as writer of the SlingScriptHelper response");
}
}
// set base variables when executing inside a request
bindings.put(REQUEST, sling.getRequest());
bindings.put(READER, sling.getRequest().getReader());
bindings.put(RESPONSE, sling.getResponse());
bindings.put(RESOURCE, sling.getRequest().getResource());
bindings.put(RESOLVER, sling.getRequest().getResourceResolver());
bindings.put(OUT, sling.getResponse().getWriter());
}
Object logObject = slingBindings.get(LOG);
if (logObject == null) {
logObject = LoggerFactory.getLogger(getLoggerName());
} else if (!(logObject instanceof Logger)) {
throw fail(LOG, "Wrong type");
}
bindings.put(LOG, logObject);
// copy non-base variables
for (Map.Entry<String, Object> entry : slingBindings.entrySet()) {
if (!bindings.containsKey(entry.getKey())) {
bindings.put(entry.getKey(), entry.getValue());
}
}
if (!bindingsValuesProviders.isEmpty()) {
Set<String> protectedKeys = new HashSet<String>();
protectedKeys.addAll(PROTECTED_KEYS);
ProtectedBindings protectedBindings = new ProtectedBindings(bindings, protectedKeys);
for (BindingsValuesProvider provider : bindingsValuesProviders) {
provider.addBindings(protectedBindings);
}
}
return bindings;
}
use of javax.script.SimpleBindings in project sling by apache.
the class ProtectedBindingsTest method setup.
@Before
public void setup() {
SimpleBindings inner = new SimpleBindings();
inner.put("test1", "value1");
this.bindings = new ProtectedBindings(inner, Collections.singleton("test1"));
}
use of javax.script.SimpleBindings in project sling by apache.
the class ScriptEngineHelper method eval.
public Object eval(String javascriptCode, Map<String, Object> data, final StringWriter sw) throws ScriptException {
final PrintWriter pw = new PrintWriter(sw, true);
ScriptContext ctx = new SimpleScriptContext();
final Bindings b = new SimpleBindings();
b.put("out", pw);
if (data != null) {
for (Map.Entry<String, Object> e : data.entrySet()) {
b.put(e.getKey(), e.getValue());
}
}
ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
ctx.setWriter(sw);
ctx.setErrorWriter(new OutputStreamWriter(System.err));
Object result = getEngine().eval(javascriptCode, ctx);
if (result instanceof Wrapper) {
result = ((Wrapper) result).unwrap();
}
if (result instanceof ScriptableObject) {
Context.enter();
try {
result = ((ScriptableObject) result).getDefaultValue(null);
} finally {
Context.exit();
}
}
return result;
}
Aggregations