Search in sources :

Example 11 with ResourceNotFoundException

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);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) RepositoryException(javax.jcr.RepositoryException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException)

Example 12 with ResourceNotFoundException

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();
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) InputStream(java.io.InputStream) Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) RepositoryException(javax.jcr.RepositoryException) ValueFormatException(javax.jcr.ValueFormatException) PathNotFoundException(javax.jcr.PathNotFoundException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 13 with ResourceNotFoundException

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));
}
Also used : Modification(org.apache.sling.servlets.post.Modification) ArrayList(java.util.ArrayList) RepositoryException(javax.jcr.RepositoryException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) AbstractPostResponse(org.apache.sling.servlets.post.AbstractPostResponse) Session(javax.jcr.Session)

Example 14 with ResourceNotFoundException

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);
    }
}
Also used : ServletException(javax.servlet.ServletException) AccessDeniedException(javax.jcr.AccessDeniedException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) Session(javax.jcr.Session)

Example 15 with ResourceNotFoundException

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);
}
Also used : MapEntry(org.apache.sling.resourceresolver.impl.mapping.MapEntry) RedirectResource(org.apache.sling.resourceresolver.impl.helper.RedirectResource) StarResource(org.apache.sling.resourceresolver.impl.helper.StarResource) RedirectResource(org.apache.sling.resourceresolver.impl.helper.RedirectResource) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) StringUtils.defaultString(org.apache.commons.lang3.StringUtils.defaultString) URI(org.apache.sling.resourceresolver.impl.helper.URI) StarResource(org.apache.sling.resourceresolver.impl.helper.StarResource) URIException(org.apache.sling.resourceresolver.impl.helper.URIException) ParsedParameters(org.apache.sling.resourceresolver.impl.params.ParsedParameters) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Aggregations

ResourceNotFoundException (org.apache.sling.api.resource.ResourceNotFoundException)22 RepositoryException (javax.jcr.RepositoryException)10 Resource (org.apache.sling.api.resource.Resource)10 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)6 UserManager (org.apache.jackrabbit.api.security.user.UserManager)5 ArrayList (java.util.ArrayList)4 Session (javax.jcr.Session)4 Group (org.apache.jackrabbit.api.security.user.Group)4 User (org.apache.jackrabbit.api.security.user.User)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Item (javax.jcr.Item)3 ServletException (javax.servlet.ServletException)3 InputStream (java.io.InputStream)2 PrintWriter (java.io.PrintWriter)2 Principal (java.security.Principal)2 LinkedHashMap (java.util.LinkedHashMap)2 Entry (java.util.Map.Entry)2