org.springframework.transaction.IllegalTransactionStateException Java Examples

The following examples show how to use org.springframework.transaction.IllegalTransactionStateException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Neo4jTransactionUtils.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
/**
 * Maps a Spring {@link TransactionDefinition transaction definition} to a native Neo4j driver transaction.
 * Only the default isolation leven ({@link TransactionDefinition#ISOLATION_DEFAULT}) and
 * {@link TransactionDefinition#PROPAGATION_REQUIRED propagation required} behaviour are supported.
 *
 * @param definition The transaction definition passed to a Neo4j transaction manager
 * @return A Neo4j native transaction configuration
 */
static TransactionConfig createTransactionConfigFrom(TransactionDefinition definition) {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		throw new InvalidIsolationLevelException(
			"Neo4jTransactionManager is not allowed to support custom isolation levels.");
	}

	int propagationBehavior = definition.getPropagationBehavior();
	if (!(propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRED || propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRES_NEW)) {
		throw new IllegalTransactionStateException("Neo4jTransactionManager only supports 'required' or 'requires new' propagation.");
	}

	TransactionConfig.Builder builder = TransactionConfig.builder();
	if (definition.getTimeout() > 0) {
		builder = builder.withTimeout(Duration.ofSeconds(definition.getTimeout()));
	}

	return builder.build();
}
 
Example #2
Source File: WebSphereUowTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void propagationNeverFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #3
Source File: WebSphereUowTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void propagationMandatoryFailsInCaseOfNoExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #4
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void propagationMandatoryFailsInCaseOfNoExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #5
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void propagationNeverFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #6
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void propagationNeverFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #7
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void propagationMandatoryFailsInCaseOfNoExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #8
Source File: ReactiveTransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void noExistingTransaction() {
	ReactiveTransactionManager tm = new ReactiveTestTransactionManager(false, true);

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual ->
				assertFalse(actual.hasTransaction())
			).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED))
			.cast(GenericReactiveTransaction.class).subscriberContext(TransactionContextManager.createTransactionContext())
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertTrue(actual.hasTransaction());
				assertTrue(actual.isNewTransaction());
			}).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).expectError(IllegalTransactionStateException.class).verify();
}
 
Example #9
Source File: AbstractReactiveTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see ReactiveTransaction#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final Mono<Void> commit(ReactiveTransaction transaction) throws TransactionException {
	if (transaction.isCompleted()) {
		return Mono.error(new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction"));
	}

	return TransactionSynchronizationManager.currentTransaction().flatMap(synchronizationManager -> {
		GenericReactiveTransaction reactiveTx = (GenericReactiveTransaction) transaction;
		if (reactiveTx.isRollbackOnly()) {
			if (reactiveTx.isDebug()) {
				logger.debug("Transactional code has requested rollback");
			}
			return processRollback(synchronizationManager, reactiveTx);
		}
		return processCommit(synchronizationManager, reactiveTx);
	});
}
 
Example #10
Source File: TransactionUtilTest.java    From training with MIT License 5 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void testMandatoryFailsWhenInvokedWithoutTx() {
	txUtil.executeWith_MANDATORY(new Runnable() {
		@Override
		public void run() {
			fail("Must never reach this point!");
		}
	});
}
 
Example #11
Source File: GridSpringTransactionManagerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testMandatoryPropagation() {
    try {
        service().putWithMandatoryPropagation(cache());
    }
    catch (IllegalTransactionStateException e) {
        assertEquals("No existing transaction found for transaction marked with propagation 'mandatory'", e.getMessage());
    }

    assertEquals(0, cache().size());
}
 
Example #12
Source File: OptimisticConcurrencyControlAspect.java    From db-util with Apache License 2.0 5 votes vote down vote up
private Object proceed(ProceedingJoinPoint pjp, Retry retryAnnotation) throws Throwable {
    int times = retryAnnotation.times();
    Class<? extends Throwable>[] retryOn = retryAnnotation.on();
    Assert.isTrue(times > 0, "@Retry{times} should be greater than 0!");
    Assert.isTrue(retryOn.length > 0, "@Retry{on} should have at least one Throwable!");
    if (retryAnnotation.failInTransaction() && TransactionSynchronizationManager.isActualTransactionActive()) {
        throw new IllegalTransactionStateException(
                "You shouldn't retry an operation from within an existing Transaction." +
                        "This is because we can't retry if the current Transaction was already rolled back!");
    }
    LOGGER.info("Proceed with {} retries on {}", times, Arrays.toString(retryOn));
    return tryProceeding(pjp, times, retryOn);
}
 
