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

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

Introduction

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

Prototype

public static boolean isSynchronizationActive() 

Source Link

Document

Return if transaction synchronization is active for the current thread.

Usage

From source file:org.alfresco.util.transaction.TransactionSupportUtil.java

/**
 * Binds the Alfresco-specific to the transaction resources
 * //www . jav  a 2s.  co m
 * @return Returns the current or new synchronization implementation
 */
private static TransactionSynchronizationImpl registerSynchronizations() {
    /*
     * No thread synchronization or locking required as the resources are all threadlocal
     */
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        Thread currentThread = Thread.currentThread();
        throw new AlfrescoRuntimeException(
                "Transaction must be active and synchronization is required: " + currentThread);
    }
    TransactionSynchronizationImpl txnSynch = (TransactionSynchronizationImpl) TransactionSynchronizationManager
            .getResource(RESOURCE_KEY_TXN_SYNCH);
    if (txnSynch != null) {
        // synchronization already registered
        return txnSynch;
    }
    // we need a unique ID for the transaction
    String txnId = GUID.generate();
    // register the synchronization
    txnSynch = new TransactionSynchronizationImpl(txnId);
    TransactionSynchronizationManager.registerSynchronization(txnSynch);
    // register the resource that will ensure we don't duplication the synchronization
    TransactionSynchronizationManager.bindResource(RESOURCE_KEY_TXN_SYNCH, txnSynch);
    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Bound txn synch: " + txnSynch);
    }
    return txnSynch;
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java

@Test
public void testWrongIsolationLevel() {
    final ODB odb = Mockito.mock(ODB.class);
    Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException());
    PlatformTransactionManager tm = new NeoDatisTransactionManager(odb);
    TransactionTemplate tmpl = new TransactionTemplate(tm);

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    tmpl.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {/*from  www. j  a va 2 s.  co  m*/
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
                NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
                neoDatisTemplate.store(null);
                transactionStatus.setRollbackOnly();
            }
        });
        Assert.fail("Should throw an exception.");
    } catch (InvalidIsolationLevelException e) {
        // is ok
    }

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

}

From source file:org.hengdao.utils.SqlSessionUtils.java

/**
 * If a Spring transaction is active it uses {@code DataSourceUtils} to get
 * a Spring managed {@code Connection}, then creates a new
 * {@code SqlSession} with this connection and synchronizes it with the
 * transaction. If there is not an active transaction it gets a connection
 * directly from the {@code DataSource} and creates a {@code SqlSession}
 * with it.//w w w  .j  a v a 2 s  .c om
 *
 * @param sessionFactory
 *            a MyBatis {@code SqlSessionFactory} to create new sessions
 * @param executorType
 *            The executor type of the SqlSession to create
 * @param exceptionTranslator
 *            Optional. Translates SqlSession.commit() exceptions to Spring
 *            exceptions.
 * @throws TransientDataAccessResourceException
 *             if a transaction is active and the {@code SqlSessionFactory}
 *             is not using a {@code SpringManagedTransactionFactory}
 * @see SpringManagedTransactionFactory
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    Assert.notNull(sessionFactory, "No SqlSessionFactory specified");
    Assert.notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource();

    // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but
    // we keep this check for the case that SqlSessionUtils is called from
    // custom code
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    Connection conn;
    try {
        conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource);
    } catch (SQLException e) {
        throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]");
    }

    // Assume either DataSourceTransactionManager or the underlying
    // connection pool already dealt with enabling auto commit.
    // This may not be a good assumption, but the overhead of checking
    // connection.getAutoCommit() again may be expensive (?) in some drivers
    // (see DataSourceTransactionManager.doBegin()). One option would be to
    // only check for auto commit if this function is being called outside
    // of DSTxMgr, but to do that we would need to be able to call
    // ConnectionHolder.isTransactionActive(), which is protected and not
    // visible to this class.
    SqlSession session = sessionFactory.openSession(executorType, conn);

    // Register session holder and bind it to enable synchronization.
    //
    // Note: The DataSource should be synchronized with the transaction
    // either through DataSourceTxMgr or another tx synchronization.
    // Further assume that if an exception is thrown, whatever started the
    // transaction will
    // handle closing / rolling back the Connection associated with the
    // SqlSession.
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!(sessionFactory.getConfiguration().getEnvironment()
                .getTransactionFactory() instanceof SpringManagedTransactionFactory)
                && DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new TransientDataAccessResourceException(
                    "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
        }
        holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
        TransactionSynchronizationManager.bindResource(sessionFactory, holder);
        TransactionSynchronizationManager
                .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
        holder.setSynchronizedWithTransaction(true);
        holder.requested();
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }

    return session;
}

From source file:org.openvpms.component.business.service.archetype.Notifier.java

/**
 * Returns the notifier for the given service and current thread.
 * <p/>/*from  w  ww. ja v  a  2 s .  co  m*/
 * If one does not exist, it will be created.
 *
 * @param service the archetype service
 * @return the context
 */
