Search in sources :

Example 1 with VersioningConfiguration

use of org.apache.sling.servlets.post.VersioningConfiguration in project sling by apache.

the class SlingPostServlet method doPost.

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    final VersioningConfiguration localVersioningConfig = createRequestVersioningConfiguration(request);
    request.setAttribute(VersioningConfiguration.class.getName(), localVersioningConfig);
    // prepare the response
    final PostResponse htmlResponse = createPostResponse(request);
    htmlResponse.setReferer(request.getHeader("referer"));
    final PostOperation operation = getSlingPostOperation(request);
    if (operation == null) {
        htmlResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid operation specified for POST request");
    } else {
        request.getRequestProgressTracker().log("Calling PostOperation: {0}", operation.getClass().getName());
        final SlingPostProcessor[] processors = this.cachedPostProcessors;
        try {
            operation.run(request, htmlResponse, processors);
        } catch (ResourceNotFoundException rnfe) {
            htmlResponse.setStatus(HttpServletResponse.SC_NOT_FOUND, rnfe.getMessage());
        } catch (final Exception exception) {
            log.warn("Exception while handling POST " + request.getResource().getPath() + " with " + operation.getClass().getName(), exception);
            htmlResponse.setError(exception);
        }
    }
    // check for redirect URL if processing succeeded
    if (htmlResponse.isSuccessful()) {
        if (redirectIfNeeded(request, htmlResponse, response)) {
            return;
        }
    }
    // create a html response and send if unsuccessful or no redirect
    htmlResponse.send(response, isSetStatus(request));
}
Also used : SlingPostProcessor(org.apache.sling.servlets.post.SlingPostProcessor) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) PostOperation(org.apache.sling.servlets.post.PostOperation) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) PostResponse(org.apache.sling.servlets.post.PostResponse)

Example 2 with VersioningConfiguration

use of org.apache.sling.servlets.post.VersioningConfiguration in project sling by apache.

the class DeleteOperation method doRun.

@Override
protected void doRun(final SlingHttpServletRequest request, final PostResponse response, final List<Modification> changes) throws PersistenceException {
    // SLING-3203: selectors, extension and suffix make no sense here and
    // might lead to deleting other resources than the one the user means.
    final RequestPathInfo rpi = request.getRequestPathInfo();
    if ((rpi.getSelectors() != null && rpi.getSelectors().length > 0) || (rpi.getExtension() != null && rpi.getExtension().length() > 0) || (rpi.getSuffix() != null && rpi.getSuffix().length() > 0)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN, "DeleteOperation request cannot include any selectors, extension or suffix");
        return;
    }
    final VersioningConfiguration versioningConfiguration = getVersioningConfiguration(request);
    final boolean deleteChunks = isDeleteChunkRequest(request);
    final Iterator<Resource> res = getApplyToResources(request);
    if (res == null) {
        final Resource resource = request.getResource();
        deleteResource(resource, changes, versioningConfiguration, deleteChunks);
    } else {
        while (res.hasNext()) {
            final Resource resource = res.next();
            deleteResource(resource, changes, versioningConfiguration, deleteChunks);
        }
    }
}
Also used : RequestPathInfo(org.apache.sling.api.request.RequestPathInfo) Resource(org.apache.sling.api.resource.Resource) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration)

Example 3 with VersioningConfiguration

use of org.apache.sling.servlets.post.VersioningConfiguration in project sling by apache.

the class AbstractCopyMoveOperation method doRun.

