Example usage for org.springframework.dao ConcurrencyFailureException ConcurrencyFailureException

List of usage examples for org.springframework.dao ConcurrencyFailureException ConcurrencyFailureException

Introduction

In this page you can find the example usage for org.springframework.dao ConcurrencyFailureException ConcurrencyFailureException.

Prototype

public ConcurrencyFailureException(String msg) 

Source Link

Document

Constructor for ConcurrencyFailureException.

Usage

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

@Override
public Pair<Long, AssociationRef> getNodeAssoc(Long assocId) {
    Pair<Long, AssociationRef> ret = getNodeAssocOrNull(assocId);
    if (ret == null) {
        throw new ConcurrencyFailureException("Assoc ID does not point to a valid association: " + assocId);
    } else {/*ww  w  .ja  v  a 2 s . co  m*/
        return ret;
    }
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

@Override
public void deleteChildAssoc(Long assocId) {
    ChildAssocEntity assoc = selectChildAssoc(assocId);
    if (assoc == null) {
        throw new ConcurrencyFailureException("Child association not found: " + assocId
                + ".  A concurrency violation is likely.\n"
                + "This can also occur if code reacts to 'beforeDelete' callbacks and pre-emptively deletes associations \n"
                + "that are about to be cascade-deleted.  The 'onDelete' phase then fails to delete the association.\n"
                + "See links on issue ALF-12358."); // TODO: Get docs URL
    }//from   w  w  w.j a va  2s.  c om
    // Update cache
    Long childNodeId = assoc.getChildNode().getId();
    ParentAssocsInfo parentAssocInfo = getParentAssocsCached(childNodeId);
    // Delete it
    List<Long> assocIds = Collections.singletonList(assocId);
    int count = deleteChildAssocs(assocIds);
    if (count != 1) {
        throw new ConcurrencyFailureException("Child association not deleted: " + assocId);
    }
    // Touch the node; parent assocs have been updated
    touchNode(childNodeId, null, null, false, false, true);
    // Update cache
    parentAssocInfo = parentAssocInfo.removeAssoc(assocId);
    setParentAssocsCached(childNodeId, parentAssocInfo);
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

@Override
public Pair<Long, ChildAssociationRef> getChildAssoc(Long assocId) {
    ChildAssocEntity assoc = selectChildAssoc(assocId);
    if (assoc == null) {
        throw new ConcurrencyFailureException("Child association not found: " + assocId);
    }//from  w w  w. j ava2  s.c  om
    return assoc.getPair(qnameDAO);
}

From source file:org.alfresco.email.server.EmailServiceImpl.java

/**
 * Process the message. Method is called after filtering by sender's address.
 * @param delivery - who gets the message and who is it from (may be different from the contents of the message)
 * @param nodeRef Addressed node (target node).
 * @param message Email message/*w  w w  .  j  a  v  a 2s  .co m*/
 * @throws EmailMessageException Any exception occured inside the method will be converted and thrown as <code>EmailMessageException</code>
 */
private void processMessage(final EmailDelivery delivery, final NodeRef nodeRef, final EmailMessage message) {
    if (!emailInboundEnabled) {
        throw new EmailMessageException(ERR_INBOUND_EMAIL_DISABLED);
    }
    try {
        // Get the username for the process using the system account
        final RetryingTransactionCallback<String> getUsernameCallback = new RetryingTransactionCallback<String>() {

            public String execute() throws Throwable {
                String userName = null;

                userName = getUsername(delivery.getFrom());
                if (userName == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("unable to find user for from: " + delivery.getFrom()
                                + ",trying message.from next");
                    }
                    userName = getUsername(message.getFrom());
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("userName = : " + userName);
                }

                if (userName == null) {
                    if (unknownUser.isEmpty()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("unable to find user for from: " + message.getFrom());
                        }
                        throw new EmailMessageException(ERR_UNKNOWN_SOURCE_ADDRESS, message.getFrom());
                    } else {
                        if (logger.isDebugEnabled()) {
                            logger.debug("unable to find user for from - return anonymous: ");
                        }
                        userName = unknownUser;
                    }
                }

                // Ensure that the user is part of the Email Contributors group
                if (userName == null || !isEmailContributeUser(userName)) {
                    throw new EmailMessageException(ERR_USER_NOT_EMAIL_CONTRIBUTOR, userName);
                }

                return userName;
            }
        };
        RunAsWork<String> getUsernameRunAsWork = new RunAsWork<String>() {
            public String doWork() throws Exception {
                return retryingTransactionHelper.doInTransaction(getUsernameCallback, false);
            }
        };

        String username;
        if (delivery.getAuth() != null) {
            // The user has authenticated.
            username = delivery.getAuth();
            logger.debug("user has already authenticated as:" + username);
        } else {
            // Need to faff with old message stuff.
            username = AuthenticationUtil.runAs(getUsernameRunAsWork, AuthenticationUtil.SYSTEM_USER_NAME);
        }

        // Process the message using the username's account
        final RetryingTransactionCallback<Object> processMessageCallback = new RetryingTransactionCallback<Object>() {
            public Object execute() throws Throwable {
                //String recipient = message.getTo();
                String recipient = delivery.getRecipient();
                NodeRef targetNodeRef = null;
                if (nodeRef == null) {
                    targetNodeRef = getTargetNode(recipient);
                } else {
                    targetNodeRef = nodeRef;
                }
                EmailMessageHandler messageHandler = getMessageHandler(targetNodeRef);
                try {
                    messageHandler.processMessage(targetNodeRef, message);
                } catch (DuplicateChildNodeNameException e) {
                    throw new ConcurrencyFailureException(e.getMessage());
                }
                return null;
            }
        };
        RunAsWork<Object> processMessageRunAsWork = new RunAsWork<Object>() {
            public Object doWork() throws Exception {
                return retryingTransactionHelper.doInTransaction(processMessageCallback, false);
            }
        };
        AuthenticationUtil.runAs(processMessageRunAsWork, username);
    } catch (EmailMessageException e) {
        // These are email-specific errors
        throw e;
    } catch (AccessDeniedException e) {
        throw new EmailMessageException(ERR_ACCESS_DENIED, delivery.getFrom(), delivery.getRecipient());
    } catch (IntegrityException e) {
        throw new EmailMessageException(ERR_INVALID_SUBJECT);
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Email message processing failed", e);
    }
}