Example #13
Source File: TransactionUtilTest.java    From training with MIT License 5 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void testMandatoryFailsWhenInvokedWithoutTx() {
	txUtil.executeWith_MANDATORY(new Runnable() {
		@Override
		public void run() {
			fail("Must never reach this point!");
		}
	});
}
 
Example #14
Source File: OptimisticConcurrencyControlAspectTest.java    From db-util with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void testRetryFailsOnTransaction() {
    try {
        TransactionSynchronizationManager.setActualTransactionActive(true);
        itemService.saveItem();
    } finally {
        TransactionSynchronizationManager.setActualTransactionActive(false);
    }
}
 
Example #15
Source File: FooTransactionalUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() {
    mandatoryTransactionalFooService.identity(new Foo("baeldung"));
    PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
    Assert.assertEquals(0, transactionSpy.getSuspend());
    Assert.assertEquals(0, transactionSpy.getCreate());
}
 
Example #16
Source File: FooTransactionalUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() {
    transactionTemplate.execute(status -> {
        Foo foo = new Foo("baeldung");
        return neverTransactionalFooService.identity(foo);
    });
    PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
    Assert.assertEquals(0, transactionSpy.getSuspend());
    Assert.assertEquals(1, transactionSpy.getCreate());
}
 
Example #17
Source File: AbstractPlatformTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus, false);
		return;
	}

	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus, true);
		return;
	}

	processCommit(defStatus);
}
 
Example #18
Source File: AbstractPlatformTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus);
}
 
Example #19
Source File: AbstractPlatformTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus);
		return;
	}
	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus);
		// Throw UnexpectedRollbackException only at outermost transaction boundary
		// or if explicitly asked to.
		if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
			throw new UnexpectedRollbackException(
					"Transaction rolled back because it has been marked as rollback-only");
		}
		return;
	}

	processCommit(defStatus);
}
 
Example #20
Source File: AbstractPlatformTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus);
}
 
Example #21
Source File: AbstractPlatformTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus);
		return;
	}
	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus);
		// Throw UnexpectedRollbackException only at outermost transaction boundary
		// or if explicitly asked to.
		if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
			throw new UnexpectedRollbackException(
					"Transaction rolled back because it has been marked as rollback-only");
		}
		return;
	}

	processCommit(defStatus);
}
 
Example #22
Source File: PlatformTransactionManagerAdapter.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction getTransaction() throws SystemException {
    try {
        if (platformTransactionManager == null) {
            return null;
        }
        TransactionHolder holder = getOrCreateTransaction(false);
        if (holder == null) {
            return null;
        }
        return holder.transaction;
    } catch (IllegalTransactionStateException e) {
        return null;
    }
}
 
Example #23
Source File: AbstractPlatformTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus, false);
}
 
Example #24
Source File: AbstractPlatformTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus, false);
		return;
	}

	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus, true);
		return;
	}

	processCommit(defStatus);
}
 
Example #25
Source File: AbstractReactiveTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation of rollback handles participating in existing transactions.
 * Delegates to {@code doRollback} and {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final Mono<Void> rollback(ReactiveTransaction transaction) throws TransactionException {
	if (transaction.isCompleted()) {
		return Mono.error(new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction"));
	}
	return TransactionSynchronizationManager.currentTransaction().flatMap(synchronizationManager -> {
		GenericReactiveTransaction reactiveTx = (GenericReactiveTransaction) transaction;
		return processRollback(synchronizationManager, reactiveTx);
	});
}
 
Example #26
Source File: AbstractPlatformTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus, false);
}
 
