org.springframework.transaction.NoTransactionException Java Examples

The following examples show how to use org.springframework.transaction.NoTransactionException. 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: TransactionContextManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Obtain the current {@link TransactionContext} from the subscriber context or the
 * transactional context holder. Context retrieval fails with NoTransactionException
 * if no context or context holder is registered.
 * @return the current {@link TransactionContext}
 * @throws NoTransactionException if no TransactionContext was found in the subscriber context
 * or no context found in a holder
 */
public static Mono<TransactionContext> currentContext() throws NoTransactionException {
	return Mono.subscriberContext().handle((ctx, sink) -> {
		if (ctx.hasKey(TransactionContext.class)) {
			sink.next(ctx.get(TransactionContext.class));
			return;
		}
		if (ctx.hasKey(TransactionContextHolder.class)) {
			TransactionContextHolder holder = ctx.get(TransactionContextHolder.class);
			if (holder.hasContext()) {
				sink.next(holder.currentContext());
				return;
			}
		}
		sink.error(new NoTransactionException("No transaction in context"));
	});
}
 
Example #2
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
	// do transaction checks
	if (requireTransactionContext) {
		TransactionInterceptor.currentTransactionStatus();
	}
	else {
		try {
			TransactionInterceptor.currentTransactionStatus();
			throw new RuntimeException("Shouldn't have a transaction");
		}
		catch (NoTransactionException ex) {
			// this is Ok
		}
	}
	super.before(method, args, target);
}
 
Example #3
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
	// do transaction checks
	if (requireTransactionContext) {
		TransactionInterceptor.currentTransactionStatus();
	}
	else {
		try {
			TransactionInterceptor.currentTransactionStatus();
			throw new RuntimeException("Shouldn't have a transaction");
		}
		catch (NoTransactionException ex) {
			// this is Ok
		}
	}
	super.before(method, args, target);
}
 
Example #4
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
	// do transaction checks
	if (requireTransactionContext) {
		TransactionInterceptor.currentTransactionStatus();
	}
	else {
		try {
			TransactionInterceptor.currentTransactionStatus();
			throw new RuntimeException("Shouldn't have a transaction");
		}
		catch (NoTransactionException ex) {
			// this is Ok
		}
	}
	super.before(method, args, target);
}
 
Example #5
Source File: SpringAwareUserTransactionTest.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkNoStatusOnThread()
{
    try
    {
        TransactionAspectSupport.currentTransactionStatus();
        fail("Spring transaction info is present outside of transaction boundaries");
    }
    catch (NoTransactionException e)
    {
        // expected
    }
}
 
Example #6
Source File: TransactionalBean.java    From redisson with Apache License 2.0 5 votes vote down vote up
public void testNoTransaction() {
    try {
        RTransaction transaction = transactionManager.getCurrentTransaction();
        Assert.fail();
    } catch (NoTransactionException e) {
        // skip
    }
}
 
Example #7
Source File: ReactiveTransactionalBean.java    From redisson with Apache License 2.0 5 votes vote down vote up
public Mono<Void> testNoTransaction() {
    Mono<RTransactionReactive> reactiveTransaction = transactionManager.getCurrentTransaction();
    return reactiveTransaction.onErrorResume(e -> {
        if (e instanceof NoTransactionException) {
            return Mono.empty();
        }
        return Mono.error(e);
    }).then();
}
 
Example #8
Source File: ReactiveRedissonTransactionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
public Mono<RTransactionReactive> getCurrentTransaction() {
    return TransactionSynchronizationManager.forCurrentTransaction().map(manager -> {
        ReactiveRedissonResourceHolder holder = (ReactiveRedissonResourceHolder) manager.getResource(redissonClient);
        if (holder == null) {
            throw new NoTransactionException("No transaction is available for the current thread");
        } else {
            return holder.getTransaction();
        }
    });
}
 
Example #9
Source File: RedissonTransactionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RTransaction getCurrentTransaction() {
    RedissonTransactionHolder to = (RedissonTransactionHolder) TransactionSynchronizationManager.getResource(redisson);
    if (to == null) {
        throw new NoTransactionException("No transaction is available for the current thread");
    }
    return to.getTransaction();
}
 
