Search in sources :

Example 16 with TransactionException

use of org.springframework.transaction.TransactionException in project spring-framework by spring-projects.

the class AbstractReactiveTransactionManager method getReactiveTransaction.

// ---------------------------------------------------------------------
// Implementation of ReactiveTransactionManager
// ---------------------------------------------------------------------
/**
 * This implementation handles propagation behavior. Delegates to
 * {@code doGetTransaction}, {@code isExistingTransaction}
 * and {@code doBegin}.
 * @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.forCurrentTransaction().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));
        }
    });
}
Also used : TransactionDefinition(org.springframework.transaction.TransactionDefinition) TransactionSuspensionNotSupportedException(org.springframework.transaction.TransactionSuspensionNotSupportedException) Predicate(java.util.function.Predicate) TransactionDefinition(org.springframework.transaction.TransactionDefinition) ObjectInputStream(java.io.ObjectInputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) ReactiveTransaction(org.springframework.transaction.ReactiveTransaction) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) ReactiveTransactionManager(org.springframework.transaction.ReactiveTransactionManager) Serializable(java.io.Serializable) Flux(reactor.core.publisher.Flux) List(java.util.List) InvalidTimeoutException(org.springframework.transaction.InvalidTimeoutException) TransactionException(org.springframework.transaction.TransactionException) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) Nullable(org.springframework.lang.Nullable) LogFactory(org.apache.commons.logging.LogFactory) InvalidTimeoutException(org.springframework.transaction.InvalidTimeoutException) Optional(java.util.Optional) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException)

Example 17 with TransactionException

use of org.springframework.transaction.TransactionException in project spring-framework by spring-projects.

the class AbstractPollingMessageListenerContainer method receiveAndExecute.

/**
 * Execute the listener for a message received from the given consumer,
 * wrapping the entire operation in an external transaction if demanded.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doReceiveAndExecute
 */
protected boolean receiveAndExecute(Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer) throws JMSException {
    if (this.transactionManager != null) {
        // Execute receive within transaction.
        TransactionStatus status = this.transactionManager.getTransaction(this.transactionDefinition);
        boolean messageReceived;
        try {
            messageReceived = doReceiveAndExecute(invoker, session, consumer, status);
        } catch (JMSException | RuntimeException | Error ex) {
            rollbackOnException(this.transactionManager, status, ex);
            throw ex;
        }
        try {
            this.transactionManager.commit(status);
        } catch (TransactionException ex) {
            // Propagate transaction system exceptions as infrastructure problems.
            throw ex;
        } catch (RuntimeException ex) {
            // Typically a late persistence exception from a listener-used resource
            // -> handle it as listener exception, not as an infrastructure problem.
            // E.g. a database locking failure should not lead to listener shutdown.
            handleListenerException(ex);
        }
        return messageReceived;
    } else {
        // Execute receive outside of transaction.
        return doReceiveAndExecute(invoker, session, consumer, null);
    }
}
Also used : TransactionException(org.springframework.transaction.TransactionException) TransactionStatus(org.springframework.transaction.TransactionStatus) JMSException(jakarta.jms.JMSException)

Example 18 with TransactionException

use of org.springframework.transaction.TransactionException in project spring-framework by spring-projects.

the class BeanFactoryTransactionTests method doTestGetsAreNotTransactional.