Example #27
Source File: WebSphereUowTransactionManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public <T> T execute(@Nullable TransactionDefinition definition, TransactionCallback<T> callback)
		throws TransactionException {

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

	if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
		throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
	}

	UOWManager uowManager = obtainUOWManager();
	int pb = def.getPropagationBehavior();
	boolean existingTx = (uowManager.getUOWStatus() != UOWSynchronizationRegistry.UOW_STATUS_NONE &&
			uowManager.getUOWType() != UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION);

	int uowType = UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION;
	boolean joinTx = false;
	boolean newSynch = false;

	if (existingTx) {
		if (pb == TransactionDefinition.PROPAGATION_NEVER) {
			throw new IllegalTransactionStateException(
					"Transaction propagation 'never' but existing transaction found");
		}
		if (pb == TransactionDefinition.PROPAGATION_NESTED) {
			throw new NestedTransactionNotSupportedException(
					"Transaction propagation 'nested' not supported for WebSphere UOW transactions");
		}
		if (pb == TransactionDefinition.PROPAGATION_SUPPORTS ||
				pb == TransactionDefinition.PROPAGATION_REQUIRED ||
				pb == TransactionDefinition.PROPAGATION_MANDATORY) {
			joinTx = true;
			newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
		}
		else if (pb == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
			uowType = UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION;
			newSynch = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
		}
		else {
			newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
		}
	}
	else {
		if (pb == TransactionDefinition.PROPAGATION_MANDATORY) {
			throw new IllegalTransactionStateException(
					"Transaction propagation 'mandatory' but no existing transaction found");
		}
		if (pb == TransactionDefinition.PROPAGATION_SUPPORTS ||
				pb == TransactionDefinition.PROPAGATION_NOT_SUPPORTED ||
				pb == TransactionDefinition.PROPAGATION_NEVER) {
			uowType = UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION;
			newSynch = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
		}
		else {
			newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
		}
	}

	boolean debug = logger.isDebugEnabled();
	if (debug) {
		logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
	}
	SuspendedResourcesHolder suspendedResources = (!joinTx ? suspend(null) : null);
	UOWActionAdapter<T> action = null;
	try {
		if (def.getTimeout() > TransactionDefinition.TIMEOUT_DEFAULT) {
			uowManager.setUOWTimeout(uowType, def.getTimeout());
		}
		if (debug) {
			logger.debug("Invoking WebSphere UOW action: type=" + uowType + ", join=" + joinTx);
		}
		action = new UOWActionAdapter<>(
				def, callback, (uowType == UOWManager.UOW_TYPE_GLOBAL_TRANSACTION), !joinTx, newSynch, debug);
		uowManager.runUnderUOW(uowType, joinTx, action);
		if (debug) {
			logger.debug("Returned from WebSphere UOW action: type=" + uowType + ", join=" + joinTx);
		}
		return action.getResult();
	}
	catch (UOWException | UOWActionException ex) {
		TransactionSystemException tse =
				new TransactionSystemException("UOWManager transaction processing failed", ex);
		Throwable appEx = action.getException();
		if (appEx != null) {
			logger.error("Application exception overridden by rollback exception", appEx);
			tse.initApplicationException(appEx);
		}
		throw tse;
	}
	finally {
		if (suspendedResources != null) {
			resume(null, suspendedResources);
		}
	}
}
 
Example #28
Source File: AbstractReactiveTransactionManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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.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));
		}
	});
}
 
Example #29
Source File: OptimisticLockingTest.java    From vladmihalcea.wordpress.com with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalTransactionStateException.class)
public void testRetryFailsOnTransaction() {
    itemService.saveItem();
}
 
Example #30
Source File: AbstractReactiveTransactionManager.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Set the given transaction rollback-only. Only called on rollback
 * if the current transaction participates in an existing one.
 * <p>The default implementation throws an IllegalTransactionStateException,
 * assuming that participating in existing transactions is generally not
 * supported. Subclasses are of course encouraged to provide such support.
 * @param synchronizationManager the synchronization manager bound to the current transaction
 * @param status the status representation of the transaction
 * @throws TransactionException in case of system errors
 */
protected Mono<Void> doSetRollbackOnly(TransactionSynchronizationManager synchronizationManager,
		GenericReactiveTransaction status) throws TransactionException {

	throw new IllegalTransactionStateException(
			"Participating in existing transactions is not supported - when 'isExistingTransaction' " +
			"returns true, appropriate 'doSetRollbackOnly' behavior must be provided");
}