Example #10
Source File: AbstractTransactionAspectTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void checkTransactionStatus(boolean expected) {
	try {
		TransactionInterceptor.currentTransactionStatus();
		if (!expected) {
			fail("Should have thrown NoTransactionException");
		}
	}
	catch (NoTransactionException ex) {
		if (expected) {
			fail("Should have current TransactionStatus");
		}
	}
}
 
Example #11
Source File: TransactionAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return the transaction status of the current method invocation.
 * Mainly intended for code that wants to set the current transaction
 * rollback-only but not throw an application exception.
 * @throws NoTransactionException if the transaction info cannot be found,
 * because the method was invoked outside an AOP invocation context
 */
public static TransactionStatus currentTransactionStatus() throws NoTransactionException {
	TransactionInfo info = currentTransactionInfo();
	if (info == null || info.transactionStatus == null) {
		throw new NoTransactionException("No transaction aspect-managed TransactionStatus in scope");
	}
	return info.transactionStatus;
}
 
Example #12
Source File: TransactionAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the transaction status of the current method invocation.
 * Mainly intended for code that wants to set the current transaction
 * rollback-only but not throw an application exception.
 * @throws NoTransactionException if the transaction info cannot be found,
 * because the method was invoked outside an AOP invocation context
 */
public static TransactionStatus currentTransactionStatus() throws NoTransactionException {
	TransactionInfo info = currentTransactionInfo();
	if (info == null || info.transactionStatus == null) {
		throw new NoTransactionException("No transaction aspect-managed TransactionStatus in scope");
	}
	return info.transactionStatus;
}
 
Example #13
Source File: PlatformTransactionManagerAdapter.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public TransactionHolder getOrCreateTransaction(boolean start) {
    TransactionStatus status = null;
    try {
        //Spring managed transaction
        status = TransactionAspectSupport.currentTransactionStatus();
    } catch (NoTransactionException e) {
        //Teiid programatically managed transaction
        if (start) {
            status = platformTransactionManager.getTransaction(NEW_TRANSACTION_DEFINITION);
            TransactionHolder holder = new TransactionHolder(status, new PlatformTransactionAdapter(status));
            TRANSACTION_HOLDERS.set(holder);
            return holder;
        } else {
            try {
                status = platformTransactionManager.getTransaction(EXISTING_TRANSACTION_DEFINITION);
                //success means that there is one defined/associated, so we are safe to use
                //the thread local
                return TRANSACTION_HOLDERS.get();
            } catch (TransactionException e1) {
                TRANSACTION_HOLDERS.remove();
            }
        }
    }
    if (status == null) {
        return null;
    }
    synchronized (transactions) {
        PlatformTransactionAdapter adapter = transactions.get(status);
        if (adapter == null) {
            adapter = new PlatformTransactionAdapter(status);
            transactions.put(status, adapter);
        }
        return new TransactionHolder(status, adapter);
    }
}
 
Example #14
Source File: AbstractTransactionAspectTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected void checkTransactionStatus(boolean expected) {
	try {
		TransactionInterceptor.currentTransactionStatus();
		if (!expected) {
			fail("Should have thrown NoTransactionException");
		}
	}
	catch (NoTransactionException ex) {
		if (expected) {
			fail("Should have current TransactionStatus");
		}
	}
}
 
Example #15
Source File: TransactionAspectSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return the transaction status of the current method invocation.
 * Mainly intended for code that wants to set the current transaction
 * rollback-only but not throw an application exception.
 * @throws NoTransactionException if the transaction info cannot be found,
 * because the method was invoked outside an AOP invocation context
 */
public static TransactionStatus currentTransactionStatus() throws NoTransactionException {
	TransactionInfo info = currentTransactionInfo();
	if (info == null || info.transactionStatus == null) {
		throw new NoTransactionException("No transaction aspect-managed TransactionStatus in scope");
	}
	return info.transactionStatus;
}
 
Example #16
Source File: AbstractTransactionAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected void checkTransactionStatus(boolean expected) {
	try {
		TransactionInterceptor.currentTransactionStatus();
		if (!expected) {
			fail("Should have thrown NoTransactionException");
		}
	}
	catch (NoTransactionException ex) {
		if (expected) {
			fail("Should have current TransactionStatus");
		}
	}
}
 
Example #17
Source File: TransactionContextHolder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the current {@link TransactionContext}.
 * @throws NoTransactionException if no transaction is ongoing
 */
