Search in sources :

Example 56 with PersistenceException

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

the class CRUDMergedResource method adaptTo.

/**
     * {@inheritDoc}
     */
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(final Class<AdapterType> type) {
    if (type == ModifiableValueMap.class) {
        final Iterator<Resource> iter = this.picker.pickResources(this.getResourceResolver(), this.relativePath, null).iterator();
        Resource highestRsrc = null;
        while (iter.hasNext()) {
            highestRsrc = iter.next();
        }
        if (ResourceUtil.isNonExistingResource(highestRsrc)) {
            final String[] paths = (String[]) this.getResourceMetadata().get(MergedResourceConstants.METADATA_RESOURCES);
            final Resource copyResource = this.getResourceResolver().getResource(paths[paths.length - 1]);
            try {
                final Resource newResource = ResourceUtil.getOrCreateResource(this.getResourceResolver(), highestRsrc.getPath(), copyResource.getResourceType(), null, false);
                final ModifiableValueMap target = newResource.adaptTo(ModifiableValueMap.class);
                if (target != null) {
                    return (AdapterType) new ModifiableProperties(this, target);
                }
            } catch (final PersistenceException pe) {
            // we ignore this for now
            }
            return super.adaptTo(type);
        }
        final ModifiableValueMap target = highestRsrc.adaptTo(ModifiableValueMap.class);
        if (target != null) {
            return (AdapterType) new ModifiableProperties(this, target);
        }
    }
    return super.adaptTo(type);
}
Also used : Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Example 57 with PersistenceException

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

the class CRUDMergingResourceProvider method delete.

@Override
public void delete(final ResolveContext<Void> ctx, final Resource resource) throws PersistenceException {
    final ResourceResolver resolver = ctx.getResourceResolver();
    final String path = resource.getPath();
    // deleting of the root mount resource is not supported
    final String relativePath = getRelativePath(path);
    if (relativePath == null || relativePath.length() == 0) {
        throw new PersistenceException("Resource at " + path + " can't be deleted.", null, path, null);
    }
    final ExtendedResourceHolder holder = this.getAllResources(resolver, path, relativePath);
    // we only support modifications if there is more than one location merged
    if (holder.count < 2) {
        throw new PersistenceException("Modifying is only supported with at least two potentially merged resources.", null, path, null);
    }
    if (holder.resources.size() == 1 && holder.resources.get(0).getPath().equals(holder.highestResourcePath)) {
        // delete the only resource which is the highest one
        resolver.delete(holder.resources.get(0));
    } else {
        // create overlay resource which is hiding the other
        final String createPath = holder.highestResourcePath;
        final Resource parentResource = ResourceUtil.getOrCreateResource(resolver, ResourceUtil.getParent(createPath), (String) null, null, false);
        final Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(MergedResourceConstants.PN_HIDE_RESOURCE, Boolean.TRUE);
        resolver.create(parentResource, ResourceUtil.getName(createPath), properties);
    }
}
Also used : HashMap(java.util.HashMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) Resource(org.apache.sling.api.resource.Resource)

Example 58 with PersistenceException

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

the class ResourceDistributionPackageBuilder method readPackageInternal.

@Override
protected DistributionPackage readPackageInternal(@Nonnull ResourceResolver resourceResolver, @Nonnull InputStream inputStream) throws DistributionException {
    try {
        Resource packagesRoot = DistributionPackageUtils.getPackagesRoot(resourceResolver, packagesPath);
        Resource packageResource = uploadStream(resourceResolver, packagesRoot, inputStream, -1);
        return new ResourceDistributionPackage(packageResource, getType(), resourceResolver, null, null);
    } catch (PersistenceException e) {
        throw new DistributionException(e);
    }
}
Also used : Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) DistributionException(org.apache.sling.distribution.common.DistributionException)

Example 59 with PersistenceException

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

the class ResourceDistributionPackageCleanup method run.

public void run() {
    log.debug("Cleaning up {} packages", packageBuilder.getType());
    ResourceResolver serviceResolver = null;
    try {
        int deleted = 0, total = 0;
        serviceResolver = resolverFactory.getServiceResourceResolver(null);
        for (Iterator<ResourceDistributionPackage> pkgs = packageBuilder.getPackages(serviceResolver); pkgs.hasNext(); total++) {
            ResourceDistributionPackage pkg = pkgs.next();
            if (pkg.disposable()) {
                log.debug("Delete package {}", pkg.getId());
                deleted++;
                pkg.delete(false);
            } else {
                log.debug("package {} is not disposable", pkg.getId());
            }
        }
        if (serviceResolver.hasChanges()) {
            serviceResolver.commit();
        }
        log.debug("Cleaned up {}/{} {} packages", new Object[] { deleted, total, packageBuilder.getType() });
    } catch (LoginException e) {
        log.error("Failed to get distribution service resolver: {}", e.getMessage());
    } catch (DistributionException e) {
        log.error("Failed to get the list of packages", e);
    } catch (PersistenceException e) {
        log.error("Failed to delete disposable packages", e);
    } finally {
        if (serviceResolver != null && serviceResolver.isLive()) {
            serviceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) DistributionException(org.apache.sling.distribution.common.DistributionException)

Example 60 with PersistenceException

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

the class StreamingUploadOperationTest method test.

@Test
public void test() 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("formfield1", null, null, 0, new ByteArrayInputStream("testformfield1".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("formfield2", null, null, 0, new ByteArrayInputStream("testformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("test".getBytes("UTF-8")), Collections.EMPTY_MAP));
    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) {
            return null;
        }

        @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 ");
            }
            Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, (String) map.get("sling:resourceType"), map);
            repository.put(newResource.getPath(), newResource);
            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("Committted {} ", 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("test", 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)

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