Search in sources :

Example 76 with PersistenceException

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

the class JobHandler method finished.

/**
     * Finish a job.
     * @param state The state of the processing
     * @param keepJobInHistory whether to keep the job in the job history.
     * @param duration the duration of the processing.
     */
public void finished(final Job.JobState state, final boolean keepJobInHistory, final Long duration) {
    final boolean isSuccess = (state == Job.JobState.SUCCEEDED);
    final ResourceResolver resolver = this.configuration.createResourceResolver();
    try {
        final Resource jobResource = resolver.getResource(job.getResourcePath());
        if (jobResource != null) {
            try {
                String newPath = null;
                if (keepJobInHistory) {
                    final ValueMap vm = ResourceHelper.getValueMap(jobResource);
                    newPath = this.configuration.getStoragePath(job.getTopic(), job.getId(), isSuccess);
                    final Map<String, Object> props = new HashMap<>(vm);
                    props.put(JobImpl.PROPERTY_FINISHED_STATE, state.name());
                    if (isSuccess) {
                        // we set the finish date to start date + duration
                        final Date finishDate = new Date();
                        finishDate.setTime(job.getProcessingStarted().getTime().getTime() + duration);
                        final Calendar finishCal = Calendar.getInstance();
                        finishCal.setTime(finishDate);
                        props.put(JobImpl.PROPERTY_FINISHED_DATE, finishCal);
                    } else {
                        // current time is good enough
                        props.put(JobImpl.PROPERTY_FINISHED_DATE, Calendar.getInstance());
                    }
                    if (job.getProperty(Job.PROPERTY_RESULT_MESSAGE) != null) {
                        props.put(Job.PROPERTY_RESULT_MESSAGE, job.getProperty(Job.PROPERTY_RESULT_MESSAGE));
                    }
                    ResourceHelper.getOrCreateResource(resolver, newPath, props);
                }
                resolver.delete(jobResource);
                resolver.commit();
                if (keepJobInHistory && configuration.getMainLogger().isDebugEnabled()) {
                    if (isSuccess) {
                        configuration.getMainLogger().debug("Kept successful job {} at {}", Utility.toString(job), newPath);
                    } else {
                        configuration.getMainLogger().debug("Moved cancelled job {} to {}", Utility.toString(job), newPath);
                    }
                }
            } catch (final PersistenceException pe) {
                this.configuration.getMainLogger().warn("Unable to finish job " + job.getId(), pe);
            } catch (final InstantiationException ie) {
                // something happened with the resource in the meantime
                this.configuration.getMainLogger().debug("Unable to instantiate job", ie);
            }
        }
    } finally {
        resolver.close();
    }
}
Also used : HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Calendar(java.util.Calendar) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) Date(java.util.Date)

Example 77 with PersistenceException

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

the class JobManagerImpl method internalRemoveJobById.

/**
     * Remove a job.
     * If the job is already in the storage area, it's removed forever.
     * Otherwise it's moved to the storage area.
     */
private boolean internalRemoveJobById(final String jobId, final boolean forceRemove) {
    logger.debug("Trying to remove job {}", jobId);
    boolean result = true;
    JobImpl job = (JobImpl) this.getJobById(jobId);
    if (job != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found removal job: {}", Utility.toString(job));
        }
        final JobImpl retryJob = (JobImpl) this.configuration.getJobFromRetryList(jobId);
        if (retryJob != null) {
            job = retryJob;
        }
        // currently running?
        if (!forceRemove && job.getProcessingStarted() != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to remove job - job is started: {}", Utility.toString(job));
            }
            result = false;
        } else {
            final boolean isHistoryJob = this.configuration.isStoragePath(job.getResourcePath());
            // if history job, simply remove - otherwise move to history!
            if (isHistoryJob) {
                final ResourceResolver resolver = this.configuration.createResourceResolver();
                try {
                    final Resource jobResource = resolver.getResource(job.getResourcePath());
                    if (jobResource != null) {
                        resolver.delete(jobResource);
                        resolver.commit();
                        logger.debug("Removed job with id: {}", jobId);
                    } else {
                        logger.debug("Unable to remove job with id - resource already removed: {}", jobId);
                    }
                    NotificationUtility.sendNotification(this.eventAdmin, NotificationConstants.TOPIC_JOB_REMOVED, job, null);
                } catch (final PersistenceException pe) {
                    logger.warn("Unable to remove job at " + job.getResourcePath(), pe);
                    result = false;
                } finally {
                    resolver.close();
                }
            } else {
                final JobHandler jh = new JobHandler(job, null, this.configuration);
                jh.finished(Job.JobState.DROPPED, true, null);
            }
            this.configuration.getAuditLogger().debug("REMOVE OK : {}", jobId);
        }
    } else {
        logger.debug("Job for removal does not exist (anymore): {}", jobId);
    }
    return result;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException)

Example 78 with PersistenceException

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

the class StreamingUploadOperationTest method testPartsContentRange.

@Test
public void testPartsContentRange() 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")), mapOf("Content-Range", "bytes 0-3/8", "Content-Length", "4")));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("part".getBytes("UTF-8")), mapOf("Content-Range", "bytes 4-7/8", "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 79 with PersistenceException

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

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

the class ModifyOperation method getResourcePath.

@Override
protected String getResourcePath(SlingHttpServletRequest request) {
    // calculate the paths
    StringBuilder rootPathBuf = new StringBuilder();
    String suffix;
    Resource currentResource = request.getResource();
    if (ResourceUtil.isSyntheticResource(currentResource)) {
        // no resource, treat the missing resource path as suffix
        suffix = currentResource.getPath();
    } else {
        // resource for part of the path, use request suffix
        suffix = request.getRequestPathInfo().getSuffix();
        if (suffix != null) {
            // cut off any selectors/extension from the suffix
            int dotPos = suffix.indexOf('.');
            if (dotPos > 0) {
                suffix = suffix.substring(0, dotPos);
            }
        }
        // and preset the path buffer with the resource path
        rootPathBuf.append(currentResource.getPath());
    }
    // check for extensions or create suffix in the suffix
    boolean doGenerateName = false;
    if (suffix != null) {
        // check whether it is a create request (trailing /)
        if (suffix.endsWith(SlingPostConstants.DEFAULT_CREATE_SUFFIX)) {
            suffix = suffix.substring(0, suffix.length() - SlingPostConstants.DEFAULT_CREATE_SUFFIX.length());
            doGenerateName = true;
        // or with the star suffix /*
        } else if (suffix.endsWith(SlingPostConstants.STAR_CREATE_SUFFIX)) {
            suffix = suffix.substring(0, suffix.length() - SlingPostConstants.STAR_CREATE_SUFFIX.length());
            doGenerateName = true;
        }
        // append the remains of the suffix to the path buffer
        rootPathBuf.append(suffix);
    }
    String path = rootPathBuf.toString();
    if (doGenerateName) {
        try {
            path = generateName(request, path);
        } catch (PersistenceException re) {
            throw new SlingException("Failed to generate name", re);
        }
    }
    return path;
}
Also used : Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) SlingException(org.apache.sling.api.SlingException)

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