Search in sources :

Example 6 with Modification

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

the class StreamingUploadOperationTest method testParts.

@Test
public void testParts() throws PersistenceException, RepositoryException, UnsupportedEncodingException {
    List<Modification> changes = new ArrayList<>();
    PostResponse response = new AbstractPostResponse() {

        @Override
        protected void doSend(HttpServletResponse response) throws IOException {
        }

        @Override
        public void onChange(String type, String... arguments) {
        }

        @Override
        public String getPath() {
            return "/test/upload/location";
        }
    };
    List<Part> partsList = new ArrayList<>();
    partsList.add(new MockPart("test1.txt@Length", null, null, 0, new ByteArrayInputStream("8".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("test1.txt@Offset", null, null, 0, new ByteArrayInputStream("0".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("test".getBytes("UTF-8")), mapOf("Content-Length", "4")));
    partsList.add(new MockPart("test1.txt@Offset", null, null, 0, new ByteArrayInputStream("4".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("part".getBytes("UTF-8")), mapOf("Content-Length", "4")));
    partsList.add(new MockPart("*", "text/plain2", "test2.txt", 8, new ByteArrayInputStream("test1234".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("badformfield2", null, null, 0, new ByteArrayInputStream("testbadformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
    final Iterator<Part> partsIterator = partsList.iterator();
    final Map<String, Resource> repository = new HashMap<>();
    final ResourceResolver resourceResolver = new MockResourceResolver() {

        @Override
        public Resource getResource(String path) {
            Resource resource = repository.get(path);
            if (resource == null) {
                if ("/test/upload/location".equals(path)) {
                    resource = new MockRealResource(this, path, "sling:Folder");
                    repository.put(path, resource);
                    LOG.debug("Created {} ", path);
                }
            }
            LOG.debug("Resource {} is {} {}", path, resource, ResourceUtil.isSyntheticResource(resource));
            return resource;
        }

        @Override
        public Iterable<Resource> getChildren(Resource resource) {
            List<Resource> children = new ArrayList<>();
            for (Map.Entry<String, Resource> e : repository.entrySet()) {
                if (isChild(resource.getPath(), e.getKey())) {
                    children.add(e.getValue());
                }
            }
            return children;
        }

        private boolean isChild(String path, String key) {
            if (key.length() > path.length() && key.startsWith(path)) {
                return !key.substring(path.length() + 1).contains("/");
            }
            return false;
        }

        @Override
        public Iterator<Resource> listChildren(Resource parent) {
            return getChildren(parent).iterator();
        }

        @Override
        public void delete(Resource resource) throws PersistenceException {
        }

        @Override
        public Resource create(Resource resource, String s, Map<String, Object> map) throws PersistenceException {
            Resource childResource = resource.getChild(s);
            if (childResource != null) {
                throw new IllegalArgumentException("Child " + s + " already exists ");
            }
            String resourceType = (String) map.get("sling:resourceType");
            if (resourceType == null) {
                resourceType = (String) map.get("jcr:primaryType");
            }
            if (resourceType == null) {
                LOG.warn("Resource type null for {} {} ", resource, resource.getPath() + "/" + s);
            }
            Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, resourceType, map);
            repository.put(newResource.getPath(), newResource);
            LOG.debug("Created Resource {} ", newResource.getPath());
            return newResource;
        }

        @Override
        public void revert() {
        }

        @Override
        public void commit() throws PersistenceException {
            LOG.debug("Committing");
            for (Map.Entry<String, Resource> e : repository.entrySet()) {
                LOG.debug("Committing {} ", e.getKey());
                Resource r = e.getValue();
                ModifiableValueMap vm = r.adaptTo(ModifiableValueMap.class);
                for (Map.Entry<String, Object> me : vm.entrySet()) {
                    if (me.getValue() instanceof InputStream) {
                        try {
                            String value = IOUtils.toString((InputStream) me.getValue());
                            LOG.debug("Converted {} {}  ", me.getKey(), value);
                            vm.put(me.getKey(), value);
                        } catch (IOException e1) {
                            throw new PersistenceException("Failed to commit input stream", e1);
                        }
                    }
                }
                LOG.debug("Converted {} ", vm);
            }
            LOG.debug("Comittted {} ", repository);
        }

        @Override
        public boolean hasChanges() {
            return false;
        }
    };
    SlingHttpServletRequest request = new MockSlingHttpServlet3Request(null, null, null, null, null) {

        @Override
        public Object getAttribute(String name) {
            if ("request-parts-iterator".equals(name)) {
                return partsIterator;
            }
            return super.getAttribute(name);
        }

        @Override
        public ResourceResolver getResourceResolver() {
            return resourceResolver;
        }
    };
    streamedUplodOperation.doRun(request, response, changes);
    {
        Resource r = repository.get("/test/upload/location/test1.txt");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
    }
    {
        Resource r = repository.get("/test/upload/location/test1.txt/jcr:content");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
        Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
        Assert.assertEquals("text/plain", m.get("jcr:mimeType"));
        Assert.assertEquals("testpart", m.get("jcr:data"));
    }
    {
        Resource r = repository.get("/test/upload/location/test2.txt");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
    }
    {
        Resource r = repository.get("/test/upload/location/test2.txt/jcr:content");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
        Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
        Assert.assertEquals("text/plain2", m.get("jcr:mimeType"));
        Assert.assertEquals("test1234", m.get("jcr:data"));
    }
}
Also used : Modification(org.apache.sling.servlets.post.Modification) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ArrayList(java.util.ArrayList) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) AbstractPostResponse(org.apache.sling.servlets.post.AbstractPostResponse) PostResponse(org.apache.sling.servlets.post.PostResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) Resource(org.apache.sling.api.resource.Resource) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) AbstractPostResponse(org.apache.sling.servlets.post.AbstractPostResponse) MockSlingHttpServlet3Request(org.apache.sling.servlets.post.impl.helper.MockSlingHttpServlet3Request) ByteArrayInputStream(java.io.ByteArrayInputStream) Part(javax.servlet.http.Part) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) ValueMap(org.apache.sling.api.resource.ValueMap) HashMap(java.util.HashMap) Map(java.util.Map) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 7 with Modification

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

the class AbstractPostOperation method run.

/**
     * Prepares and finalizes the actual operation. Preparation encompasses
     * getting the absolute path of the item to operate on by calling the
     * {@link #getResourcePath(SlingHttpServletRequest)} method and setting the
     * location and parent location on the response. After the operation has
     * been done in the {@link #doRun(SlingHttpServletRequest, PostResponse, List)}
     * method the session is saved if there are unsaved modifications. In case
     * of errors, the unsaved changes in the session are rolled back.
     *
     * @param request the request to operate on
     * @param response The <code>PostResponse</code> to record execution
     *            progress.
     * @param processors The array of processors
     */
@Override
public void run(final SlingHttpServletRequest request, final PostResponse response, final SlingPostProcessor[] processors) {
    final VersioningConfiguration versionableConfiguration = getVersioningConfiguration(request);
    try {
        // calculate the paths
        String path = this.getResourcePath(request);
        response.setPath(path);
        // location
        response.setLocation(externalizePath(request, path));
        // parent location
        path = ResourceUtil.getParent(path);
        if (path != null) {
            response.setParentLocation(externalizePath(request, path));
        }
        final List<Modification> changes = new ArrayList<>();
        doRun(request, response, changes);
        // invoke processors
        if (processors != null) {
            for (SlingPostProcessor processor : processors) {
                processor.process(request, changes);
            }
        }
        // check modifications for remaining postfix and store the base path
        final Map<String, String> modificationSourcesContainingPostfix = new HashMap<>();
        final Set<String> allModificationSources = new HashSet<>(changes.size());
        for (final Modification modification : changes) {
            final String source = modification.getSource();
            if (source != null) {
                allModificationSources.add(source);
                final int atIndex = source.indexOf('@');
                if (atIndex > 0) {
                    modificationSourcesContainingPostfix.put(source.substring(0, atIndex), source);
                }
            }
        }
        // fail if any of the base paths (before the postfix) which had a postfix are contained in the modification set
        if (modificationSourcesContainingPostfix.size() > 0) {
            for (final Map.Entry<String, String> sourceToCheck : modificationSourcesContainingPostfix.entrySet()) {
                if (allModificationSources.contains(sourceToCheck.getKey())) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Postfix-containing path " + sourceToCheck.getValue() + " contained in the modification list. Check configuration.");
                    return;
                }
            }
        }
        final Set<String> nodesToCheckin = new LinkedHashSet<>();
        // 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());
                    if (versionableConfiguration.isCheckinOnNewVersionableNode()) {
                        nodesToCheckin.add(change.getSource());
                    }
                    break;
                case ORDER:
                    response.onChange("ordered", change.getSource(), change.getDestination());
                    break;
                case CHECKOUT:
                    response.onChange("checkout", change.getSource());
                    nodesToCheckin.add(change.getSource());
                    break;
                case CHECKIN:
                    response.onChange("checkin", change.getSource());
                    nodesToCheckin.remove(change.getSource());
                    break;
                case RESTORE:
                    response.onChange("restore", change.getSource());
                    break;
            }
        }
        if (isResourceResolverCommitRequired(request)) {
            request.getResourceResolver().commit();
        }
        if (!isSkipCheckin(request)) {
            // now do the checkins
            for (String checkinPath : nodesToCheckin) {
                if (this.jcrSsupport.checkin(request.getResourceResolver().getResource(checkinPath))) {
                    response.onChange("checkin", checkinPath);
                }
            }
        }
    } catch (Exception e) {
        log.error("Exception during response processing.", e);
        response.setError(e);
    } finally {
        if (isResourceResolverCommitRequired(request)) {
            request.getResourceResolver().revert();
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Modification(org.apache.sling.servlets.post.Modification) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration) NoSuchElementException(java.util.NoSuchElementException) PersistenceException(org.apache.sling.api.resource.PersistenceException) SlingPostProcessor(org.apache.sling.servlets.post.SlingPostProcessor) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 8 with Modification

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

the class AbstractPostServlet 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;
            }
        }
        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)

Aggregations

Modification (org.apache.sling.servlets.post.Modification)8 ArrayList (java.util.ArrayList)6 PersistenceException (org.apache.sling.api.resource.PersistenceException)5 AbstractPostResponse (org.apache.sling.servlets.post.AbstractPostResponse)5 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Session (javax.jcr.Session)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Calendar (java.util.Calendar)3 RepositoryException (javax.jcr.RepositoryException)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Part (javax.servlet.http.Part)3 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)3 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)3 Resource (org.apache.sling.api.resource.Resource)3 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)3 ValueMap (org.apache.sling.api.resource.ValueMap)3 MockResourceResolver (org.apache.sling.commons.testing.sling.MockResourceResolver)3