Package org.apache.sling.api.resource

Examples of org.apache.sling.api.resource.ModifiableValueMap


     * {@inheritDoc}
     */
    @Override
    public final void initialize(Resource resource, final ValueMap params) throws
            PersistenceException, RepositoryException {
        final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);

        log.trace("Entering initialized");

        if (properties.get(KEY_INITIALIZED, false)) {
            log.warn("Refusing to re-initialize an already initialized Bulk Workflow Manager.");
            return;
        }

        properties.putAll(params);
        properties.put(KEY_JOB_NAME, resource.getPath());

        // Query for all candidate resources

        final ResourceResolver resourceResolver = resource.getResourceResolver();
        final Session session = resourceResolver.adaptTo(Session.class);
        final QueryManager queryManager = session.getWorkspace().getQueryManager();
        final QueryResult queryResult = queryManager.createQuery(properties.get(KEY_QUERY, ""),
                Query.JCR_SQL2).execute();
        final NodeIterator nodes = queryResult.getNodes();

        long size = nodes.getSize();
        if (size < 0) {
            log.debug("Using provided estimate total size [ {} ] as actual size [ {} ] could not be retrieved.",
                    properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL), size);
            size = properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL);
        }

        final int batchSize = properties.get(KEY_BATCH_SIZE, DEFAULT_BATCH_SIZE);
        final Bucket bucket = new Bucket(batchSize, size,
                resource.getChild(NN_BATCHES).getPath(), "sling:Folder");

        final String relPath = params.get(KEY_RELATIVE_PATH, "");

        // Create the structure
        String currentBatch = null;
        int total = 0;
        Node previousBatchNode = null, batchItemNode = null;
        while (nodes.hasNext()) {
            Node payloadNode = nodes.nextNode();
            log.debug("nodes has next: {}", nodes.hasNext());

            log.trace("Processing search result [ {} ]", payloadNode.getPath());

            if (StringUtils.isNotBlank(relPath)) {
                if (payloadNode.hasNode(relPath)) {
                    payloadNode = payloadNode.getNode(relPath);
                } else {
                    log.warn("Could not find node at [ {} ]", payloadNode.getPath() + "/" + relPath);
                    continue;
                }
                // No rel path, so use the Query result node as the payload Node
            }

            total++;
            final String batchPath = bucket.getNextPath(resourceResolver);

            if (currentBatch == null) {
                // Set the currentBatch to the first batch folder
                currentBatch = batchPath;
            }

            final String batchItemPath = batchPath + "/" + total;

            batchItemNode = JcrUtil.createPath(batchItemPath, SLING_FOLDER, JcrConstants.NT_UNSTRUCTURED, session,
                    false);

            log.trace("Created batch item path at [ {} ]", batchItemPath);

            JcrUtil.setProperty(batchItemNode, KEY_PATH, payloadNode.getPath());
            log.trace("Added payload [ {} ] for batch item [ {} ]", payloadNode.getPath(), batchItemNode.getPath());

            if (total % batchSize == 0) {
                previousBatchNode = batchItemNode.getParent();
            } else if ((total % batchSize == 1) && previousBatchNode != null) {
                // Set the "next batch" property, so we know what the next batch to process is when
                // the current batch is complete
                JcrUtil.setProperty(previousBatchNode, KEY_NEXT_BATCH, batchItemNode.getParent().getPath());
            }

            if (total % SAVE_THRESHOLD == 0) {
                session.save();
            }
        } // while

        if (total > 0) {
            // Set last batch's "next batch" property to complete so we know we're done
            JcrUtil.setProperty(batchItemNode.getParent(), KEY_NEXT_BATCH, STATE_COMPLETE);

            if (total % SAVE_THRESHOLD != 0) {
                session.save();
            }

            properties.put(KEY_CURRENT_BATCH, currentBatch);
            properties.put(KEY_TOTAL, total);
            properties.put(KEY_INITIALIZED, true);
            properties.put(KEY_STATE, STATE_NOT_STARTED);

            resource.getResourceResolver().commit();

            log.info("Completed initialization of Bulk Workflow Manager");
        } else {
View Full Code Here


    /**
     * {@inheritDoc}
     */
    @Override
    public final void start(final Resource resource) {
        final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);

        final String jobName = properties.get(KEY_JOB_NAME, String.class);
        final String workflowModel = properties.get(KEY_WORKFLOW_MODEL, String.class);
        final String resourcePath = resource.getPath();
        long interval = properties.get(KEY_INTERVAL, DEFAULT_INTERVAL);

        final Runnable job = new Runnable() {

            private Map<String, String> activeWorkflows = new LinkedHashMap<String, String>();

            public void run() {
                ResourceResolver adminResourceResolver = null;
                Resource contentResource = null;

                try {
                    adminResourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
                    activeWorkflows = getActiveWorkflows(adminResourceResolver, activeWorkflows);
                    contentResource = adminResourceResolver.getResource(resourcePath);

                    if (contentResource == null) {
                        log.warn("Bulk workflow process resource [ {} ] could not be found. Removing periodic job.",
                                resourcePath);
                        scheduler.removeJob(jobName);
                    } else if (activeWorkflows.isEmpty()) {
                        // Either the beginning or the end of a batch process
                        activeWorkflows = process(contentResource, workflowModel);
                    } else {
                        log.debug("Workflows for batch [ {} ] are still active.",
                                contentResource.adaptTo(ValueMap.class).get(KEY_CURRENT_BATCH, "Missing batch"));

                        final ValueMap properties = contentResource.adaptTo(ValueMap.class);
                        final int batchTimeout = properties.get(KEY_BATCH_TIMEOUT, 0);

                        final Resource currentBatch = getCurrentBatch(contentResource);
                        final ModifiableValueMap currentBatchProperties =
                                currentBatch.adaptTo(ModifiableValueMap.class);

                        final int batchTimeoutCount = currentBatchProperties.get(KEY_BATCH_TIMEOUT_COUNT, 0);

                        if (batchTimeoutCount >= batchTimeout) {
                            terminateActiveWorkflows(adminResourceResolver,
                                    contentResource,
                                    activeWorkflows);
                            // Next batch will be pulled on next iteration
                        } else {
                            // Still withing batch processing range; continue.
                            currentBatchProperties.put(KEY_BATCH_TIMEOUT_COUNT, batchTimeoutCount + 1);
                            adminResourceResolver.commit();
                        }
                    }
                } catch (Exception e) {
                    log.error("Error processing periodic execution: {}", e.getMessage());
View Full Code Here

     *
     * @param resource the jcr:content configuration resource
     * @throws PersistenceException
     */
    private void stop(final Resource resource, final String state) throws PersistenceException {
        final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
        final String jobName = properties.get(KEY_JOB_NAME, String.class);

        log.debug("Stopping job [ {} ]", jobName);

        if (StringUtils.isNotBlank(jobName)) {
            scheduler.removeJob(jobName);
            jobs.remove(resource.getPath());

            log.info("Bulk Workflow Manager stopped for [ {} ]", jobName);

            properties.put(KEY_STATE, state);
            properties.put(KEY_STOPPED_AT, Calendar.getInstance());

            resource.getResourceResolver().commit();
        } else {
            log.error("Trying to stop a job without a name from Bulk Workflow Manager resource [ {} ]",
                    resource.getPath());
View Full Code Here

    /**
     * {@inheritDoc}
     */
    @Override
    public final void resume(final Resource resource, final long interval) throws PersistenceException {
        final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
        properties.put(KEY_INTERVAL, interval);
        resource.getResourceResolver().commit();

        this.start(resource);
        log.info("Resumed bulk workflow for [ {} ] with new interval [ {} ]", resource.getPath(), interval);
    }
View Full Code Here

     *
     * @param resource the jcr:content configuration resource
     * @throws PersistenceException
     */
    private void complete(final Resource resource) throws PersistenceException {
        final ModifiableValueMap mvm = resource.adaptTo(ModifiableValueMap.class);
        final String jobName = mvm.get(KEY_JOB_NAME, String.class);

        if (StringUtils.isNotBlank(jobName)) {
            scheduler.removeJob(jobName);

            log.info("Bulk Workflow Manager completed for [ {} ]", jobName);

            mvm.put(KEY_STATE, STATE_COMPLETE);
            mvm.put(KEY_COMPLETED_AT, Calendar.getInstance());

            resource.getResourceResolver().commit();
        } else {
            log.error("Trying to complete a job without a name from Bulk Workflow Manager resource [ {} ]",
                    resource.getPath());
View Full Code Here

        final WorkflowModel model = workflowSession.getModel(workflowModel);

        final Map<String, String> workflowMap = new LinkedHashMap<String, String>();

        final Resource currentBatch = this.getCurrentBatch(resource);
        final ModifiableValueMap currentProperties = currentBatch.adaptTo(ModifiableValueMap.class);

        Resource batchToProcess;
        if (currentProperties.get(KEY_STARTED_AT, Date.class) == null) {
            currentProperties.put(KEY_STARTED_AT, Calendar.getInstance());
            batchToProcess = currentBatch;
            log.debug("Virgin batch [ {} ]; preparing to initiate WF.", currentBatch.getPath());
        } else {
            batchToProcess = this.advance(resource);
            log.debug("Completed batch [ {} ]; preparing to advance and initiate WF on next batch [ {} ].",
                    currentBatch.getPath(), batchToProcess);
        }

        if (batchToProcess != null) {
            for (final Resource child : batchToProcess.getChildren()) {
                final ModifiableValueMap properties = child.adaptTo(ModifiableValueMap.class);

                final String state = properties.get(KEY_STATE, "");
                final String payloadPath = properties.get(KEY_PATH, String.class);

                if (StringUtils.isBlank(state)
                        && StringUtils.isNotBlank(payloadPath)) {

                    // Don't try to restart already processed batch items

                    final Workflow workflow = workflowSession.startWorkflow(model,
                            workflowSession.newWorkflowData("JCR_PATH", payloadPath));
                    properties.put(KEY_WORKFLOW_ID, workflow.getId());
                    properties.put(KEY_STATE, workflow.getState());

                    workflowMap.put(child.getPath(), workflow.getId());
                }
            }
        } else {
View Full Code Here

     * @throws RepositoryException
     */
    private Resource advance(final Resource resource) throws PersistenceException, RepositoryException {
        // Page Resource
        final ResourceResolver resourceResolver = resource.getResourceResolver();
        final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
        final boolean autoCleanupWorkflow = properties.get(KEY_PURGE_WORKFLOW, true);

        // Current Batch
        final Resource currentBatch = this.getCurrentBatch(resource);
        final ModifiableValueMap currentProperties = currentBatch.adaptTo(ModifiableValueMap.class);

        if (autoCleanupWorkflow) {
            this.purge(currentBatch);
        }

        currentProperties.put(KEY_COMPLETED_AT, Calendar.getInstance());

        // Next Batch
        final String nextBatchPath = currentProperties.get(KEY_NEXT_BATCH, STATE_COMPLETE);

        if (StringUtils.equalsIgnoreCase(nextBatchPath, STATE_COMPLETE)) {

            // Last batch

            this.complete(resource);

            properties.put(KEY_COMPLETE_COUNT,
                    properties.get(KEY_COMPLETE_COUNT, 0) + this.getSize(currentBatch.getChildren()));

            return null;

        } else {

            // Not the last batch

            final Resource nextBatch = resourceResolver.getResource(nextBatchPath);
            final ModifiableValueMap nextProperties = nextBatch.adaptTo(ModifiableValueMap.class);

            currentProperties.put(KEY_STATE, STATE_COMPLETE);
            currentProperties.put(KEY_COMPLETED_AT, Calendar.getInstance());

            nextProperties.put(KEY_STATE, STATE_RUNNING);
            nextProperties.put(KEY_STARTED_AT, Calendar.getInstance());

            properties.put(KEY_CURRENT_BATCH, nextBatch.getPath());
            properties.put(KEY_COMPLETE_COUNT,
                    properties.get(KEY_COMPLETE_COUNT, 0) + this.getSize(currentBatch.getChildren()));

View Full Code Here

    private int purge(Resource batchResource) throws RepositoryException {
        final ResourceResolver resourceResolver = batchResource.getResourceResolver();
        final List<String> payloadPaths = new ArrayList<String>();

        for (final Resource child : batchResource.getChildren()) {
            final ModifiableValueMap properties = child.adaptTo(ModifiableValueMap.class);
            final String workflowId = properties.get(KEY_WORKFLOW_ID, "Missing WorkflowId");
            final String path = properties.get(KEY_PATH, "Missing Path");

            final Resource resource = resourceResolver.getResource(workflowId);
            if (resource != null) {
                final Node node = resource.adaptTo(Node.class);
                node.remove();
View Full Code Here

                if (workflow.isActive()) {
                    activeWorkflowMap.put(entry.getKey(), workflow.getId());
                }

                final Resource resource = resourceResolver.getResource(entry.getKey());
                final ModifiableValueMap mvm = resource.adaptTo(ModifiableValueMap.class);

                if (!StringUtils.equals(mvm.get(KEY_STATE, String.class), workflow.getState())) {
                    mvm.put(KEY_STATE, workflow.getState());
                    dirty = true;
                }
            } catch (WorkflowException e) {
                log.error("Could not get workflow with id [ {} ]. {}", workflowId, e.getMessage());
            }
View Full Code Here

                    count++;

                    log.info("Terminated workflow [ {} ]", workflowId);

                    final Resource resource = resourceResolver.getResource(entry.getKey());
                    final ModifiableValueMap mvm = resource.adaptTo(ModifiableValueMap.class);

                    mvm.put(KEY_STATE, STATE_FORCE_TERMINATED.toUpperCase());

                    dirty = true;
                }

            } catch (WorkflowException e) {
                log.error("Could not get workflow with id [ {} ]. {}", workflowId, e.getMessage());
            }
        }

        if (dirty) {
            final ModifiableValueMap properties = contentResource.adaptTo(ModifiableValueMap.class);
            properties.put(KEY_FORCE_TERMINATED_COUNT,
                    properties.get(KEY_FORCE_TERMINATED_COUNT, 0) + count);
            resourceResolver.commit();
        }

        return count;
    }
View Full Code Here

TOP

Related Classes of org.apache.sling.api.resource.ModifiableValueMap

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.