use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.
the class ScriptUtils method resolveScript.
public static Resource resolveScript(ResourceResolver resolver, RenderContext renderContext, String scriptIdentifier) {
SlingHttpServletRequest request = BindingsUtils.getRequest(renderContext.getBindings());
Resource caller = ResourceResolution.getResourceForRequest(resolver, request);
Resource result = ResourceResolution.getResourceFromSearchPath(caller, scriptIdentifier);
if (result == null) {
SlingScriptHelper sling = BindingsUtils.getHelper(renderContext.getBindings());
caller = resolver.getResource(sling.getScript().getScriptResource().getPath());
result = ResourceResolution.getResourceFromSearchPath(caller, scriptIdentifier);
}
return result;
}
use of org.apache.sling.api.scripting.SlingScriptHelper 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 org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.
the class SlingGlobal method load.
private void load(Context cx, Scriptable thisObj, Object[] args) {
SlingScriptHelper sling = getProperty(cx, thisObj, SlingBindings.SLING, SlingScriptHelper.class);
if (sling == null) {
throw new NullPointerException(SlingBindings.SLING);
}
Scriptable globalScope = ScriptableObject.getTopLevelScope(thisObj);
Resource scriptResource = sling.getScript().getScriptResource();
ResourceResolver resolver = scriptResource.getResourceResolver();
// the path of the current script to resolve realtive paths
String currentScript = sling.getScript().getScriptResource().getPath();
String scriptParent = ResourceUtil.getParent(currentScript);
for (Object arg : args) {
String scriptName = ScriptRuntime.toString(arg);
Resource loadScript = null;
if (!scriptName.startsWith("/")) {
String absScriptName = scriptParent + "/" + scriptName;
loadScript = resolver.resolve(absScriptName);
}
// not resolved relative to the current script
if (loadScript == null) {
loadScript = resolver.resolve(scriptName);
}
if (loadScript == null) {
throw Context.reportRuntimeError("Script file " + scriptName + " not found");
}
InputStream scriptStream = loadScript.adaptTo(InputStream.class);
if (scriptStream == null) {
throw Context.reportRuntimeError("Script file " + scriptName + " cannot be read from");
}
try {
// reader for the stream
Reader scriptReader = new InputStreamReader(scriptStream, Charset.forName("UTF-8"));
// check whether we have to wrap the basic reader
if (scriptName.endsWith(RhinoJavaScriptEngineFactory.ESP_SCRIPT_EXTENSION)) {
scriptReader = new EspReader(scriptReader);
}
// read the suff buffered for better performance
scriptReader = new BufferedReader(scriptReader);
// now, let's go
cx.evaluateReader(globalScope, scriptReader, scriptName, 1, null);
} catch (IOException ioe) {
throw Context.reportRuntimeError("Failure reading file " + scriptName + ": " + ioe);
} finally {
// ensure the script input stream is closed
try {
scriptStream.close();
} catch (IOException ignore) {
}
}
}
}
use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.
the class SlingGlobal method loadModule.
private ModuleScope loadModule(Context cx, String modulePath, ModuleScope moduleScope, Scriptable thisObj) {
String absolutePath = modulePath;
if (modulePath.startsWith(".")) {
// relative
if (moduleScope == null) {
throw Context.reportRuntimeError("Cannot resolve relative module name outside of a module scope.");
}
absolutePath = (moduleScope.getModuleName() + "/" + modulePath).replaceAll("[^/]*/\\./", "");
while (absolutePath.matches("([^/]*/)?[^/]*/\\.\\./")) {
absolutePath = absolutePath.replaceAll("([^/]*/)?[^/]*/\\.\\./", "");
}
}
absolutePath = absolutePath + ".js";
SlingScriptHelper sling = getProperty(cx, thisObj, SlingBindings.SLING, SlingScriptHelper.class);
if (sling == null) {
throw new NullPointerException(SlingBindings.SLING);
}
ResourceResolver resrev = sling.getScript().getScriptResource().getResourceResolver();
Resource script = null;
String scriptName = null;
for (String basepath : resrev.getSearchPath()) {
script = resrev.resolve(basepath + absolutePath);
if (script != null && !(script instanceof NonExistingResource)) {
scriptName = basepath + absolutePath;
break;
}
}
if (script == null) {
throw Context.reportRuntimeError("Unable to resolve module " + absolutePath + " in search path");
}
InputStream scriptStream = script.adaptTo(InputStream.class);
if (scriptStream == null) {
//try once again
scriptStream = resrev.resolve(scriptName).adaptTo(InputStream.class);
if (scriptStream == null) {
throw Context.reportRuntimeError("Script file " + script.getPath() + " cannot be read");
}
}
try {
// reader for the stream
Reader scriptReader = new InputStreamReader(scriptStream, Charset.forName("UTF-8"));
// check whether we have to wrap the basic reader
if (scriptName.endsWith(RhinoJavaScriptEngineFactory.ESP_SCRIPT_EXTENSION)) {
scriptReader = new EspReader(scriptReader);
}
// read the suff buffered for better performance
scriptReader = new BufferedReader(scriptReader);
//TODO: execute script with ModuleScope
// now, let's go
ModuleScope scope = moduleScope;
if (scope == null) {
scope = new ModuleScope(thisObj, absolutePath.substring(0, absolutePath.length() - 3));
} else {
scope.reset();
}
cx.evaluateReader(scope, scriptReader, scriptName, 1, null);
return scope;
} catch (IOException ioe) {
throw Context.reportRuntimeError("Failure reading file " + scriptName + ": " + ioe);
} finally {
// ensure the script input stream is closed
try {
scriptStream.close();
} catch (IOException ignore) {
}
}
}
use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.
the class CallTag method doEndTag.
@Override
public int doEndTag() throws JspException {
final SlingBindings bindings = (SlingBindings) pageContext.getRequest().getAttribute(SlingBindings.class.getName());
final SlingScriptHelper scriptHelper = bindings.getSling();
final ServletResolver servletResolver = scriptHelper.getService(ServletResolver.class);
final RequestProgressTracker tracker = TagUtil.getRequest(pageContext).getRequestProgressTracker();
String servletName = null;
final Servlet servlet;
if (!ignoreComponentHierarchy) {
final Resource resource = bindings.getResource();
servlet = servletResolver.resolveServlet(resource, this.script);
if (servlet != null) {
servletName = RequestUtil.getServletName(servlet);
tracker.log("Including script {0} for path={1}, type={2}: {3}", script, resource.getPath(), resource.getResourceType(), servletName);
}
} else {
final ResourceResolver resolver = bindings.getRequest().getResourceResolver();
final String scriptPath;
if (!script.startsWith("/")) {
// resolve relative script
String parentPath = ResourceUtil.getParent(scriptHelper.getScript().getScriptResource().getPath());
// check if parent resides on search path
for (String sp : resolver.getSearchPath()) {
if (parentPath.startsWith(sp)) {
parentPath = parentPath.substring(sp.length());
break;
}
}
scriptPath = parentPath + "/" + script;
} else {
scriptPath = this.script;
}
servlet = servletResolver.resolveServlet(resolver, scriptPath);
if (servlet != null) {
servletName = RequestUtil.getServletName(servlet);
tracker.log("Including script {0} (ignoring component hierarchy): {1}", script, servletName);
}
}
if (servlet == null) {
throw new JspException("Could not find script " + script);
}
try {
if (flush && !(pageContext.getOut() instanceof BodyContent)) {
// might throw an IOException of course
pageContext.getOut().flush();
}
// wrap the response to get the correct output order
SlingHttpServletResponse response = new JspSlingHttpServletResponseWrapper(pageContext);
tracker.startTimer(servletName);
servlet.service(pageContext.getRequest(), response);
tracker.logTimer(servletName);
return EVAL_PAGE;
} catch (Exception e) {
throw new JspException("Error while executing script " + script, e);
}
}
Aggregations