Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_MANDATORY

List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_MANDATORY

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition PROPAGATION_MANDATORY.

Prototype

int PROPAGATION_MANDATORY

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_MANDATORY.

Click Source Link

Document

Support a current transaction; throw an exception if no current transaction exists.

Usage

From source file:app.core.TransactionPositiveTest.java

@Test(expected = IllegalTransactionStateException.class)
public void test1() {
    transactionManager/*from   w ww.  jav  a  2s. co  m*/
            .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
}

From source file:org.dalesbred.integration.spring.SpringTransactionManager.java

@Override
public <T> T withCurrentTransaction(@NotNull TransactionCallback<T> callback, @NotNull Dialect dialect) {
    return execute(callback, dialect,
            new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
}

From source file:org.dalesbred.integration.spring.SpringTransactionManager.java

static int springPropagationCode(@NotNull Propagation propagation) {
    switch (propagation) {
    case REQUIRED:
        return TransactionDefinition.PROPAGATION_REQUIRED;
    case MANDATORY:
        return TransactionDefinition.PROPAGATION_MANDATORY;
    case NESTED://  www.  j a  v a  2s .c o  m
        return TransactionDefinition.PROPAGATION_NESTED;
    case REQUIRES_NEW:
        return TransactionDefinition.PROPAGATION_REQUIRES_NEW;
    }
    throw new IllegalArgumentException("unknown propagation: " + propagation);
}

From source file:org.nabucco.alfresco.enhScriptEnv.repo.script.batch.RepositoryExecuteBatchWorker.java

/**
 * /*w  ww. j  a  va 2s  . c o m*/
 * {@inheritDoc}
 */
@Override
public void process(final Object entry) throws Throwable {
    try {
        try {
            super.doProcess(entry);
        } catch (final WrappedException ex) {
            // super should already handle unwrap runtime exceptions
            final Throwable wrappedException = ex.getWrappedException();
            if (wrappedException instanceof RuntimeException) {
                // super should have handled this
                throw (RuntimeException) wrappedException;
            }
            throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
        } catch (final Throwable ex) {
            throw new AlfrescoRuntimeException(ex.getMessage(), ex);
        }
    } catch (final Throwable ex) {
        /*
         * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
         * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
         * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
         * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
         * SpringAwareUserTransaction)
         */

        final RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
        transactionAttribute.setReadOnly(true);
        transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

        final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
        if (!transaction.isRollbackOnly()) {
            LOGGER.debug("Marking transaction as rollback-only due to exception during batch processing", ex);
            transaction.setRollbackOnly();
        }

        throw ex;
    }
}

From source file:nl.nn.adapterframework.core.PipeLine.java

public boolean isTransacted() {
    //      return transacted;
    int txAtt = getTransactionAttributeNum();
    return txAtt == TransactionDefinition.PROPAGATION_REQUIRED
            || txAtt == TransactionDefinition.PROPAGATION_REQUIRES_NEW
            || txAtt == TransactionDefinition.PROPAGATION_MANDATORY;
}

From source file:org.springframework.transaction.reactive.AbstractReactiveTransactionManager.java

/**
 * This implementation handles propagation behavior. Delegates to
 * {@code doGetTransaction}, {@code isExistingTransaction}
 * and {@code doBegin}./*from  w w  w.  j ava  2  s.c o m*/
 * @see #doGetTransaction
 * @see #isExistingTransaction
 * @see #doBegin
 */
@Override
public final Mono<ReactiveTransaction> getReactiveTransaction(@Nullable TransactionDefinition definition)
        throws TransactionException {

    // Use defaults if no transaction definition given.
    TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());

    return TransactionSynchronizationManager.currentTransaction().flatMap(synchronizationManager -> {

        Object transaction = doGetTransaction(synchronizationManager);

        // Cache debug flag to avoid repeated checks.
        boolean debugEnabled = logger.isDebugEnabled();

        if (isExistingTransaction(transaction)) {
            // Existing transaction found -> check propagation behavior to find out how to behave.
            return handleExistingTransaction(synchronizationManager, def, transaction, debugEnabled);
        }

        // Check definition settings for new transaction.
        if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
            return Mono.error(new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout()));
        }

        // No existing transaction found -> check propagation behavior to find out how to proceed.
        if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
            return Mono.error(new IllegalTransactionStateException(
                    "No existing transaction found for transaction marked with propagation 'mandatory'"));
        } else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED
                || def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW
                || def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {

            return TransactionContextManager.currentContext().map(TransactionSynchronizationManager::new)
                    .flatMap(nestedSynchronizationManager -> suspend(nestedSynchronizationManager, null)
                            .map(Optional::of).defaultIfEmpty(Optional.empty()).flatMap(suspendedResources -> {
                                if (debugEnabled) {
                                    logger.debug("Creating new transaction with name [" + def.getName() + "]: "
                                            + def);
                                }
                                return Mono.defer(() -> {
                                    GenericReactiveTransaction status = newReactiveTransaction(
                                            nestedSynchronizationManager, def, transaction, true, debugEnabled,
                                            suspendedResources.orElse(null));
                                    return doBegin(nestedSynchronizationManager, transaction, def)
                                            .doOnSuccess(ignore -> prepareSynchronization(
                                                    nestedSynchronizationManager, status, def))
                                            .thenReturn(status);
                                }).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
                                        ex -> resume(nestedSynchronizationManager, null,
                                                suspendedResources.orElse(null)).then(Mono.error(ex)));
                            }));
        } else {
            // Create "empty" transaction: no actual transaction, but potentially synchronization.
            if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
                logger.warn("Custom isolation level specified but no actual transaction initiated; "
                        + "isolation level will effectively be ignored: " + def);
            }
            return Mono.just(
                    prepareReactiveTransaction(synchronizationManager, def, null, true, debugEnabled, null));
        }
    });
}

From source file:org.springframework.transaction.support.AbstractPlatformTransactionManager.java

/**
 * This implementation handles propagation behavior. Delegates to
 * {@code doGetTransaction}, {@code isExistingTransaction}
 * and {@code doBegin}./*from w  w w.j  ava  2s  .co m*/
 * @see #doGetTransaction
 * @see #isExistingTransaction
 * @see #doBegin
 */
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
        throws TransactionException {
    Object transaction = doGetTransaction();

    // Cache debug flag to avoid repeated checks.
    boolean debugEnabled = logger.isDebugEnabled();

    if (definition == null) {
        // Use defaults if no transaction definition given.
        definition = new DefaultTransactionDefinition();
    }

    if (isExistingTransaction(transaction)) {
        // Existing transaction found -> check propagation behavior to find out how to behave.
        return handleExistingTransaction(definition, transaction, debugEnabled);
    }

    // Check definition settings for new transaction.
    if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
        throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
    }

    // No existing transaction found -> check propagation behavior to find out how to proceed.
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
        throw new IllegalTransactionStateException(
                "No existing transaction found for transaction marked with propagation 'mandatory'");
    } else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED
            || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW
            || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        SuspendedResourcesHolder suspendedResources = suspend(null);
        if (debugEnabled) {
            logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
        }
        try {
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, suspendedResources);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        } catch (RuntimeException | Error ex) {
            resume(null, suspendedResources);
            throw ex;
        }
    } else {
        // Create "empty" transaction: no actual transaction, but potentially synchronization.
        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT
                && logger.isWarnEnabled()) {
            logger.warn("Custom isolation level specified but no actual transaction initiated; "
                    + "isolation level will effectively be ignored: " + definition);
        }
        boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
        return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
    }
}