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.sakaiproject.chat2.model.impl.ChatManagerImpl.java

/**
 * {@inheritDoc}//from   w ww .  j  av  a2 s  . c o m
 */
public void sendDeleteChannel(ChatChannel channel) {
    ChatChannelDeleteTxSync txSync = new ChatChannelDeleteTxSync(channel);

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(txSync);
    } else {
        txSync.afterCompletion(ChatChannelDeleteTxSync.STATUS_COMMITTED);
    }
}

From source file:org.sakaiproject.chat2.model.impl.ChatManagerImpl.java

/**
 * {@inheritDoc}// w ww . ja v  a 2s .co  m
 */
public void sendDeleteChannelMessages(ChatChannel channel) {
    ChatChannelMessagesDeleteTxSync txSync = new ChatChannelMessagesDeleteTxSync(channel);

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(txSync);
    } else {
        txSync.afterCompletion(ChatChannelMessagesDeleteTxSync.STATUS_COMMITTED);
    }
}

From source file:org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.java

public static void bindResourceToTransaction(RabbitResourceHolder resourceHolder,
        ConnectionFactory connectionFactory, boolean synched) {
    if (TransactionSynchronizationManager.hasResource(connectionFactory)
            || !TransactionSynchronizationManager.isActualTransactionActive() || !synched) {
        return;//from  w w w.j  av  a  2  s  .  c o  m
    }
    TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolder);
    resourceHolder.setSynchronizedWithTransaction(true);
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(
                new RabbitResourceSynchronization(resourceHolder, connectionFactory, synched));
    }
}

From source file:org.springframework.data.document.mongodb.MongoDbUtils.java