private void doTestGetsAreNotTransactional(final ITestBean testBean) {
    // Install facade
    PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
    PlatformTransactionManagerFacade.delegate = ptm;
    assertThat(testBean.getAge() == 666).as("Age should not be " + testBean.getAge()).isTrue();
    // Expect no methods
    verifyNoInteractions(ptm);
    // Install facade expecting a call
    final TransactionStatus ts = mock(TransactionStatus.class);
    ptm = new PlatformTransactionManager() {

        private boolean invoked;

        @Override
        public TransactionStatus getTransaction(@Nullable TransactionDefinition def) throws TransactionException {
            if (invoked) {
                throw new IllegalStateException("getTransaction should not get invoked more than once");
            }
            invoked = true;
            if (!(def.getName().contains(DerivedTestBean.class.getName()) && def.getName().contains("setAge"))) {
                throw new IllegalStateException("transaction name should contain class and method name: " + def.getName());
            }
            return ts;
        }

        @Override
        public void commit(TransactionStatus status) throws TransactionException {
            assertThat(status == ts).isTrue();
        }

        @Override
        public void rollback(TransactionStatus status) throws TransactionException {
            throw new IllegalStateException("rollback should not get invoked");
        }
    };
    PlatformTransactionManagerFacade.delegate = ptm;
    // TODO same as old age to avoid ordering effect for now
    int age = 666;
    testBean.setAge(age);
    assertThat(testBean.getAge() == age).isTrue();
}
Also used : TransactionDefinition(org.springframework.transaction.TransactionDefinition) TransactionException(org.springframework.transaction.TransactionException) TransactionStatus(org.springframework.transaction.TransactionStatus) DerivedTestBean(org.springframework.beans.testfixture.beans.DerivedTestBean) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager)

Example 19 with TransactionException

use of org.springframework.transaction.TransactionException in project grails-core by grails.

the class ChainedTransactionManager method commit.

/*
	 * (non-Javadoc)
	 * @see org.springframework.transaction.PlatformTransactionManager#commit(org.springframework.transaction.TransactionStatus)
	 */
public void commit(TransactionStatus status) throws TransactionException {
    MultiTransactionStatus multiTransactionStatus = (MultiTransactionStatus) status;
    boolean commit = true;
    Exception commitException = null;
    PlatformTransactionManager commitExceptionTransactionManager = null;
    for (PlatformTransactionManager transactionManager : reverse(transactionManagers)) {
        if (commit) {
            try {
                multiTransactionStatus.commit(transactionManager);
            } catch (Exception ex) {
                commit = false;
                commitException = ex;
                commitExceptionTransactionManager = transactionManager;
            }
        } else {
            try {
                multiTransactionStatus.rollback(transactionManager);
            } catch (Exception ex) {
                LOGGER.warn("Rollback exception (after commit) (" + transactionManager + ") " + ex.getMessage(), ex);
            }
        }
    }
    if (multiTransactionStatus.isNewSynchronization()) {
        synchronizationManager.clearSynchronization();
    }
    if (commitException != null) {
        boolean firstTransactionManagerFailed = commitExceptionTransactionManager == getLastTransactionManager();
        int transactionState = firstTransactionManagerFailed ? HeuristicCompletionException.STATE_ROLLED_BACK : HeuristicCompletionException.STATE_MIXED;
        throw new HeuristicCompletionException(transactionState, commitException);
    }
}
Also used : HeuristicCompletionException(org.springframework.transaction.HeuristicCompletionException) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) TransactionException(org.springframework.transaction.TransactionException) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) HeuristicCompletionException(org.springframework.transaction.HeuristicCompletionException) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager)

Aggregations

TransactionException (org.springframework.transaction.TransactionException)19 CannotCreateTransactionException (org.springframework.transaction.CannotCreateTransactionException)8 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)8 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)7 HeuristicCompletionException (org.springframework.transaction.HeuristicCompletionException)6 TransactionDefinition (org.springframework.transaction.TransactionDefinition)4 IllegalTransactionStateException (org.springframework.transaction.IllegalTransactionStateException)3 TransactionStatus (org.springframework.transaction.TransactionStatus)3 IOException (java.io.IOException)2 ObjectInputStream (java.io.ObjectInputStream)2 Serializable (java.io.Serializable)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Predicate (java.util.function.Predicate)2 Log (org.apache.commons.logging.Log)2 LogFactory (org.apache.commons.logging.LogFactory)2 Nullable (org.springframework.lang.Nullable)2 DataGridUser (com.emc.metalnx.core.domain.entity.DataGridUser)1