public static Notifier getNotifier(ArchetypeService service) {
    Notifier notifier;
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!TransactionSynchronizationManager.hasResource(service)) {
            notifier = new Notifier(service, true);
            TransactionSynchronizationManager.bindResource(service, notifier);
            TransactionSynchronizationManager.registerSynchronization(new NotifierSynchronization(notifier));
        } else {
            notifier = (Notifier) TransactionSynchronizationManager.getResource(service);
        }
    } else {
        notifier = new Notifier(service, false);
    }
    return notifier;
}

From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java

@Test
public void testInvalidIsolation() throws Exception {
    final ExtObjectContainer container = mock(ExtObjectContainer.class);

    PlatformTransactionManager tm = new Db4oTransactionManager(container);
    TransactionTemplate tt = new TransactionTemplate(tm);

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {/*from w ww  .  j  av a2 s.c o  m*/
        tt.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(container),
                        "Has thread session");
                Db4oTemplate template = new Db4oTemplate(container);
                template.execute(new Db4oCallback() {
                    public Object doInDb4o(ObjectContainer cont) {
                        return null;
                    }
                });
            }
        });
        Assert.fail("Should have thrown InvalidIsolationLevelException");
    } catch (InvalidIsolationLevelException e) {
        // it's okay
    }

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    // TODO verify(container)....; exception thrown?
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.TransactionAwareContentSourceProxy.java

/**
 * Determine whether to obtain a fixed target Session for the proxy
 * or to reobtain the target Session for each operation.
 * <p>The default implementation returns {@code true} for all
 * standard cases. This can be overridden through the
 * {@link #setReobtainTransactionalSessions "reobtainTransactionalSessions"}
 * flag, which enforces a non-fixed target Session within an active transaction.
 * Note that non-transactional access will always use a fixed Session.
 *
 * @param targetContentSource the target ContentSource
 * @return whether to obtain a fixed target Session for the proxy
 *//*from w ww  .  j a v  a2 s  .c om*/
protected boolean shouldObtainFixedSession(ContentSource targetContentSource) {
    return (!TransactionSynchronizationManager.isSynchronizationActive()
            || !this.reobtainTransactionalSessions);
}

From source file:org.guzz.web.context.spring.TransactionManagerUtils.java

/**
 * Get a Guzz WriteTranSession for the given TransactionManager. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link GuzzTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is <code>true</code>.
 * <p>Same as {@link #getSession}, but throwing the original GuzzException.
 * @param transactionManager Guzz TransactionManager to create the session with
 * @param entityInterceptor Guzz entity interceptor, or <code>null</code> if none
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be <code>null</code>)
 * @param allowCreate whether a non-transactional Session should be created
 * when no transactional Session can be found for the current thread
 * @return the Guzz WriteTranSession/* w  ww  . j  av  a2  s. com*/
 * @throws GuzzException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 */
