Search in sources :

Example 61 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project CQ-Actions by Cognifide.

the class ReplicationMessageProducer method sendMessage.

@Override
public boolean sendMessage(String type, Map<String, String> message) {
    ResourceResolver resolver = null;
    try {
        resolver = resolverFactory.getAdministrativeResourceResolver(null);
        final Resource actionResource = createActionResource(resolver, type, "*");
        MessageSerializer.saveMessageToResource(actionResource, type, message);
        resolver.commit();
        return true;
    } catch (LoginException | PersistenceException e) {
        LOG.error("Can't replicate message", e);
        return false;
    } finally {
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException)

Example 62 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project CQ-Actions by Cognifide.

the class Resender method run.

@Override
public void run() {
    ResourceResolver resolver = null;
    try {
        resolver = resolverFactory.getAdministrativeResourceResolver(null);
        final Resource parent = resolver.getResource(MessagePersistenceService.SERIALIZED_ACTIONS);
        if (parent == null) {
            return;
        }
        for (final Resource child : parent.getChildren()) {
            resend(child);
        }
        resolver.commit();
    } catch (LoginException | PersistenceException e) {
        LOG.error("Can't resend", e);
    } catch (ActionSendException e) {
        LOG.error("Can't resend", e);
    } finally {
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : ActionSendException(com.cognifide.actions.api.ActionSendException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException)

Example 63 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project acs-aem-commons by Adobe-Consulting-Services.

the class WorkflowInstanceRemoverScheduler method run.

@Override
@SuppressWarnings("squid:S2142")
public final void run() {
    ResourceResolver adminResourceResolver = null;
    try {
        adminResourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO);
        final long start = System.currentTimeMillis();
        int count = workflowInstanceRemover.removeWorkflowInstances(adminResourceResolver, models, statuses, payloads, olderThan, batchSize, maxDuration);
        if (log.isInfoEnabled()) {
            log.info("Removed [ {} ] Workflow instances in {} ms", count, System.currentTimeMillis() - start);
        }
    } catch (LoginException e) {
        log.error("Login Exception when getting admin resource resolver", e);
    } catch (PersistenceException e) {
        log.error("Persistence Exception when saving Workflow Instances removal", e);
    } catch (WorkflowRemovalException e) {
        log.error("Workflow Removal exception during Workflow Removal", e);
    } catch (InterruptedException e) {
        log.error("Interrupted Exception during Workflow Removal", e);
    } catch (WorkflowRemovalForceQuitException e) {
        log.info("Workflow Removal force quit", e);
    } finally {
        if (adminResourceResolver != null) {
            adminResourceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) WorkflowRemovalException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalException) WorkflowRemovalForceQuitException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalForceQuitException)

Example 64 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project acs-aem-commons by Adobe-Consulting-Services.

the class WorkflowInstanceRemoverImpl method removeWorkflowInstances.

/**
 * {@inheritDoc}
 */
@SuppressWarnings({ "squid:S3776", "squid:S1141" })
public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds, final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan, final int batchSize, final int maxDurationInMins) throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException {
    final long start = System.currentTimeMillis();
    long end = -1;
    int count = 0;
    int checkedCount = 0;
    int workflowRemovedCount = 0;
    if (maxDurationInMins > 0) {
        // Max duration has been requested (greater than 0)
        // Convert minutes to milliseconds
        long maxDurationInMs = maxDurationInMins * MS_IN_ONE_MINUTE;
        // Compute the end time
        end = start + maxDurationInMs;
    }
    try {
        this.start(resourceResolver);
        final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver);
        for (Resource containerFolder : containerFolders) {
            log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath());
            final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder);
            for (final Resource folder : sortedFolders) {
                int remaining = 0;
                for (final Resource instance : folder.getChildren()) {
                    if (this.forceQuit.get()) {
                        throw new WorkflowRemovalForceQuitException();
                    } else if (end > 0 && System.currentTimeMillis() >= end) {
                        throw new WorkflowRemovalMaxDurationExceededException();
                    }
                    final ValueMap properties = instance.getValueMap();
                    if (!StringUtils.equals(NT_CQ_WORKFLOW, properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) {
                        // Only process cq:Workflow's
                        remaining++;
                        continue;
                    }
                    checkedCount++;
                    final String instanceStatus = getStatus(instance);
                    final String model = properties.get(PN_MODEL_ID, String.class);
                    final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class);
                    final String payload = properties.get(PAYLOAD_PATH, String.class);
                    if (StringUtils.isBlank(payload)) {
                        log.warn("Unable to find payload for Workflow instance [ {} ]", instance.getPath());
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(instanceStatus)) {
                        log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]", instance.getPath(), instanceStatus);
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) {
                        log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]", instance.getPath(), model);
                        remaining++;
                        continue;
                    } else if (olderThan != null && startTime != null && startTime.before(olderThan)) {
                        log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]", instance.getPath(), startTime);
                        remaining++;
                        continue;
                    } else {
                        if (CollectionUtils.isNotEmpty(payloads)) {
                            // Only evaluate payload patterns if they are provided
                            boolean match = false;
                            if (StringUtils.isNotEmpty(payload)) {
                                for (final Pattern pattern : payloads) {
                                    if (payload.matches(pattern.pattern())) {
                                        // payload matches a pattern
                                        match = true;
                                        break;
                                    }
                                }
                                if (!match) {
                                    // Not a match; skip to next workflow instance
                                    log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]", instance.getPath(), payload);
                                    remaining++;
                                    continue;
                                }
                            }
                        }
                        try {
                            instance.adaptTo(Node.class).remove();
                            log.debug("Removed workflow instance at [ {} ]", instance.getPath());
                            workflowRemovedCount++;
                            count++;
                        } catch (RepositoryException e) {
                            log.error("Could not remove workflow instance at [ {} ]. Continuing...", instance.getPath(), e);
                        }
                        if (count % batchSize == 0) {
                            this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount);
                            log.info("Removed a running total of [ {} ] workflow instances", count);
                        }
                    }
                }
                if (remaining == 0 && isWorkflowDatedFolder(folder) && !StringUtils.startsWith(folder.getName(), new SimpleDateFormat(WORKFLOW_FOLDER_FORMAT).format(new Date()))) {
                    // MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders
                    try {
                        folder.adaptTo(Node.class).remove();
                        log.debug("Removed empty workflow folder node [ {} ]", folder.getPath());
                        // Incrementing only count to trigger batch save and not total since is not a WF
                        count++;
                    } catch (RepositoryException e) {
                        log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e);
                    }
                }
            }
            // Save final batch if needed, and update tracking nodes
            this.complete(resourceResolver, checkedCount, workflowRemovedCount);
        }
    } catch (PersistenceException e) {
        this.forceQuit.set(false);
        log.error("Error persisting changes with Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalException e) {
        this.forceQuit.set(false);
        log.error("Error with Workflow Removal", e);
        this.error();
        throw e;
    } catch (InterruptedException e) {
        this.forceQuit.set(false);
        log.error("Errors in persistence retries during Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalForceQuitException e) {
        this.forceQuit.set(false);
        // Uncommon instance of using Exception to control flow; Force quitting is an extreme condition.
        log.warn("Workflow removal was force quit. The removal state is unknown.");
        this.internalForceQuit();
        throw e;
    } catch (WorkflowRemovalMaxDurationExceededException e) {
        // Uncommon instance of using Exception to control flow; Exceeding max duration extreme condition.
        log.warn("Workflow removal exceeded max duration of [ {} ] minutes. Final removal commit initiating...", maxDurationInMins);
        this.complete(resourceResolver, checkedCount, count);
    }
    if (log.isInfoEnabled()) {
        log.info("Workflow Removal Process Finished! " + "Removed a total of [ {} ] workflow instances in [ {} ] ms", count, System.currentTimeMillis() - start);
    }
    return count;
}
Also used : Pattern(java.util.regex.Pattern) ValueMap(org.apache.sling.api.resource.ValueMap) Calendar(java.util.Calendar) Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) RepositoryException(javax.jcr.RepositoryException) WorkflowRemovalException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalException) Date(java.util.Date) PersistenceException(org.apache.sling.api.resource.PersistenceException) WorkflowRemovalMaxDurationExceededException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalMaxDurationExceededException) SimpleDateFormat(java.text.SimpleDateFormat) WorkflowRemovalForceQuitException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalForceQuitException)

