use of org.apache.sling.api.resource.NonExistingResource in project sling by apache.
the class MergingResourcePicker method pickResources.
@Override
public List<Resource> pickResources(final ResourceResolver resolver, final String relativePath, final Resource relatedResource) {
List<Resource> relatedMappedResources = null;
if (relatedResource instanceof MergedResource) {
relatedMappedResources = ((MergedResource) relatedResource).getMappedResources();
// Check if the path is the same
if (relatedResource.getPath().equals(mergeRootPath + '/' + relativePath)) {
return relatedMappedResources;
}
}
final List<Resource> resources = new ArrayList<Resource>();
final String[] searchPaths = resolver.getSearchPath();
for (int i = searchPaths.length - 1; i >= 0; i--) {
final String basePath = searchPaths[i];
final String fullPath = basePath + relativePath;
int baseIndex = resources.size();
Resource baseResource = null;
if (relatedMappedResources != null && relatedMappedResources.size() > baseIndex) {
baseResource = relatedMappedResources.get(baseIndex);
}
Resource resource = (baseResource != null) ? getFromBaseResource(resolver, baseResource, fullPath) : null;
if (resource == null) {
resource = resolver.getResource(fullPath);
if (resource == null) {
resource = new NonExistingResource(resolver, fullPath);
}
}
resources.add(resource);
}
return resources;
}
use of org.apache.sling.api.resource.NonExistingResource in project sling by apache.
the class ResourceResolverImpl method resolveInternal.
private Resource resolveInternal(final HttpServletRequest request, String absPath) {
// make sure abspath is not null and is absolute
if (absPath == null) {
absPath = "/";
} else if (!absPath.startsWith("/")) {
absPath = "/" + absPath;
}
// check for special namespace prefix treatment
absPath = unmangleNamespaces(absPath);
// Assume http://localhost:80 if request is null
String[] realPathList = { absPath };
String requestPath;
if (request != null) {
requestPath = getMapPath(request.getScheme(), request.getServerName(), request.getServerPort(), absPath);
} else {
requestPath = getMapPath("http", "localhost", 80, absPath);
}
logger.debug("resolve: Resolving request path {}", requestPath);
// TODO: might do better to be able to log the loop and help the user
for (int i = 0; i < 100; i++) {
String[] mappedPath = null;
final Iterator<MapEntry> mapEntriesIterator = this.factory.getMapEntries().getResolveMapsIterator(requestPath);
while (mapEntriesIterator.hasNext()) {
final MapEntry mapEntry = mapEntriesIterator.next();
mappedPath = mapEntry.replace(requestPath);
if (mappedPath != null) {
if (logger.isDebugEnabled()) {
logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry, Arrays.toString(mappedPath));
}
if (mapEntry.isInternal()) {
// internal redirect
logger.debug("resolve: Redirecting internally");
break;
}
// external redirect
logger.debug("resolve: Returning external redirect");
return this.factory.getResourceDecoratorTracker().decorate(new RedirectResource(this, absPath, mappedPath[0], mapEntry.getStatus()));
}
}
// and use the original realPath
if (mappedPath == null) {
logger.debug("resolve: Request path {} does not match any MapEntry", requestPath);
break;
}
// if the mapped path is not an URL, use this path to continue
if (!mappedPath[0].contains("://")) {
logger.debug("resolve: Mapped path is for resource tree");
realPathList = mappedPath;
break;
}
// resolve that URI now, using the URI's path as the real path
try {
final URI uri = new URI(mappedPath[0], false);
requestPath = getMapPath(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
realPathList = new String[] { uri.getPath() };
logger.debug("resolve: Mapped path is an URL, using new request path {}", requestPath);
} catch (final URIException use) {
// TODO: log and fail
throw new ResourceNotFoundException(absPath);
}
}
// now we have the real path resolved from virtual host mapping
// this path may be absolute or relative, in which case we try
// to resolve it against the search path
Resource res = null;
for (int i = 0; res == null && i < realPathList.length; i++) {
final ParsedParameters parsedPath = new ParsedParameters(realPathList[i]);
final String realPath = parsedPath.getRawPath();
// first check whether the requested resource is a StarResource
if (StarResource.appliesTo(realPath)) {
logger.debug("resolve: Mapped path {} is a Star Resource", realPath);
res = new StarResource(this, ensureAbsPath(realPath));
} else {
if (realPath.startsWith("/")) {
// let's check it with a direct access first
logger.debug("resolve: Try absolute mapped path {}", realPath);
res = resolveInternal(realPath, parsedPath.getParameters());
} else {
final String[] searchPath = getSearchPath();
for (int spi = 0; res == null && spi < searchPath.length; spi++) {
logger.debug("resolve: Try relative mapped path with search path entry {}", searchPath[spi]);
res = resolveInternal(searchPath[spi] + realPath, parsedPath.getParameters());
}
}
}
}
// if no resource has been found, use a NonExistingResource
if (res == null) {
final ParsedParameters parsedPath = new ParsedParameters(realPathList[0]);
final String resourcePath = ensureAbsPath(parsedPath.getRawPath());
logger.debug("resolve: Path {} does not resolve, returning NonExistingResource at {}", absPath, resourcePath);
res = new NonExistingResource(this, resourcePath);
// SLING-864: if the path contains a dot we assume this to be
// the start for any selectors, extension, suffix, which may be
// used for further request processing.
// the resolution path must be the full path and is already set within
// the non existing resource
final int index = resourcePath.indexOf('.');
if (index != -1) {
res.getResourceMetadata().setResolutionPathInfo(resourcePath.substring(index));
}
res.getResourceMetadata().setParameterMap(parsedPath.getParameters());
} else {
logger.debug("resolve: Path {} resolves to Resource {}", absPath, res);
}
return this.factory.getResourceDecoratorTracker().decorate(res);
}
use of org.apache.sling.api.resource.NonExistingResource 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.resource.NonExistingResource in project sling by apache.
the class ProviderHandlerTest method testServletRegistrationAndSyntheticResources.
@SuppressWarnings("unchecked")
@Test
public void testServletRegistrationAndSyntheticResources() throws LoginException {
final String servletpath = "/libs/a/b/GET.servlet";
final Resource servletResource = Mockito.mock(Resource.class);
Mockito.when(servletResource.getResourceMetadata()).then(new Answer<ResourceMetadata>() {
@Override
public ResourceMetadata answer(InvocationOnMock invocation) throws Throwable {
return new ResourceMetadata();
}
});
final ResourceProvider<?> leaveProvider = Mockito.mock(ResourceProvider.class);
Mockito.when(leaveProvider.getResource(Mockito.any(ResolveContext.class), Mockito.eq(servletpath), Mockito.any(ResourceContext.class), Mockito.any(Resource.class))).thenReturn(servletResource);
final ResourceProviderHandler h = createRPHandler(leaveProvider, "my-pid", 0, servletpath);
ResourceResolverFactoryActivator activator = new ResourceResolverFactoryActivator();
activator.resourceAccessSecurityTracker = new ResourceAccessSecurityTracker();
ResourceResolver resolver = new ResourceResolverImpl(new CommonResourceResolverFactoryImpl(activator), false, null, new ResourceProviderStorageProvider() {
@Override
public ResourceProviderStorage getResourceProviderStorage() {
return new ResourceProviderStorage(Arrays.asList(h));
}
});
final Resource parent = resolver.getResource(ResourceUtil.getParent(servletpath));
assertNotNull("Parent must be available", parent);
assertTrue("Resource should be synthetic", ResourceUtil.isSyntheticResource(parent));
final Resource servlet = resolver.getResource(servletpath);
assertNotNull("Servlet resource must not be null", servlet);
assertEquals(servletResource, servlet);
assertNotNull(resolver.getResource("/libs"));
// now check when doing a resolve()
assertTrue(resolver.resolve("/libs") instanceof NonExistingResource);
assertTrue(resolver.resolve(ResourceUtil.getParent(servletpath)) instanceof NonExistingResource);
assertNotNull(resolver.resolve(servletpath));
resolver.close();
}
use of org.apache.sling.api.resource.NonExistingResource in project sling by apache.
the class ResourceResolverImplTest method testBasicAPIAssumptions.
@SuppressWarnings("deprecation")
@Test
public void testBasicAPIAssumptions() throws Exception {
// null resource is accessing /, which exists of course
final Resource res00 = resResolver.resolve((String) null);
assertNotNull(res00);
assertTrue("Resource must be NonExistingResource", res00 instanceof NonExistingResource);
assertEquals("Null path is expected to return root", "/", res00.getPath());
// relative paths are treated as if absolute
final String path01 = "relPath/relPath";
final Resource res01 = resResolver.resolve(path01);
assertNotNull(res01);
assertEquals("Expecting absolute path for relative path", "/" + path01, res01.getPath());
assertTrue("Resource must be NonExistingResource", res01 instanceof NonExistingResource);
final String no_resource_path = "/no_resource/at/this/location";
final Resource res02 = resResolver.resolve(no_resource_path);
assertNotNull(res02);
assertEquals("Expecting absolute path for relative path", no_resource_path, res02.getPath());
assertTrue("Resource must be NonExistingResource", res01 instanceof NonExistingResource);
try {
resResolver.resolve((HttpServletRequest) null);
fail("Expected NullPointerException trying to resolve null request");
} catch (NullPointerException npe) {
// expected
}
final Resource res0 = resResolver.resolve(null, no_resource_path);
assertNotNull("Expecting resource if resolution fails", res0);
assertTrue("Resource must be NonExistingResource", res0 instanceof NonExistingResource);
assertEquals("Path must be the original path", no_resource_path, res0.getPath());
final HttpServletRequest req1 = mock(HttpServletRequest.class);
when(req1.getProtocol()).thenReturn("http");
when(req1.getServerName()).thenReturn("localhost");
when(req1.getPathInfo()).thenReturn(no_resource_path);
final Resource res1 = resResolver.resolve(req1);
assertNotNull("Expecting resource if resolution fails", res1);
assertTrue("Resource must be NonExistingResource", res1 instanceof NonExistingResource);
assertEquals("Path must be the original path", no_resource_path, res1.getPath());
final HttpServletRequest req2 = mock(HttpServletRequest.class);
when(req2.getProtocol()).thenReturn("http");
when(req2.getServerName()).thenReturn("localhost");
when(req2.getPathInfo()).thenReturn(null);
final Resource res2 = resResolver.resolve(req2);
assertNotNull("Expecting resource if resolution fails", res2);
assertTrue("Resource must be NonExistingResource", res2 instanceof NonExistingResource);
assertEquals("Path must be the the root path", "/", res2.getPath());
final Resource res3 = resResolver.getResource(null);
assertNull("Expected null resource for null path", res3);
final Resource res4 = resResolver.getResource(null, null);
assertNull("Expected null resource for null path", res4);
final Resource res5 = resResolver.getResource(res01, null);
assertNull("Expected null resource for null path", res5);
}
Aggregations