From source file:org.alfresco.repo.admin.RepoAdminServiceImpl.java

@Override
public NodeRef deployModel(InputStream modelStream, String modelFileName, boolean activate) {
    try {//from   w w w.  j  a v  a  2 s  .  c o  m
        // Check that all the passed values are not null
        ParameterCheck.mandatory("ModelStream", modelStream);
        ParameterCheck.mandatoryString("ModelFileName", modelFileName);

        Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
        contentProps.put(ContentModel.PROP_NAME, modelFileName);

        StoreRef storeRef = repoModelsLocation.getStoreRef();
        NodeRef rootNode = nodeService.getRootNode(storeRef);

        List<NodeRef> nodeRefs = searchService.selectNodes(rootNode, repoModelsLocation.getPath(), null,
                namespaceService, false);

        if (nodeRefs.size() == 0) {
            throw new AlfrescoRuntimeException(MODELS_LOCATION_NOT_FOUND,
                    new Object[] { repoModelsLocation.getPath() });
        } else if (nodeRefs.size() > 1) {
            // unexpected: should not find multiple nodes with same name
            throw new AlfrescoRuntimeException(MODELS_LOCATION_MULTIPLE_FOUND,
                    new Object[] { repoModelsLocation.getPath() });
        }

        NodeRef customModelsSpaceNodeRef = nodeRefs.get(0);

        nodeRefs = searchService.selectNodes(customModelsSpaceNodeRef,
                "*[@cm:name='" + modelFileName + "' and " + defaultSubtypeOfDictionaryModel + "]", null,
                namespaceService, false);

        NodeRef modelNodeRef = null;

        if (nodeRefs.size() == 1) {
            // re-deploy existing model to the repository       

            modelNodeRef = nodeRefs.get(0);
        } else {
            // deploy new model to the repository

            try {
                // note: dictionary model type has associated policies that will be invoked
                ChildAssociationRef association = nodeService.createNode(customModelsSpaceNodeRef,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, modelFileName),
                        ContentModel.TYPE_DICTIONARY_MODEL, contentProps); // also invokes policies for DictionaryModelType - e.g. onUpdateProperties

                modelNodeRef = association.getChildRef();
            } catch (DuplicateChildNodeNameException dcnne) {
                String msg = "Model already exists: " + modelFileName + " - " + dcnne;
                logger.warn(msg);

                // for now, assume concurrency failure
                throw new ConcurrencyFailureException(getLocalisedMessage(MODEL_EXISTS, modelFileName));
            }

            // add titled aspect (for Web Client display)
            Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
            titledProps.put(ContentModel.PROP_TITLE, modelFileName);
            titledProps.put(ContentModel.PROP_DESCRIPTION, modelFileName);
            nodeService.addAspect(modelNodeRef, ContentModel.ASPECT_TITLED, titledProps);

            // add versionable aspect (set auto-version)
            Map<QName, Serializable> versionProps = new HashMap<QName, Serializable>();
            versionProps.put(ContentModel.PROP_AUTO_VERSION, true);
            nodeService.addAspect(modelNodeRef, ContentModel.ASPECT_VERSIONABLE, versionProps);
        }

        ContentWriter writer = contentService.getWriter(modelNodeRef, ContentModel.PROP_CONTENT, true);

        writer.setMimetype(MimetypeMap.MIMETYPE_XML);
        writer.setEncoding("UTF-8");

        writer.putContent(modelStream); // also invokes policies for DictionaryModelType - e.g. onContentUpdate
        modelStream.close();

        // activate the model
        nodeService.setProperty(modelNodeRef, ContentModel.PROP_MODEL_ACTIVE, Boolean.valueOf(activate));

        // note: model will be loaded as part of DictionaryModelType.beforeCommit()

        return modelNodeRef;
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException(MODEL_DEPLOYMENT_FAILED, e);
    }
}