public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password,
        boolean allowCreate) {
    Assert.notNull(mongo, "No Mongo instance specified");

    DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo);
    if (dbHolder != null && !dbHolder.isEmpty()) {
        // pre-bound Mongo DB
        DB db = null;/*  w  w w. jav a  2 s  .  c o m*/
        if (TransactionSynchronizationManager.isSynchronizationActive() && dbHolder.doesNotHoldNonDefaultDB()) {
            // Spring transaction management is active ->
            db = dbHolder.getDB();
            if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
                LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB");
                TransactionSynchronizationManager
                        .registerSynchronization(new MongoSynchronization(dbHolder, mongo));
                dbHolder.setSynchronizedWithTransaction(true);
            }
        }
        if (db != null) {
            return db;
        }
    }

    LOGGER.trace("Getting Mongo Database name=[" + databaseName + "]");
    DB db = mongo.getDB(databaseName);

    boolean credentialsGiven = username != null && password != null;
    if (credentialsGiven && !db.isAuthenticated()) {
        //Note, can only authenticate once against the same com.mongodb.DB object.
        if (!db.authenticate(username, password)) {
            throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName
                    + "], username = [" + username + "], password = [" + new String(password) + "]",
                    databaseName, username, password);
        }
    }

    // Use same Session for further Mongo 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 Hibernate Session");
        DbHolder holderToUse = dbHolder;
        if (holderToUse == null) {
            holderToUse = new DbHolder(db);
        } else {
            holderToUse.addDB(db);
        }
        TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != dbHolder) {
            TransactionSynchronizationManager.bindResource(mongo, holderToUse);
        }
    }

    // Check whether we are allowed to return the DB.
    if (!allowCreate && !isDBTransactional(db, mongo)) {
        throw new IllegalStateException("No Mongo DB bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    return db;
}

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

/**
 * Gets a Redis connection. Is aware of and will return any existing corresponding connections bound to the current thread, 
 * for example when using a transaction manager. Will create a new Connection otherwise, if {@code allowCreate} is <tt>true</tt>.
 * /*w w  w. ja va 2  s.  com*/
 * @param factory connection factory for creating the connection
 * @param allowCreate whether a new (unbound) connection should be created when no connection can be found for the current thread
 * @param bind binds the connection to the thread, in case one was created
 * @return an active Redis connection
 */
public static RedisConnection doGetConnection(RedisConnectionFactory factory, boolean allowCreate,
        boolean bind) {
    Assert.notNull(factory, "No RedisConnectionFactory specified");

    RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager
            .getResource(factory);
    //TODO: investigate tx synchronization

    if (connHolder != null)
        return connHolder.getConnection();

    if (!allowCreate) {
        throw new IllegalArgumentException("No connection found and allowCreate = false");
    }

    if (log.isDebugEnabled())
        log.debug("Opening RedisConnection");

    RedisConnection conn = factory.getConnection();

    boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();

    if (bind || synchronizationActive) {
        connHolder = new RedisConnectionHolder(conn);
        if (synchronizationActive) {
            TransactionSynchronizationManager
                    .registerSynchronization(new RedisConnectionSynchronization(connHolder, factory, true));
        }
        TransactionSynchronizationManager.bindResource(factory, connHolder);
        return connHolder.getConnection();
    }
    return conn;
}

From source file:org.springframework.data.mongodb.core.MongoDbUtils.java

public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password,
        boolean allowCreate) {
    Assert.notNull(mongo, "No Mongo instance specified");

    DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo);
    if (dbHolder != null && !dbHolder.isEmpty()) {
        // pre-bound Mongo DB
        DB db = null;//from w w w  . ja v  a 2  s.  c o  m
        if (TransactionSynchronizationManager.isSynchronizationActive() && dbHolder.doesNotHoldNonDefaultDB()) {
            // Spring transaction management is active ->
            db = dbHolder.getDB(databaseName);
            if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
                LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB");
                TransactionSynchronizationManager
                        .registerSynchronization(new MongoSynchronization(dbHolder, mongo));
                dbHolder.setSynchronizedWithTransaction(true);
            }
        }
        if (db != null) {
            return db;
        }
    }

    LOGGER.trace("Getting Mongo Database name=[" + databaseName + "]");
    DB db = mongo.getDB(databaseName);

    boolean credentialsGiven = username != null && password != null;
    if (credentialsGiven && !db.isAuthenticated()) {
        // Note, can only authenticate once against the same com.mongodb.DB object.
        synchronized (db) {
            if (!db.authenticate(username, password)) {
                throw new CannotGetMongoDbConnectionException(
                        "Failed to authenticate to database [" + databaseName + "], username = [" + username
                                + "], password = [" + new String(password) + "]",
                        databaseName, username, password);
            }
        }
    }

    // Use same Session for further Mongo 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 Hibernate Session");
        DbHolder holderToUse = dbHolder;
        if (holderToUse == null) {
            holderToUse = new DbHolder(databaseName, db);
        } else {
            holderToUse.addDB(databaseName, db);
        }
        TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != dbHolder) {
            TransactionSynchronizationManager.bindResource(mongo, holderToUse);
        }
    }

    // Check whether we are allowed to return the DB.
    if (!allowCreate && !isDBTransactional(db, mongo)) {
        throw new IllegalStateException("No Mongo DB bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    return db;
}

From source file:org.springframework.data.neo4j.transaction.SessionFactoryUtils.java

public static Session getSession(SessionFactory sessionFactory) throws IllegalStateException {

    Assert.notNull(sessionFactory, "No SessionFactory specified");

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null) {
        if (!sessionHolder.isSynchronizedWithTransaction()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            sessionHolder.setSynchronizedWithTransaction(true);
            TransactionSynchronizationManager
                    .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, false));
        }//from w  ww.  j  a v a  2s  .  c  o  m
        return sessionHolder.getSession();
    }

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        return null;
    }

    Session session = sessionFactory.openSession();

    if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
        System.out.println("hitting read only txn.");
    }

    logger.debug("Registering transaction synchronization for Neo4j Session");
    // Use same Session for further Neo4j actions within the transaction.
    // Thread object will get removed by synchronization at transaction completion.

    sessionHolder = new SessionHolder(session);
    sessionHolder.setSynchronizedWithTransaction(true);
    TransactionSynchronizationManager
            .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, true));
    TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);

    return session;
}

From source file:org.springframework.datastore.mapping.core.DatastoreUtils.java