@Override
protected final void doRun(final SlingHttpServletRequest request, final PostResponse response, final List<Modification> changes) throws PersistenceException {
    final VersioningConfiguration versioningConfiguration = getVersioningConfiguration(request);
    final Resource resource = request.getResource();
    final String source = resource.getPath();
    // ensure dest is not empty/null and is absolute
    String dest = request.getParameter(SlingPostConstants.RP_DEST);
    if (dest == null || dest.length() == 0) {
        throw new IllegalArgumentException("Unable to process " + getOperationName() + ". Missing destination");
    }
    // register whether the path ends with a trailing slash
    final boolean trailingSlash = dest.endsWith("/");
    // ensure destination is an absolute and normalized path
    if (!dest.startsWith("/")) {
        dest = ResourceUtil.getParent(source) + "/" + dest;
    }
    dest = ResourceUtil.normalize(dest);
    // destination parent and name
    final String dstParent = trailingSlash ? dest : ResourceUtil.getParent(dest);
    // delete destination if already exists
    if (!trailingSlash && request.getResourceResolver().getResource(dest) != null) {
        final String replaceString = request.getParameter(SlingPostConstants.RP_REPLACE);
        final boolean isReplace = "true".equalsIgnoreCase(replaceString);
        if (!isReplace) {
            response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Cannot " + getOperationName() + " " + resource + " to " + dest + ": destination exists");
            return;
        } else {
            this.jcrSsupport.checkoutIfNecessary(request.getResourceResolver().getResource(dstParent), changes, versioningConfiguration);
        }
    } else {
        // if it's a descendant of the current node
        if (!dstParent.equals("")) {
            final Resource parentResource = request.getResourceResolver().getResource(dstParent);
            if (parentResource != null) {
                this.jcrSsupport.checkoutIfNecessary(parentResource, changes, versioningConfiguration);
            } else {
                response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Cannot " + getOperationName() + " " + resource + " to " + dest + ": parent of destination does not exist");
                return;
            }
        }
        // the destination is newly created, hence a create request
        response.setCreateRequest(true);
    }
    final Iterator<Resource> resources = getApplyToResources(request);
    final Resource destResource;
    if (resources == null) {
        final String dstName = trailingSlash ? null : ResourceUtil.getName(dest);
        destResource = execute(changes, resource, dstParent, dstName, versioningConfiguration);
    } else {
        // multiple applyTo requires trailing slash on destination
        if (!trailingSlash) {
            throw new IllegalArgumentException("Applying " + getOperationName() + " to multiple resources requires a trailing slash on the destination");
        }
        // multiple copy will never return 201/CREATED
        response.setCreateRequest(false);
        while (resources.hasNext()) {
            final Resource applyTo = resources.next();
            execute(changes, applyTo, dstParent, null, versioningConfiguration);
        }
        destResource = request.getResourceResolver().getResource(dest);
    }
    if (destResource == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing source " + resource + " for " + getOperationName());
        return;
    }
    // finally apply the ordering parameter
    this.jcrSsupport.orderNode(request, destResource, changes);
}
Also used : Resource(org.apache.sling.api.resource.Resource) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration)

Example 4 with VersioningConfiguration

use of org.apache.sling.servlets.post.VersioningConfiguration in project sling by apache.

the class ImportOperation method doRun.

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, final List<Modification> changes) throws PersistenceException {
    try {
        Object importer = contentImporter;
        if (importer == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing content importer for import");
            return;
        }
        Map<String, RequestProperty> reqProperties = collectContent(request, response);
        VersioningConfiguration versioningConfiguration = getVersioningConfiguration(request);
        // do not change order unless you have a very good reason.
        Session session = request.getResourceResolver().adaptTo(Session.class);
        processCreate(request.getResourceResolver(), reqProperties, response, changes, versioningConfiguration);
        String path = response.getPath();
        Node node = null;
        try {
            node = (Node) session.getItem(path);
        } catch (RepositoryException e) {
            log.warn(e.getMessage(), e);
        // was not able to resolve the node
        } catch (ClassCastException e) {
            log.warn(e.getMessage(), e);
        // it was not a node
        }
        if (node == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing target node " + path + " for import");
            return;
        }
        String contentType = getRequestParamAsString(request, SlingPostConstants.RP_CONTENT_TYPE);
        if (contentType == null) {
            response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Required :contentType parameter is missing");
            return;
        }
        //import options passed as request parameters.
        final boolean replace = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_REPLACE));
        final boolean replaceProperties = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_REPLACE_PROPERTIES));
        final boolean checkin = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_CHECKIN));
        final boolean autoCheckout = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_AUTO_CHECKOUT));
        String basePath = getResourcePath(request);
        if (basePath.endsWith("/")) {
            //remove the trailing slash
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        // default to creating content
        response.setCreateRequest(true);
        final String targetName;
        //check if a name was posted to use as the name of the imported root node
        if (getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME) != null) {
            // exact name
            targetName = getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME);
            if (targetName.length() > 0 && node.hasNode(targetName)) {
                if (replace) {
                    response.setCreateRequest(false);
                } else {
                    response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Cannot import " + path + "/" + targetName + ": node exists");
                    return;
                }
            }
        } else if (getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME_HINT) != null) {
            // node name hint only
            String nodePath = generateName(request, basePath);
            String name = nodePath.substring(nodePath.lastIndexOf('/') + 1);
            targetName = name;
        } else {
            // no name posted, so the import won't create a root node
            targetName = "";
        }
        final String contentRootName = targetName + "." + contentType;
        try {
            InputStream contentStream = null;
            RequestParameter contentParameter = request.getRequestParameter(SlingPostConstants.RP_CONTENT);
            if (contentParameter != null) {
                contentStream = contentParameter.getInputStream();
            } else {
                RequestParameter contentFile = request.getRequestParameter(SlingPostConstants.RP_CONTENT_FILE);
                if (contentFile != null) {
                    contentStream = contentFile.getInputStream();
                }
            }
            if (contentStream == null) {
                response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Missing content for import");
                return;
            } else {
                ((ContentImporter) importer).importContent(node, contentRootName, contentStream, new ImportOptions() {

                    @Override
                    public boolean isCheckin() {
                        return checkin;
                    }

                    @Override
                    public boolean isAutoCheckout() {
                        return autoCheckout;
                    }

                    @Override
                    public boolean isIgnoredImportProvider(String extension) {
                        // this probably isn't important in this context.
                        return false;
                    }

                    @Override
                    public boolean isOverwrite() {
                        return replace;
                    }

                    /* (non-Javadoc)
                                 * @see org.apache.sling.jcr.contentloader.ImportOptions#isPropertyOverwrite()
                                 */
                    @Override
                    public boolean isPropertyOverwrite() {
                        return replaceProperties;
                    }
                }, new ContentImportListener() {

                    @Override
                    public void onReorder(String orderedPath, String beforeSibbling) {
                        changes.add(Modification.onOrder(orderedPath, beforeSibbling));
                    }

                    @Override
                    public void onMove(String srcPath, String destPath) {
                        changes.add(Modification.onMoved(srcPath, destPath));
                    }

                    @Override
                    public void onModify(String srcPath) {
                        changes.add(Modification.onModified(srcPath));
                    }

                    @Override
                    public void onDelete(String srcPath) {
                        changes.add(Modification.onDeleted(srcPath));
                    }

                    @Override
                    public void onCreate(String srcPath) {
                        changes.add(Modification.onCreated(srcPath));
                    }

                    @Override
                    public void onCopy(String srcPath, String destPath) {
                        changes.add(Modification.onCopied(srcPath, destPath));
                    }

                    @Override
                    public void onCheckin(String srcPath) {
                        changes.add(Modification.onCheckin(srcPath));
                    }

                    @Override
                    public void onCheckout(String srcPath) {
                        changes.add(Modification.onCheckout(srcPath));
                    }
                });
            }
            if (!changes.isEmpty()) {
                //fill in the data for the response report
                Modification modification = changes.get(0);
                if (modification.getType() == ModificationType.CREATE) {
                    String importedPath = modification.getSource();
                    response.setLocation(externalizePath(request, importedPath));
                    response.setPath(importedPath);
                    int lastSlashIndex = importedPath.lastIndexOf('/');
                    if (lastSlashIndex != -1) {
                        String parentPath = importedPath.substring(0, lastSlashIndex);
                        response.setParentLocation(externalizePath(request, parentPath));
                    }
                }
            }
        } catch (IOException e) {
            throw new PersistenceException(e.getMessage(), e);
        }
    } catch (final RepositoryException re) {
        throw new PersistenceException(re.getMessage(), re);
    }
}
Also used : Modification(org.apache.sling.servlets.post.Modification) InputStream(java.io.InputStream) RequestParameter(org.apache.sling.api.request.RequestParameter) Node(javax.jcr.Node) ContentImportListener(org.apache.sling.jcr.contentloader.ContentImportListener) RepositoryException(javax.jcr.RepositoryException) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration) IOException(java.io.IOException) ContentImporter(org.apache.sling.jcr.contentloader.ContentImporter) RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) PersistenceException(org.apache.sling.api.resource.PersistenceException) ImportOptions(org.apache.sling.jcr.contentloader.ImportOptions) Session(javax.jcr.Session)

