Example usage for org.springframework.transaction.support TransactionSynchronizationManager isActualTransactionActive

List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager isActualTransactionActive

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionSynchronizationManager isActualTransactionActive.

Prototype

public static boolean isActualTransactionActive() 

Source Link

Document

Return whether there currently is an actual transaction active.

Usage

From source file:org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate.java

private TransactionContext getTransactionContext() {
    return TransactionSynchronizationManager.isActualTransactionActive()
            ? ((SpannerTransactionManager.Tx) ((DefaultTransactionStatus) TransactionAspectSupport
                    .currentTransactionStatus()).getTransaction()).getTransactionContext()
            : null;/*  w  ww  .j  a va  2s.  c  om*/
}

From source file:org.springframework.data.jdbc.retry.oracle.RacRetryOperationsInterceptor.java

public Object invoke(MethodInvocation methodInvocation) throws Throwable {

    Object result;//  ww  w.j  a  va  2 s  .c o m

    if (activeRacRetry.get() == null) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            throw new JdbcRetryException(
                    "An active transaction was found.  This is not allowed when starting a retryable operation.");
        }
        startRacRetryInterception(methodInvocation);
        result = super.invoke(methodInvocation);
        clearRacRetryInterception();
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Participating in existing RAC Retry Interceptor");
        }
        result = methodInvocation.proceed();
    }

    return result;
}

From source file:org.springframework.data.redis.core.RedisConnectionUtils.java

private static boolean isActualNonReadonlyTransactionActive() {
    return TransactionSynchronizationManager.isActualTransactionActive()
            && !TransactionSynchronizationManager.isCurrentTransactionReadOnly();
}

From source file:org.springframework.integration.sqs.SQSInboundGateway.java

/**
 * {@inheritDoc}/*from  ww  w  .j  ava  2 s  .  co  m*/
 */
public Message<Object> receive() {
    if (transaction && (!TransactionSynchronizationManager.isActualTransactionActive()
            || TransactionSynchronizationManager.isCurrentTransactionReadOnly())) {
        throw new IllegalStateException("An active non read only transaction is required!");
    }
    String queueName = getQueueName();
    final com.amazonaws.queue.doc._2009_02_01.Message message = template.receive(queueName);
    log.debug("Pulled message: " + message);
    if (message == null) {
        return null;
    }
    Message<Object> result = handleReceivedMessage(message);
    postReceive(queueName, message);
    return result;
}

From source file:org.springframework.orm.jpa.EntityManagerFactoryUtils.java

/**
 * Obtain a JPA EntityManager from the given factory. Is aware of a corresponding
 * EntityManager bound to the current thread, e.g. when using JpaTransactionManager.
 * <p>Same as {@code getEntityManager}, but throwing the original PersistenceException.
 * @param emf EntityManagerFactory to create the EntityManager with
 * @param properties the properties to be passed into the {@code createEntityManager}
 * call (may be {@code null})//w  ww. ja  va2s.  c  o  m
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager, or {@code null} if none found
 * @throws javax.persistence.PersistenceException if the EntityManager couldn't be created
 * @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory)
 * @see JpaTransactionManager
 */
