Example usage for org.springframework.transaction.interceptor TransactionAspectSupport currentTransactionStatus

List of usage examples for org.springframework.transaction.interceptor TransactionAspectSupport currentTransactionStatus

Introduction

In this page you can find the example usage for org.springframework.transaction.interceptor TransactionAspectSupport currentTransactionStatus.

Prototype

public static TransactionStatus currentTransactionStatus() throws NoTransactionException 

Source Link

Document

Return the transaction status of the current method invocation.

Usage

From source file:org.alfresco.util.transaction.SpringAwareUserTransactionTest.java

private void checkNoStatusOnThread() {
    try {/*from   www  . j a  va 2 s.  c o  m*/
        TransactionAspectSupport.currentTransactionStatus();
        fail("Spring transaction info is present outside of transaction boundaries");
    } catch (NoTransactionException e) {
        // expected
    }
}

From source file:com.qcadoo.model.internal.DataAccessServiceImpl.java

@Auditable
@Override//from  w w w . jav  a 2 s .c  o m
@Transactional
@Monitorable
public Entity save(final InternalDataDefinition dataDefinition, final Entity genericEntity) {
    Set<Entity> newlySavedEntities = new HashSet<Entity>();

    Entity resultEntity = performSave(dataDefinition, genericEntity, new HashSet<Entity>(), newlySavedEntities);
    try {
        if (TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()) {
            resultEntity.setNotValid();
            for (Entity e : newlySavedEntities) {
                e.setId(null);
            }
        }
    } catch (NoTransactionException e) {
        LOG.error(e.getMessage(), e);
    }
    return resultEntity;
}

From source file:org.exitcode.spring.torque.tx.SpringTransactionManagerAdapter.java

private void markTxForRollback() {
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}

From source file:com.qcadoo.mes.productionPerShift.util.ProgressPerShiftViewSaver.java

private void rollbackCurrentTransaction() {
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}

From source file:org.grails.datastore.gorm.jpa.EntityInterceptorInvokingEntityListener.java

void rollbackTransaction(JpaSession jpaSession) {
    final Transaction<?> transaction = jpaSession.getTransaction();
    if (transaction != null) {
        transaction.rollback();/*from w w  w.  j a  v a  2  s . c  o m*/
    } else {
        try {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } catch (NoTransactionException e) {
            // ignore
        }
    }
}

From source file:org.artifactory.repo.db.DbStoringRepoMixin.java

/**
 * Create the resource in the local repository
 *//*from  w w w  .j  a  va2s  .com*/
@SuppressWarnings("unchecked")
public RepoResource saveResource(SaveResourceContext context) throws IOException, RepoRejectException {
    RepoResource res = context.getRepoResource();
    RepoPath repoPath = InternalRepoPathFactory.create(getKey(), res.getRepoPath().getPath());
    MutableVfsFile mutableFile = null;
    try {
        //Create the parent folder if it does not exist
        RepoPath parentPath = repoPath.getParent();
        if (parentPath == null) {
            throw new StorageException("Cannot save resource, no parent repo path exists");
        }

        // get or create the file. also creates any ancestors on the path to this item
        mutableFile = createOrGetFile(repoPath);

        invokeBeforeCreateInterceptors(mutableFile);

        setClientChecksums(res, mutableFile);

        /**
         * If the file isn't a non-unique snapshot and it already exists, create a defensive of the checksums
         * info for later comparison
         */
        boolean isNonUniqueSnapshot = MavenNaming.isNonUniqueSnapshot(repoPath.getId());
        String overriddenFileSha1 = null;
        if (!isNonUniqueSnapshot && !mutableFile.isNew()) {
            overriddenFileSha1 = mutableFile.getSha1();
            log.debug("Overriding {} with sha1: {}", mutableFile.getRepoPath(), overriddenFileSha1);
        }

        fillBinaryData(context, mutableFile);

        verifyChecksum(mutableFile);

        if (jarValidationRequired(repoPath)) {
            validateArtifactIfRequired(mutableFile, repoPath);
        }

        long lastModified = res.getInfo().getLastModified();
        mutableFile.setModified(lastModified);
        mutableFile.setUpdated(lastModified);

        String userId = authorizationService.currentUsername();
        mutableFile.setModifiedBy(userId);
        if (mutableFile.isNew()) {
            mutableFile.setCreatedBy(userId);
        }

        // allow admin override of selected file details (i.e., override when replicating)
        overrideFileDetailsFromRequest(context, mutableFile);

        updateResourceWithActualBinaryData(res, mutableFile);

        clearOldFileData(mutableFile, isNonUniqueSnapshot, overriddenFileSha1);

        Properties properties = context.getProperties();
        if (properties != null) {
            saveProperties(context, mutableFile);
        }

        invokeAfterCreateInterceptors(mutableFile);
        AccessLogger.deployed(repoPath);
        return res;
    } catch (Exception e) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        if (mutableFile != null) {
            mutableFile.markError();
        }
        // throw back any CancelException
        if (e instanceof CancelException) {
            if (mutableFile != null) {
                LockingHelper.removeLockEntry(mutableFile.getRepoPath());
            }
            RepoRejectException repoRejectException = new RepoRejectException(e);
            context.setException(repoRejectException);
            throw repoRejectException;
        }

        // throw back any RepoRejectException (ChecksumPolicyException etc)
        Throwable rejectException = ExceptionUtils.getCauseOfTypes(e, RepoRejectException.class);
        if (rejectException != null) {
            context.setException(rejectException);
            throw (RepoRejectException) rejectException;
        }
        //Unwrap any IOException and throw it
        Throwable ioCause = ExceptionUtils.getCauseOfTypes(e, IOException.class);
        if (ioCause != null) {
            log.error("IO error while trying to save resource {}'': {}: {}", res.getRepoPath(),
                    ioCause.getClass().getName(), ioCause.getMessage());
            log.debug("IO error while trying to save resource {}'': {}", res.getRepoPath(),
                    ioCause.getMessage(), ioCause);
            context.setException(ioCause);
            throw (IOException) ioCause;
        }

        // Throw any RuntimeException instances
        if (e instanceof RuntimeException) {
            context.setException(e);
            throw e;
        }

        context.setException(e);
        throw new RuntimeException("Failed to save resource '" + res.getRepoPath() + "'.", e);
    }
}