Example 5 with VersioningConfiguration

use of org.apache.sling.servlets.post.VersioningConfiguration in project sling by apache.

the class ModifyOperation method doRun.

@Override
protected void doRun(final SlingHttpServletRequest request, final PostResponse response, final List<Modification> changes) throws PersistenceException {
    final Map<String, RequestProperty> reqProperties = collectContent(request, response);
    final VersioningConfiguration versioningConfiguration = getVersioningConfiguration(request);
    // do not change order unless you have a very good reason.
    // ensure root of new content
    processCreate(request.getResourceResolver(), reqProperties, response, changes, versioningConfiguration);
    // write content from existing content (@Move/CopyFrom parameters)
    processMoves(request.getResourceResolver(), reqProperties, changes, versioningConfiguration);
    processCopies(request.getResourceResolver(), reqProperties, changes, versioningConfiguration);
    // cleanup any old content (@Delete parameters)
    processDeletes(request.getResourceResolver(), reqProperties, changes, versioningConfiguration);
    // write content from form
    writeContent(request.getResourceResolver(), reqProperties, changes, versioningConfiguration);
    // order content
    final Resource newResource = request.getResourceResolver().getResource(response.getPath());
    this.jcrSsupport.orderNode(request, newResource, changes);
}
Also used : RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) Resource(org.apache.sling.api.resource.Resource) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration)

Aggregations

VersioningConfiguration (org.apache.sling.servlets.post.VersioningConfiguration)8 Resource (org.apache.sling.api.resource.Resource)3 IOException (java.io.IOException)2 PersistenceException (org.apache.sling.api.resource.PersistenceException)2 Modification (org.apache.sling.servlets.post.Modification)2 SlingPostProcessor (org.apache.sling.servlets.post.SlingPostProcessor)2 RequestProperty (org.apache.sling.servlets.post.impl.helper.RequestProperty)2 InputStream (java.io.InputStream)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 Node (javax.jcr.Node)1 RepositoryException (javax.jcr.RepositoryException)1 Session (javax.jcr.Session)1 ServletException (javax.servlet.ServletException)1 RequestParameter (org.apache.sling.api.request.RequestParameter)1