Example 65 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException in project acs-aem-commons by Adobe-Consulting-Services.

the class TwitterFeedUpdaterImpl method updateTwitterFeedComponents.

@Override
@SuppressWarnings("squid:S3776")
public void updateTwitterFeedComponents(ResourceResolver resourceResolver) {
    PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    List<Resource> twitterResources = findTwitterResources(resourceResolver);
    for (Resource twitterResource : twitterResources) {
        Page page = pageManager.getContainingPage(twitterResource);
        if (page != null) {
            Twitter client = page.adaptTo(Twitter.class);
            if (client != null) {
                try {
                    ValueMap properties = twitterResource.getValueMap();
                    String username = properties.get("username", String.class);
                    if (!StringUtils.isEmpty(username)) {
                        log.info("Loading Twitter timeline for user {} for component {}.", username, twitterResource.getPath());
                        List<Status> statuses = client.getUserTimeline(username);
                        if (statuses != null) {
                            List<String> tweetsList = new ArrayList<>(statuses.size());
                            List<String> jsonList = new ArrayList<>(statuses.size());
                            for (Status status : statuses) {
                                tweetsList.add(processTweet(status));
                                jsonList.add(DataObjectFactory.getRawJSON(status));
                            }
                            if (!tweetsList.isEmpty()) {
                                ModifiableValueMap map = twitterResource.adaptTo(ModifiableValueMap.class);
                                map.put("tweets", tweetsList.toArray(new String[tweetsList.size()]));
                                map.put("tweetsJson", jsonList.toArray(new String[jsonList.size()]));
                                twitterResource.getResourceResolver().commit();
                                handleReplication(twitterResource);
                            }
                        }
                    }
                } catch (PersistenceException e) {
                    log.error("Exception while updating twitter feed on resource:" + twitterResource.getPath(), e);
                } catch (ReplicationException e) {
                    log.error("Exception while replicating twitter feed on resource:" + twitterResource.getPath(), e);
                } catch (TwitterException e) {
                    log.error("Exception while loading twitter feed on resource:" + twitterResource.getPath(), e);
                }
            } else {
                log.warn("Twitter component found on {}, but page cannot be adapted to Twitter API. Check Cloud SErvice configuration", page.getPath());
            }
        }
    }
}
Also used : Status(twitter4j.Status) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Resource(org.apache.sling.api.resource.Resource) ArrayList(java.util.ArrayList) Twitter(twitter4j.Twitter) Page(com.day.cq.wcm.api.Page) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) PageManager(com.day.cq.wcm.api.PageManager) PersistenceException(org.apache.sling.api.resource.PersistenceException) ReplicationException(com.day.cq.replication.ReplicationException) TwitterException(twitter4j.TwitterException)

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