TransactionContext currentContext() {
	TransactionContext context = this.transactionStack.peek();
	if (context == null) {
		throw new NoTransactionException("No transaction in context");
	}
	return context;
}
 
Example #18
Source File: TransactionAspectSupport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the transaction status of the current method invocation.
 * Mainly intended for code that wants to set the current transaction
 * rollback-only but not throw an application exception.
 * @throws NoTransactionException if the transaction info cannot be found,
 * because the method was invoked outside an AOP invocation context
 */
public static TransactionStatus currentTransactionStatus() throws NoTransactionException {
	TransactionInfo info = currentTransactionInfo();
	if (info == null || info.transactionStatus == null) {
		throw new NoTransactionException("No transaction aspect-managed TransactionStatus in scope");
	}
	return info.transactionStatus;
}
 
Example #19
Source File: ReactiveNeo4jTransactionManager.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
public static Mono<RxTransaction> retrieveReactiveTransaction(final Driver driver, final String targetDatabase) {

		return TransactionSynchronizationManager.forCurrentTransaction() // Do we have a Transaction context?
			// Bail out early if synchronization between transaction managers is not active
			.filter(TransactionSynchronizationManager::isSynchronizationActive)
			.flatMap(tsm -> {
				// Get an existing holder
				ReactiveNeo4jTransactionHolder existingTxHolder = (ReactiveNeo4jTransactionHolder) tsm
					.getResource(driver);

				// And use it if there is any
				if (existingTxHolder != null) {
					return Mono.just(existingTxHolder);
				}

				// Otherwise open up a new native transaction
				return Mono.defer(() -> {
					RxSession session = driver.rxSession(defaultSessionConfig(targetDatabase));
					return Mono.from(session.beginTransaction(TransactionConfig.empty())).map(tx -> {

						ReactiveNeo4jTransactionHolder newConnectionHolder = new ReactiveNeo4jTransactionHolder(
							new Neo4jTransactionContext(targetDatabase), session, tx);
						newConnectionHolder.setSynchronizedWithTransaction(true);

						tsm.registerSynchronization(
							new ReactiveNeo4jSessionSynchronization(tsm, newConnectionHolder, driver));

						tsm.bindResource(driver, newConnectionHolder);
						return newConnectionHolder;
					});
				});
			})
			.map(connectionHolder -> {
					RxTransaction transaction = connectionHolder.getTransaction(targetDatabase);
					if (transaction == null) {
						throw new IllegalStateException(
							formatOngoingTxInAnotherDbErrorMessage(connectionHolder.getDatabaseName(), targetDatabase));
					}
					return transaction;
				}
			)
			// If not, than just don't open a transaction
			.onErrorResume(NoTransactionException.class, nte -> Mono.empty());
	}
 
Example #20
Source File: SpringAwareUserTransaction.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the current transaction info, or null if none exists.
 * <p>
 * A check is done to ensure that the transaction info on the stack is exactly
 * the same instance used when this transaction was started.
 * The internal status is also checked against the transaction info.
 * These checks ensure that the transaction demarcation is done correctly and that
 * thread safety is adhered to.
 * 
 * @return Returns the current transaction
 */
private TransactionInfo getTransactionInfo()
{
    // a few quick self-checks
    if (threadId < 0 && internalStatus != Status.STATUS_NO_TRANSACTION)
    {
        throw new RuntimeException("Transaction has been started but there is no thread ID");
    }
    else if (threadId >= 0 && internalStatus == Status.STATUS_NO_TRANSACTION)
    {
        throw new RuntimeException("Transaction has not been started but a thread ID has been recorded");
    }
    
    TransactionInfo txnInfo = null;
    try
    {
        txnInfo = TransactionAspectSupport.currentTransactionInfo();
        // we are in a transaction
    }
    catch (NoTransactionException e)
    {
        // No transaction.  It is possible that the transaction threw an exception during commit.
    }
    // perform checks for active transactions
    if (internalStatus == Status.STATUS_ACTIVE)
    {
        if (Thread.currentThread().getId() != threadId)
        {
            // the internally stored transaction info (retrieved in begin()) should match the info
            // on the thread
            throw new RuntimeException("UserTransaction may not be accessed by multiple threads");
        }
        else if (txnInfo == null)
        {
            // internally we recorded a transaction starting, but there is nothing on the thread
            throw new RuntimeException("Transaction boundaries have been made to overlap in the stack");
        }
        else if (txnInfo != internalTxnInfo)
        {
            // the transaction info on the stack isn't the one we started with
            throw new RuntimeException("UserTransaction begin/commit mismatch");
        }
    }
    return txnInfo;
}
 
