Search in sources :

Example 81 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException 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 82 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project sling by apache.

the class AbstractCreateOperation method generateName.

protected String generateName(SlingHttpServletRequest request, String basePath) throws PersistenceException {
    // SLING-1091: If a :name parameter is supplied, the (first) value of this parameter is used unmodified as the name
    //    for the new node. If the name is illegally formed with respect to JCR name requirements, an exception will be
    //    thrown when trying to create the node. The assumption with the :name parameter is, that the caller knows what
    //    he (or she) is supplying and should get the exact result if possible.
    RequestParameterMap parameters = request.getRequestParameterMap();
    RequestParameter specialParam = parameters.getValue(SlingPostConstants.RP_NODE_NAME);
    if (specialParam != null) {
        if (specialParam.getString() != null && specialParam.getString().length() > 0) {
            // If the path ends with a *, create a node under its parent, with
            // a generated node name
            basePath = basePath += "/" + specialParam.getString();
            // if the resulting path already exists then report an error
            if (request.getResourceResolver().getResource(basePath) != null) {
                throw new PersistenceException("Collision in node names for path=" + basePath);
            }
            return basePath;
        }
    }
    // no :name value was supplied, so generate a name
    boolean requirePrefix = requireItemPathPrefix(request);
    String generatedName = null;
    if (extraNodeNameGenerators != null) {
        for (NodeNameGenerator generator : extraNodeNameGenerators) {
            generatedName = generator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
            if (generatedName != null) {
                break;
            }
        }
    }
    if (generatedName == null) {
        generatedName = defaultNodeNameGenerator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
    }
    // If the path ends with a *, create a node under its parent, with
    // a generated node name
    basePath += "/" + generatedName;
    basePath = ensureUniquePath(request, basePath);
    return basePath;
}
Also used : RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) RequestParameter(org.apache.sling.api.request.RequestParameter) PersistenceException(org.apache.sling.api.resource.PersistenceException) DefaultNodeNameGenerator(org.apache.sling.servlets.post.impl.helper.DefaultNodeNameGenerator) NodeNameGenerator(org.apache.sling.servlets.post.NodeNameGenerator)

Example 83 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project sling by apache.

the class AbstractCreateOperation method ensureUniquePath.

/** Generate a unique path in case the node name generator didn't */
private String ensureUniquePath(SlingHttpServletRequest request, String basePath) throws PersistenceException {
    // if resulting path exists, add a suffix until it's not the case
    // anymore
    final ResourceResolver resolver = request.getResourceResolver();
    // if resulting path exists, add a random suffix until it's not the case
    // anymore
    final int MAX_TRIES = 1000;
    if (resolver.getResource(basePath) != null) {
        for (int i = 0; i < MAX_TRIES; i++) {
            final int uniqueIndex = Math.abs(randomCollisionIndex.nextInt());
            String newPath = basePath + "_" + uniqueIndex;
            if (resolver.getResource(newPath) == null) {
                basePath = basePath + "_" + uniqueIndex;
                basePath = newPath;
                break;
            }
        }
        // Give up after MAX_TRIES
        if (resolver.getResource(basePath) != null) {
            throw new PersistenceException("Collision in generated node names under " + basePath + ", generated path " + basePath + " already exists");
        }
    }
    return basePath;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException)

Example 84 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project sling by apache.

the class CheckinOperation method doRun.

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
    try {
        Iterator<Resource> res = getApplyToResources(request);
        if (res == null) {
            Resource resource = request.getResource();
            Node node = resource.adaptTo(Node.class);
            if (node == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing source " + resource + " for checkout");
                return;
            }
            node.getSession().getWorkspace().getVersionManager().checkin(node.getPath());
            changes.add(Modification.onCheckin(resource.getPath()));
        } else {
            while (res.hasNext()) {
                Resource resource = res.next();
                Node node = resource.adaptTo(Node.class);
                if (node != null) {
                    node.getSession().getWorkspace().getVersionManager().checkin(node.getPath());
                    changes.add(Modification.onCheckin(resource.getPath()));
                }
            }
        }
    } catch (final RepositoryException re) {
        throw new PersistenceException(re.getMessage(), re);
    }
}
Also used : Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) RepositoryException(javax.jcr.RepositoryException)

Example 85 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project sling by apache.

the class RestoreOperation method doRun.

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
    try {
        final String version = request.getParameter(SlingPostConstants.RP_VERSION);
        if (version == null || version.length() == 0) {
            throw new IllegalArgumentException("Unable to process restore. Missing version");
        }
        final String removeString = request.getParameter(SlingPostConstants.RP_REMOVE_EXISTING);
        final boolean removeExisting = Boolean.parseBoolean(removeString);
        Iterator<Resource> res = getApplyToResources(request);
        if (res == null) {
            Resource resource = request.getResource();
            Node node = resource.adaptTo(Node.class);
            if (node == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing source " + resource + " for restore");
                return;
            }
            restore(node, version, removeExisting);
            changes.add(Modification.onRestore(resource.getPath(), version));
        } else {
            while (res.hasNext()) {
                Resource resource = res.next();
                Node node = resource.adaptTo(Node.class);
                if (node != null) {
                    restore(node, version, removeExisting);
                    changes.add(Modification.onRestore(resource.getPath(), version));
                }
            }
        }
    } catch (final RepositoryException re) {
        throw new PersistenceException(re.getMessage(), re);
    }
}
Also used : Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) RepositoryException(javax.jcr.RepositoryException)

Aggregations

PersistenceException (org.apache.sling.api.resource.PersistenceException)143 Resource (org.apache.sling.api.resource.Resource)102 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)62 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)37 HashMap (java.util.HashMap)34 LoginException (org.apache.sling.api.resource.LoginException)32 RepositoryException (javax.jcr.RepositoryException)24 ValueMap (org.apache.sling.api.resource.ValueMap)23 Node (javax.jcr.Node)17 Calendar (java.util.Calendar)14 Map (java.util.Map)14 IOException (java.io.IOException)13 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 ConfigurationPersistenceException (org.apache.sling.caconfig.spi.ConfigurationPersistenceException)6 InstanceDescription (org.apache.sling.discovery.InstanceDescription)6 QueueInfo (org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo)6 Test (org.junit.Test)5 JobTopicTraverser (org.apache.sling.event.impl.jobs.JobTopicTraverser)4