From source file:com.qcadoo.mes.genealogies.AutoGenealogyService.java

public void createGenealogy(final Entity order, final MessagesHolder messagesHolder,
        final boolean lastUsedMode) {
    Entity mainProduct = order.getBelongsToField(PRODUCT_MODEL);
    Entity technology = order.getBelongsToField(TECHNOLOGY_FIELD);
    if (mainProduct == null || technology == null) {
        messagesHolder.addMessage("genealogies.message.autoGenealogy.failure.product", StateMessageType.INFO);
        return;/*w ww . ja  v  a2  s.c  o  m*/
    }
    Object mainBatch = null;
    if (lastUsedMode) {
        mainBatch = mainProduct.getField(LAST_USED_BATCH_FIELD);
    } else {
        mainBatch = mainProduct.getField(BATCH_MODEL);
    }
    if (mainBatch == null) {
        messagesHolder.addMessage("genealogies.message.autoGenealogy.missingMainBatch", StateMessageType.INFO);
        return;
    }
    if (checkIfExistGenealogyWithBatch(order, mainBatch.toString())) {
        messagesHolder.addMessage("genealogies.message.autoGenealogy.genealogyExist", StateMessageType.INFO);
        return;
    }
    DataDefinition genealogyDef = dataDefinitionService.get(GenealogiesConstants.PLUGIN_IDENTIFIER,
            GenealogiesConstants.MODEL_GENEALOGY);
    Entity genealogy = genealogyDef.create();
    genealogy.setField(ORDER_MODEL, order);
    genealogy.setField(BATCH_MODEL, mainBatch);
    completeAttributesForGenealogy(technology, genealogy, lastUsedMode);
    if (pluginManager.isPluginEnabled(GENEALOGIES_FOR_COMPONENTS_PLUGIN)) {
        completeBatchForComponents(technology, genealogy, lastUsedMode);
    }

    if (genealogy.isValid()) {
        genealogy = genealogyDef.save(genealogy);
    }

    if (genealogy.isValid()) {
        messagesHolder.addMessage("genealogies.message.autoGenealogy.success", StateMessageType.SUCCESS);
    } else {
        if (genealogy.getGlobalErrors().isEmpty()) {
            messagesHolder.addMessage("genealogies.message.autoGenealogy.failure", StateMessageType.INFO);
        } else {
            for (ErrorMessage error : genealogy.getGlobalErrors()) {
                messagesHolder.addMessage(error.getMessage(), StateMessageType.FAILURE, error.getVars());
            }
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}

From source file:com.qcadoo.model.internal.DataAccessServiceImpl.java

private void rollbackAndAddGlobalError(final Entity savedEntity, final Entity errorEntity) {
    String msg = String.format(
            "Can not save entity '%s' because related entity '%s' has following validation errors:",
            savedEntity, errorEntity);//ww  w  .  ja  va  2s .  c  o m
    logEntityErrors(errorEntity, msg);
    savedEntity.addGlobalError("qcadooView.validate.field.error.invalidRelatedObject");
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}

From source file:com.qcadoo.mes.productionPerShift.util.ProgressPerShiftViewSaver.java

@Transactional(propagation = Propagation.REQUIRES_NEW)
private Either<Entity, Void> tryValidateDailyProgress(final Entity dailyProgress) {
    Entity savedDailyProgress = saved(dailyProgress);
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    // reset id to avoid 'entity cannot be found' exceptions.
    savedDailyProgress.setId(dailyProgress.getId());
    if (savedDailyProgress.isValid()) {
        return Either.right(null);
    }//  w w w  . j a v  a2 s . c o m
    return Either.left(savedDailyProgress);
}

From source file:org.openregistry.core.service.DefaultPersonService.java

@PreAuthorize("hasPermission(#sorRole, 'admin')")
public ServiceExecutionResult<SorRole> validateAndSaveRoleForSorPerson(final SorPerson sorPerson,
        final SorRole sorRole) {
    logger.info(" validateAndSaveRoleForSorPerson start");
    Assert.notNull(sorPerson, "SorPerson cannot be null.");
    Assert.notNull(sorRole, "SorRole cannot be null.");

    // check if the SoR Role has an ID assigned to it already and assign source sor
    setRoleIdAndSource(sorRole, sorPerson.getSourceSor());

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384/*from  www. ja v  a 2 s . c o m*/
        if (TransactionAspectSupport.currentTransactionStatus() != null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorPerson newSorPerson = this.personRepository.saveSorPerson(sorPerson);
    Person person = this.personRepository.findByInternalId(newSorPerson.getPersonId());
    final SorRole newSorRole = newSorPerson.findSorRoleBySorRoleId(sorRole.getSorId());
    //let sor role elector decide if this new role can be converted to calculated one
    sorRoleElector.addSorRole(newSorRole, person);
    person = recalculatePersonBiodemInfo(person, newSorPerson, RecalculationType.UPDATE, false);
    this.personRepository.savePerson(person);
    logger.info("validateAndSaveRoleForSorPerson end");
    return new GeneralServiceExecutionResult<SorRole>(newSorRole);
}