Example #21
Source File: TransactionAspectSupport.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Subclasses can use this to return the current TransactionInfo.
 * Only subclasses that cannot handle all operations in one method,
 * such as an AspectJ aspect involving distinct before and after advice,
 * need to use this mechanism to get at the current TransactionInfo.
 * An around advice such as an AOP Alliance MethodInterceptor can hold a
 * reference to the TransactionInfo throughout the aspect method.
 * <p>A TransactionInfo will be returned even if no transaction was created.
 * The {@code TransactionInfo.hasTransaction()} method can be used to query this.
 * <p>To find out about specific transaction characteristics, consider using
 * TransactionSynchronizationManager's {@code isSynchronizationActive()}
 * and/or {@code isActualTransactionActive()} methods.
 * @return TransactionInfo bound to this thread, or {@code null} if none
 * @see TransactionInfo#hasTransaction()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
 */
protected static TransactionInfo currentTransactionInfo() throws NoTransactionException {
	return transactionInfoHolder.get();
}
 
Example #22
Source File: TransactionAspectSupport.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Subclasses can use this to return the current TransactionInfo.
 * Only subclasses that cannot handle all operations in one method,
 * such as an AspectJ aspect involving distinct before and after advice,
 * need to use this mechanism to get at the current TransactionInfo.
 * An around advice such as an AOP Alliance MethodInterceptor can hold a
 * reference to the TransactionInfo throughout the aspect method.
 * <p>A TransactionInfo will be returned even if no transaction was created.
 * The {@code TransactionInfo.hasTransaction()} method can be used to query this.
 * <p>To find out about specific transaction characteristics, consider using
 * TransactionSynchronizationManager's {@code isSynchronizationActive()}
 * and/or {@code isActualTransactionActive()} methods.
 * @return TransactionInfo bound to this thread, or {@code null} if none
 * @see TransactionInfo#hasTransaction()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
 */
protected static TransactionInfo currentTransactionInfo() throws NoTransactionException {
	return transactionInfoHolder.get();
}
 
Example #23
Source File: TransactionAspectSupport.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Subclasses can use this to return the current TransactionInfo.
 * Only subclasses that cannot handle all operations in one method,
 * such as an AspectJ aspect involving distinct before and after advice,
 * need to use this mechanism to get at the current TransactionInfo.
 * An around advice such as an AOP Alliance MethodInterceptor can hold a
 * reference to the TransactionInfo throughout the aspect method.
 * <p>A TransactionInfo will be returned even if no transaction was created.
 * The {@code TransactionInfo.hasTransaction()} method can be used to query this.
 * <p>To find out about specific transaction characteristics, consider using
 * TransactionSynchronizationManager's {@code isSynchronizationActive()}
 * and/or {@code isActualTransactionActive()} methods.
 * @return the TransactionInfo bound to this thread, or {@code null} if none
 * @see TransactionInfo#hasTransaction()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
 */
@Nullable
protected static TransactionInfo currentTransactionInfo() throws NoTransactionException {
	return transactionInfoHolder.get();
}
 
Example #24
Source File: TransactionAspectSupport.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Subclasses can use this to return the current TransactionInfo.
 * Only subclasses that cannot handle all operations in one method,
 * such as an AspectJ aspect involving distinct before and after advice,
 * need to use this mechanism to get at the current TransactionInfo.
 * An around advice such as an AOP Alliance MethodInterceptor can hold a
 * reference to the TransactionInfo throughout the aspect method.
 * <p>A TransactionInfo will be returned even if no transaction was created.
 * The {@code TransactionInfo.hasTransaction()} method can be used to query this.
 * <p>To find out about specific transaction characteristics, consider using
 * TransactionSynchronizationManager's {@code isSynchronizationActive()}
 * and/or {@code isActualTransactionActive()} methods.
 * @return the TransactionInfo bound to this thread, or {@code null} if none
 * @see TransactionInfo#hasTransaction()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive()
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
 */
@Nullable
protected static TransactionInfo currentTransactionInfo() throws NoTransactionException {
	return transactionInfoHolder.get();
}