use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.
the class XMLRendererServlet method doGet.
@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ServletException, IOException {
final Resource r = req.getResource();
if (ResourceUtil.isNonExistingResource(r)) {
throw new ResourceNotFoundException("No data to render.");
}
resp.setContentType(req.getResponseContentType());
resp.setCharacterEncoding("UTF-8");
// are we included?
final boolean isIncluded = req.getAttribute(SlingConstants.ATTR_REQUEST_SERVLET) != null;
try {
final Node node = r.adaptTo(Node.class);
if (node != null) {
try {
if (req.getRequestPathInfo().getSelectorString() == null || req.getRequestPathInfo().getSelectorString().equals(DOCVIEW)) {
// check if response is adaptable to a content handler
final ContentHandler ch = resp.adaptTo(ContentHandler.class);
if (ch == null) {
node.getSession().exportDocumentView(node.getPath(), resp.getOutputStream(), false, false);
} else {
node.getSession().exportDocumentView(node.getPath(), ch, false, false);
}
} else if (req.getRequestPathInfo().getSelectorString().equals(SYSVIEW)) {
// check if response is adaptable to a content handler
final ContentHandler ch = resp.adaptTo(ContentHandler.class);
if (ch == null) {
node.getSession().exportSystemView(node.getPath(), resp.getOutputStream(), false, false);
} else {
node.getSession().exportSystemView(node.getPath(), ch, false, false);
}
} else {
// NO Content
resp.sendError(HttpServletResponse.SC_NO_CONTENT);
}
} catch (RepositoryException e) {
throw new ServletException("Unable to export resource as xml: " + r, e);
} catch (SAXException e) {
throw new ServletException("Unable to export resource as xml: " + r, e);
}
} else {
if (!isIncluded) {
// NO Content
resp.sendError(HttpServletResponse.SC_NO_CONTENT);
}
}
} catch (final Throwable t) {
// if the JCR api is not available, we get here
if (!isIncluded) {
// NO Content
resp.sendError(HttpServletResponse.SC_NO_CONTENT);
}
}
}
use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.
the class DownloadBinaryProperty method doGet.
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
String propertyName = request.getParameter("property");
if ("".equals(propertyName) || propertyName == null)
throw new ResourceNotFoundException("No property specified.");
ServletOutputStream out = response.getOutputStream();
Resource resource = request.getResource();
Node currentNode = resource.adaptTo(Node.class);
javax.jcr.Property property = null;
try {
property = currentNode.getProperty(propertyName);
} catch (PathNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found.");
throw new ResourceNotFoundException("Not found.");
} catch (RepositoryException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found.");
throw new ResourceNotFoundException("Not found.");
}
InputStream stream = null;
try {
if (property == null || property.getType() != PropertyType.BINARY) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found.");
throw new ResourceNotFoundException("Not found.");
}
long length = property.getLength();
if (length > 0) {
if (length < Integer.MAX_VALUE) {
response.setContentLength((int) length);
} else {
response.setHeader("Content-Length", String.valueOf(length));
}
}
stream = property.getStream();
byte[] buf = new byte[2048];
int rd;
while ((rd = stream.read(buf)) >= 0) {
out.write(buf, 0, rd);
}
} catch (ValueFormatException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error downloading the property content.");
log.debug("error reading the property " + property + " of path " + resource.getPath(), e);
} catch (RepositoryException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error downloading the property content.");
log.debug("error reading the property " + property + " of path " + resource.getPath(), e);
} finally {
stream.close();
}
}
use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.
the class AbstractAccessPostServlet method doPost.
/* (non-Javadoc)
* @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse httpResponse) throws ServletException, IOException {
// prepare the response
AbstractPostResponse response = createHtmlResponse(request);
response.setReferer(request.getHeader("referer"));
// calculate the paths
String path = getItemPath(request);
response.setPath(path);
// location
response.setLocation(externalizePath(request, path));
// parent location
path = ResourceUtil.getParent(path);
if (path != null) {
response.setParentLocation(externalizePath(request, path));
}
Session session = request.getResourceResolver().adaptTo(Session.class);
final List<Modification> changes = new ArrayList<Modification>();
try {
handleOperation(request, response, changes);
// set changes on html response
for (Modification change : changes) {
switch(change.getType()) {
case MODIFY:
response.onModified(change.getSource());
break;
case DELETE:
response.onDeleted(change.getSource());
break;
case MOVE:
response.onMoved(change.getSource(), change.getDestination());
break;
case COPY:
response.onCopied(change.getSource(), change.getDestination());
break;
case CREATE:
response.onCreated(change.getSource());
break;
case ORDER:
response.onChange("ordered", change.getSource(), change.getDestination());
break;
default:
break;
}
}
if (session.hasPendingChanges()) {
session.save();
}
} catch (ResourceNotFoundException rnfe) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND, rnfe.getMessage());
} catch (Throwable throwable) {
log.debug("Exception while handling POST " + request.getResource().getPath() + " with " + getClass().getName(), throwable);
response.setError(throwable);
} finally {
try {
if (session.hasPendingChanges()) {
session.refresh(false);
}
} catch (RepositoryException e) {
log.warn("RepositoryException in finally block: {}", e.getMessage(), e);
}
}
// check for redirect URL if processing succeeded
if (response.isSuccessful()) {
String redirect = getRedirectUrl(request, response);
if (redirect != null) {
httpResponse.sendRedirect(redirect);
return;
}
}
// create a html response and send if unsuccessful or no redirect
response.send(httpResponse, isSetStatus(request));
}
use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.
the class AbstractGetAclServlet method doGet.
/* (non-Javadoc)
* @see org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
try {
Session session = request.getResourceResolver().adaptTo(Session.class);
String resourcePath = request.getResource().getPath();
JsonObject acl = internalGetAcl(session, resourcePath);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
boolean isTidy = false;
final String[] selectors = request.getRequestPathInfo().getSelectors();
if (selectors != null && selectors.length > 0) {
for (final String level : selectors) {
if ("tidy".equals(level)) {
isTidy = true;
break;
}
}
}
Map<String, Object> options = new HashMap<>();
options.put(JsonGenerator.PRETTY_PRINTING, isTidy);
Json.createGeneratorFactory(options).createGenerator(response.getWriter()).write(acl).flush();
} catch (AccessDeniedException ade) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (ResourceNotFoundException rnfe) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, rnfe.getMessage());
} catch (Throwable throwable) {
log.debug("Exception while handling GET " + request.getResource().getPath() + " with " + getClass().getName(), throwable);
throw new ServletException(throwable);
}
}
use of org.apache.sling.api.resource.ResourceNotFoundException 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);
}
Aggregations