private static WriteTranSession doGetSession(TransactionManager transactionManager)
        throws GuzzException, IllegalStateException {
    Assert.notNull(transactionManager, "No TransactionManager specified");
    WriteTranSession session = null;

    WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager
            .getResource(transactionManager);
    if (writeTranSessionHolder != null) {
        // pre-bound Guzz WriteTranSession
        session = writeTranSessionHolder.getWriteTranSession();
    } else {
        //????spring?????bug
        logger.debug("Opening Guzz WriteTranSession");
        session = transactionManager.openRWTran(false);

        // Use same Session for further Guzz actions within the transaction.
        // Thread object will get removed by synchronization at transaction completion.
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
            logger.debug("Registering Spring transaction synchronization for new Guzz WriteTranSession");
            writeTranSessionHolder = new WriteTranSessionHolder(session);

            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(writeTranSessionHolder, transactionManager, true));

            TransactionSynchronizationManager.bindResource(transactionManager, writeTranSessionHolder);
            writeTranSessionHolder.setSynchronizedWithTransaction(true);
        }

        // Check whether we are allowed to return the Session.
        if (!isSessionTransactional(session, transactionManager)) {
            closeSession(session);
            throw new IllegalStateException("No Guzz WriteTranSession bound to thread here");
        }
    }

    if (writeTranSessionHolder.hasTimeout()) {
        session.setQueryTimeoutInSeconds(writeTranSessionHolder.getTimeToLiveInSeconds());
    }

    return session;
}

From source file:com.wavemaker.runtime.data.spring.SpringDataServiceManager.java

@Override
public void commit() {

    if (txLogger.isInfoEnabled()) {
        txLogger.info("commit");
    }/*from w w  w.  ja v a  2  s.co m*/

    ThreadContext.Context ctx = ThreadContext.getContext(this.metaData.getName());

    if (ctx == null) {
        if (txLogger.isWarnEnabled()) {
            txLogger.warn("ignoring commit - no tx in progress");
            if (txLogger.isDebugEnabled()) {
                logStackTrace();
            }
        }
        return;
    }

    TransactionStatus txStatus = ctx.getTransactionStatus();

    try {
        if (txStatus == null) {
            if (txLogger.isWarnEnabled()) {
                txLogger.warn("ignoring commit - no tx status");
                if (txLogger.isDebugEnabled()) {
                    logStackTrace();
                }
            }
        } else {
            this.txMgr.commit(txStatus);
        }
    } finally {
        ctx.setTransactionStatus(null);
        ThreadContext.unsetContext(this.metaData.getName());
        HashMap<String, ThreadContext.Context> contextHash = ThreadContext.getThreadLocalHash();

        if (contextHash != null && contextHash.size() > 0) {
            if (!TransactionSynchronizationManager.isSynchronizationActive()) {
                TransactionSynchronizationManager.initSynchronization();
            }
        } else {
            if (TransactionSynchronizationManager.isSynchronizationActive()) {
                TransactionSynchronizationManager.clear();
                Map map = TransactionSynchronizationManager.getResourceMap();
                for (Object entry : map.keySet()) {
                    TransactionSynchronizationManager.unbindResource(entry);
                }
            }
        }
    }
}

From source file:org.cfr.capsicum.datasource.TransactionAwareDataSourceProxy.java

/**
 * Determine whether to obtain a fixed target Connection for the proxy
 * or to reobtain the target Connection for each operation.
 * <p>The default implementation returns <code>true</code> for all
 * standard cases. This can be overridden through the
 * {@link #setReobtainTransactionalConnections "reobtainTransactionalConnections"}
 * flag, which enforces a non-fixed target Connection within an active transaction.
 * Note that non-transactional access will always use a fixed Connection.
 * @param targetDataSource the target DataSource
 *//*from  w  ww  .  j av  a2s  . c o  m*/
protected boolean shouldObtainFixedConnection(DataSource targetDataSource) {
    return !TransactionSynchronizationManager.isSynchronizationActive()
            || !this.reobtainTransactionalConnections;
}