/**
 * Get a Datastore Session for the given Datastore. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link org.springframework.datastore.mapping.transactions.DatastoreTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is <code>true</code>.
 *
 * @param datastore Datastore to create the session with
 * 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 Datastore Session/*from   w  w  w .  j a  v a 2s  . c o  m*/
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 */
private static Session doGetSession(Datastore datastore, boolean allowCreate) {

    Assert.notNull(datastore, "No Datastore specified");

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(datastore);

    if (sessionHolder != null && !sessionHolder.isEmpty()) {
        // pre-bound Datastore Session
        Session session;
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && sessionHolder.doesNotHoldNonDefaultSession()) {
            // Spring transaction management is active ->
            // register pre-bound Session with it for transactional flushing.
            session = sessionHolder.getSession();
            if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
                logger.debug("Registering Spring transaction synchronization for existing Datastore Session");
                TransactionSynchronizationManager.registerSynchronization(
                        new SpringSessionSynchronization(sessionHolder, datastore, false));
                sessionHolder.setSynchronizedWithTransaction(true);

            }
            if (session != null) {
                return session;
            }
        }
    }

    logger.debug("Opening Datastore Session");
    Session session = datastore.connect();

    // Use same Session for further Datastore 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 Datastore Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {
            holderToUse.addSession(session);
        }
        TransactionSynchronizationManager
                .registerSynchronization(new SpringSessionSynchronization(holderToUse, datastore, true));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(datastore, holderToUse);
        }
    }

    // Check whether we are allowed to return the Session.
    if (!allowCreate && !isSessionTransactional(session, datastore)) {
        closeSession(session);
        throw new IllegalStateException("No Datastore Session bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    return session;
}

From source file:org.springframework.jca.cci.connection.ConnectionFactoryUtils.java

/**
 * Actually obtain a CCI Connection from the given ConnectionFactory.
 * Same as {@link #getConnection}, but throwing the original ResourceException.
 * <p>Is aware of a corresponding Connection bound to the current thread, for example
 * when using {@link CciLocalTransactionManager}. Will bind a Connection to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareConnectionFactoryProxy}.
 * @param cf the ConnectionFactory to obtain Connection from
 * @return a CCI Connection from the given ConnectionFactory
 * @throws ResourceException if thrown by CCI API methods
 * @see #doReleaseConnection//w ww. j a  va2s . c  om
 */
public static Connection doGetConnection(ConnectionFactory cf) throws ResourceException {
    Assert.notNull(cf, "No ConnectionFactory specified");

    ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(cf);
    if (conHolder != null) {
        return conHolder.getConnection();
    }

    logger.debug("Opening CCI Connection");
    Connection con = cf.getConnection();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for CCI Connection");
        conHolder = new ConnectionHolder(con);
        conHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(conHolder, cf));
        TransactionSynchronizationManager.bindResource(cf, conHolder);
    }

    return con;
}

From source file:org.springframework.jdbc.datasource.DataSourceUtils.java

/**
 * Actually obtain a JDBC Connection from the given DataSource.
 * Same as {@link #getConnection}, but throwing the original SQLException.
 * <p>Is aware of a corresponding Connection bound to the current thread, for example
 * when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param dataSource the DataSource to obtain Connections from
 * @return a JDBC Connection from the given DataSource
 * @throws SQLException if thrown by JDBC methods
 * @see #doReleaseConnection//from w  ww. ja  v a2 s  . com
 */
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
    Assert.notNull(dataSource, "No DataSource specified");

    ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
    if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
        conHolder.requested();
        if (!conHolder.hasConnection()) {
            logger.debug("Fetching resumed JDBC Connection from DataSource");
            conHolder.setConnection(fetchConnection(dataSource));
        }
        return conHolder.getConnection();
    }
    // Else we either got no holder or an empty thread-bound holder here.

    logger.debug("Fetching JDBC Connection from DataSource");
    Connection con = fetchConnection(dataSource);

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for JDBC Connection");
        // Use same Connection for further JDBC actions within the transaction.
        // Thread-bound object will get removed by synchronization at transaction completion.
        ConnectionHolder holderToUse = conHolder;
        if (holderToUse == null) {
            holderToUse = new ConnectionHolder(con);
        } else {
            holderToUse.setConnection(con);
        }
        holderToUse.requested();
        TransactionSynchronizationManager
                .registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != conHolder) {
            TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
        }
    }

    return con;
}