@Nullable
public static EntityManager doGetTransactionalEntityManager(EntityManagerFactory emf,
        @Nullable Map<?, ?> properties, boolean synchronizedWithTransaction) throws PersistenceException {

    Assert.notNull(emf, "No EntityManagerFactory specified");

    EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(emf);
    if (emHolder != null) {
        if (synchronizedWithTransaction) {
            if (!emHolder.isSynchronizedWithTransaction()) {
                if (TransactionSynchronizationManager.isActualTransactionActive()) {
                    // Try to explicitly synchronize the EntityManager itself
                    // with an ongoing JTA transaction, if any.
                    try {
                        emHolder.getEntityManager().joinTransaction();
                    } catch (TransactionRequiredException ex) {
                        logger.debug("Could not join transaction because none was actually active", ex);
                    }
                }
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    Object transactionData = prepareTransaction(emHolder.getEntityManager(), emf);
                    TransactionSynchronizationManager
                            .registerSynchronization(new TransactionalEntityManagerSynchronization(emHolder,
                                    emf, transactionData, false));
                    emHolder.setSynchronizedWithTransaction(true);
                }
            }
            // Use holder's reference count to track synchronizedWithTransaction access.
            // isOpen() check used below to find out about it.
            emHolder.requested();
            return emHolder.getEntityManager();
        } else {
            // unsynchronized EntityManager demanded
            if (emHolder.isTransactionActive() && !emHolder.isOpen()) {
                if (!TransactionSynchronizationManager.isSynchronizationActive()) {
                    return null;
                }
                // EntityManagerHolder with an active transaction coming from JpaTransactionManager,
                // with no synchronized EntityManager having been requested by application code before.
                // Unbind in order to register a new unsynchronized EntityManager instead.
                TransactionSynchronizationManager.unbindResource(emf);
            } else {
                // Either a previously bound unsynchronized EntityManager, or the application
                // has requested a synchronized EntityManager before and therefore upgraded
                // this transaction's EntityManager to synchronized before.
                return emHolder.getEntityManager();
            }
        }
    } else if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        // Indicate that we can't obtain a transactional EntityManager.
        return null;
    }

    // Create a new EntityManager for use within the current transaction.
    logger.debug("Opening JPA EntityManager");
    EntityManager em = null;
    if (!synchronizedWithTransaction) {
        try {
            em = emf.createEntityManager(SynchronizationType.UNSYNCHRONIZED, properties);
        } catch (AbstractMethodError err) {
            // JPA 2.1 API available but method not actually implemented in persistence provider:
            // falling back to regular createEntityManager method.
        }
    }
    if (em == null) {
        em = (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties)
                : emf.createEntityManager());
    }

    // Use same EntityManager for further JPA operations within the transaction.
    // Thread-bound object will get removed by synchronization at transaction completion.
    logger.debug("Registering transaction synchronization for JPA EntityManager");
    emHolder = new EntityManagerHolder(em);
    if (synchronizedWithTransaction) {
        Object transactionData = prepareTransaction(em, emf);
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionalEntityManagerSynchronization(emHolder, emf, transactionData, true));
        emHolder.setSynchronizedWithTransaction(true);
    } else {
        // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec...
        TransactionSynchronizationManager
                .registerSynchronization(new TransactionScopedEntityManagerSynchronization(emHolder, emf));
    }
    TransactionSynchronizationManager.bindResource(emf, emHolder);

    return em;
}

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

/**
 * Suspend the given transaction. Suspends transaction synchronization first,
 * then delegates to the {@code doSuspend} template method.
 * @param transaction the current transaction object
 * (or {@code null} to just suspend active synchronizations, if any)
 * @return an object that holds suspended resources
 * (or {@code null} if neither transaction nor synchronization active)
 * @see #doSuspend//from w ww  .j  a  v  a 2  s  . c  o  m
 * @see #resume
 */
@Nullable
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
        try {
            Object suspendedResources = null;
            if (transaction != null) {
                suspendedResources = doSuspend(transaction);
            }
            String name = TransactionSynchronizationManager.getCurrentTransactionName();
            TransactionSynchronizationManager.setCurrentTransactionName(null);
            boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
            TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
            Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
            TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
            boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
            TransactionSynchronizationManager.setActualTransactionActive(false);
            return new SuspendedResourcesHolder(suspendedResources, suspendedSynchronizations, name, readOnly,
                    isolationLevel, wasActive);
        } catch (RuntimeException | Error ex) {
            // doSuspend failed - original transaction is still active...
            doResumeSynchronization(suspendedSynchronizations);
            throw ex;
        }
    } else if (transaction != null) {
        // Transaction active but no synchronization active.
        Object suspendedResources = doSuspend(transaction);
        return new SuspendedResourcesHolder(suspendedResources);
    } else {
        // Neither transaction nor synchronization active.
        return null;
    }
}