From source file:org.alfresco.repo.admin.RepoAdminServiceImpl.java

public QName undeployModel(String modelFileName) {
    // Check that all the passed values are not null
    ParameterCheck.mandatory("modelFileName", modelFileName);

    QName modelQName = null;//from   www.  ja va 2s.c o m

    try {
        // find model in repository

        StoreRef storeRef = repoModelsLocation.getStoreRef();
        NodeRef rootNode = nodeService.getRootNode(storeRef);

        List<NodeRef> nodeRefs = null;
        try {
            nodeRefs = searchService.selectNodes(rootNode, repoModelsLocation.getPath() + "//.[@cm:name='"
                    + modelFileName + "' and " + defaultSubtypeOfDictionaryModel + "]", null, namespaceService,
                    false);
        } catch (InvalidNodeRefException inre) {
            String msg = "Model no longer exists: " + modelFileName + " - " + inre;
            logger.warn(msg);
            // for now, assume concurrency failure
            throw new ConcurrencyFailureException(getLocalisedMessage(MODEL_NO_LONGER_EXISTS, modelFileName));
        }

        if (nodeRefs.size() == 0) {
            throw new AlfrescoRuntimeException(MODEL_NOT_FOUND, new Object[] { modelFileName });
        } else if (nodeRefs.size() > 1) {
            // unexpected: should not find multiple nodes with same name
            throw new AlfrescoRuntimeException(MODELS_MULTIPLE_FOUND, new Object[] { modelFileName });
        }

        NodeRef modelNodeRef = nodeRefs.get(0);

        boolean isActive = false;
        Boolean value = (Boolean) nodeService.getProperty(modelNodeRef, ContentModel.PROP_MODEL_ACTIVE);
        if (value != null) {
            isActive = value.booleanValue();
        }

        modelQName = (QName) nodeService.getProperty(modelNodeRef, ContentModel.PROP_MODEL_NAME);

        ModelDefinition modelDef = null;
        if (modelQName != null) {
            try {
                modelDef = dictionaryDAO.getModel(modelQName);
            } catch (DictionaryException e) {
                logger.warn(e);
            }
        }

        if (isActive) {
            if (modelDef == null) {
                logger.warn("Model is set to active but not loaded in Dictionary - trying to undeploy...");
            }
        }

        // permanently remove model from repository
        nodeService.addAspect(modelNodeRef, ContentModel.ASPECT_TEMPORARY, null);

        try {
            nodeService.deleteNode(modelNodeRef);
        } catch (DictionaryException de) {
            String msg = "Model undeployment failed: " + modelFileName + " - " + de;
            logger.warn(msg);
            // for now, assume concurrency failure
            throw new ConcurrencyFailureException(msg);
        }

        // note: deleted model will be unloaded as part of DictionaryModelType.beforeCommit()
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException(MODEL_UNDEPLOYMENT_FAILED, e);
    }

    return modelQName;
}

From source file:org.alfresco.repo.blog.BlogServiceImpl.java

@Override
public BlogPostInfo createBlogPost(NodeRef blogContainerNode, String blogTitle, String blogContent,
        boolean isDraft) {
    final String nodeName = getUniqueChildName(blogContainerNode, "post");

    // we simply create a new file inside the blog folder
    Map<QName, Serializable> nodeProps = new HashMap<QName, Serializable>();
    nodeProps.put(ContentModel.PROP_NAME, nodeName);
    nodeProps.put(ContentModel.PROP_TITLE, blogTitle);
    QName assocName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName);
    ChildAssociationRef postNode = null;
    try {/*  w  w  w .  j av  a2s.c  o m*/
        postNode = nodeService.createNode(blogContainerNode, ContentModel.ASSOC_CONTAINS, assocName,
                ContentModel.TYPE_CONTENT, nodeProps);
    } catch (DuplicateChildNodeNameException e) {
        // This will be rare, but it's not impossible.
        // We have to retry the operation.
        throw new ConcurrencyFailureException("Blog post name already used: " + nodeName);
    }

    ContentWriter writer = contentService.getWriter(postNode.getChildRef(), ContentModel.PROP_CONTENT, true);

    // Blog posts are always HTML (based on the JavaScript this class replaces.)
    writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
    writer.setEncoding("UTF-8");
    writer.putContent(blogContent);

    if (isDraft) {
        // Comment from the old JavaScript:
        // disable permission inheritance. The result is that only the creator will have access to the draft
        NodeRef draft = postNode.getChildRef();
        permissionService.setInheritParentPermissions(draft, false);

        // MNT-12082: give permissions to the post creator. He should be able to comment in his post's
        // forumFolder and commentsFolder, where owner is System user
        String creator = (String) nodeService.getProperty(draft, ContentModel.PROP_CREATOR);
        permissionService.setPermission(draft, creator, permissionService.getAllPermission(), true);
    } else {
        setOrUpdateReleasedAndUpdatedDates(postNode.getChildRef());
    }

    BlogPostInfo post = new BlogPostInfoImpl(postNode.getChildRef(), blogContainerNode, nodeName);
    post.setTitle(blogTitle);
    return post;
}

From source file:org.alfresco.repo.domain.audit.AbstractAuditDAOImpl.java

public int deleteAuditEntries(List<Long> auditEntryIds) {
    // Ensure that we don't have duplicates
    Set<Long> ids = new TreeSet<Long>(auditEntryIds);
    int shouldDelete = ids.size();

    int deleted = 0;
    List<Long> batch = new ArrayList<Long>(shouldDelete > 512 ? 512 : shouldDelete);
    for (Long id : ids) {
        batch.add(id);/*from w  w  w  .  j a  va2  s . com*/
        if (batch.size() >= 512) {
            deleted += deleteAuditEntriesImpl(batch);
            batch.clear();
        }
    }
    // Process remaining
    if (batch.size() > 0) {
        deleted += deleteAuditEntriesImpl(batch);
    }
    // Check concurrency
    if (deleted != shouldDelete) {
        throw new ConcurrencyFailureException(
                "Deleted " + deleted + " audit entries out of a set of " + shouldDelete + " unique IDs.");
    }
    return deleted;
}

From source file:org.alfresco.repo.domain.contentdata.AbstractContentDataDAOImpl.java

@Override
public void updateContentData(Long id, ContentData contentData) {
    if (id == null) {
        throw new IllegalArgumentException("Cannot look up ContentData by null ID.");
    }//  w  ww  .j a  v  a  2  s . c om
    if (contentData == null) {
        throw new IllegalArgumentException("Cannot update ContentData with a null.");
    }
    int updated = contentDataCache.updateValue(id, contentData);
    if (updated < 1) {
        throw new ConcurrencyFailureException("ContentData with ID " + id + " not updated");
    }
}

From source file:org.alfresco.repo.domain.contentdata.AbstractContentDataDAOImpl.java

@Override
public void deleteContentData(Long id) {
    if (id == null) {
        throw new IllegalArgumentException("Cannot delete ContentData by null ID.");
    }/*from   w  ww.ja v a 2  s .c  om*/
    int deleted = contentDataCache.deleteByKey(id);
    if (deleted < 1) {
        throw new ConcurrencyFailureException("ContentData with ID " + id + " no longer exists");
    }
    return;
}