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

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

Introduction

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

Prototype

public static void registerSynchronization(TransactionSynchronization synchronization)
        throws IllegalStateException 

Source Link

Document

Register a new transaction synchronization for the current thread.

Usage

From source file:org.cfr.capsicum.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 .  j  av  a 2  s.co  m*/
 */
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
    Assert.notNull(dataSource, "No DataSource specified");

    CayenneConnectionHolder conHolder = (CayenneConnectionHolder) 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(dataSource.getConnection());
        }
        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 = dataSource.getConnection();

    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.
        CayenneConnectionHolder holderToUse = conHolder;
        if (holderToUse == null) {
            ObjectContext context = BaseContext.getThreadObjectContext();
            holderToUse = new CayenneConnectionHolder(con, context);
        } else {
            holderToUse.setConnection(con);
        }
        holderToUse.requested();
        TransactionSynchronizationManager
                .registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != conHolder) {
            TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
        }
    }

    return con;
}

From source file:org.brekka.pegasus.core.services.impl.ProfileServiceImpl.java

@Override
@Transactional(propagation = Propagation.MANDATORY)
public void currentUserProfileUpdated() {
    List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
    for (TransactionSynchronization transactionSynchronization : synchronizations) {
        if (transactionSynchronization instanceof ProfileSynchronization) {
            // Already added for update
            return;
        }//from   w  ww . ja v  a  2  s .c o  m
    }
    MemberContext current = memberService.retrieveCurrent();
    Profile activeProfile = current.getActiveProfile();
    if (activeProfile.getId() != null) {
        TransactionSynchronizationManager.registerSynchronization(new ProfileSynchronization(activeProfile));
    }
}

From source file:org.kbac.spring.scope.TransactionScope.java

/**
 * {@inheritDoc}/*from  w w  w.j  a v a2s . com*/
 */
@Override
public Object get(String beanName, ObjectFactory<?> factory) {
    final String currentTransactionId = getCurrentTransactionId();
    final boolean isDebugEnabled = logger.isDebugEnabled();

    if (inDescopingIsolationLevel() || currentTransactionId == null) {
        if (isDebugEnabled) {
            logger.debug("returning prototype bean for [" + beanName + "]");
        }
        return factory.getObject();
    }

    Map<String, Object> namedBeans = transactionNamedBeans.get(currentTransactionId);
    if (namedBeans == null) {
        namedBeans = new HashMap<String, Object>();
        transactionNamedBeans.put(currentTransactionId, namedBeans);
        TransactionSynchronizationManager
                .registerSynchronization(new NamedTransactionSynchronisation(currentTransactionId));
        if (isDebugEnabled) {
            logger.debug("created new cache for [" + currentTransactionId + "]");
        }
    }

    Object bean = namedBeans.get(beanName);
    if (bean == null) {
        bean = factory.getObject();
        final Object previousBean = namedBeans.put(beanName, bean);
        if (isDebugEnabled) {
            logger.debug("returning new bean added to cache [" + beanName + "]->[" + bean + "] replacing ["
                    + previousBean + "]");
        }
    } else {
        if (isDebugEnabled) {
            logger.debug("returning cached bean [" + beanName + "]->[" + bean + "]");
        }
    }
    return bean;
}

From source file:org.grails.orm.hibernate.GrailsSessionContext.java

private Session createSession(Object resource) {
    LOG.debug("Opening Hibernate Session");

    SessionHolder sessionHolder = (SessionHolder) resource;

    Session session = sessionFactory.openSession();

    // Use same Session for further Hibernate 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.
        LOG.debug("Registering Spring transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {/*from  w w  w  .  ja v a  2 s .c o m*/
            // it's up to the caller to manage concurrent sessions
            // holderToUse.addSession(session);
        }
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        TransactionSynchronizationManager
                .registerSynchronization(createSpringSessionSynchronization(holderToUse));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } else {
        // No Spring transaction management active -> try JTA transaction synchronization.
        registerJtaSynchronization(session, sessionHolder);
    }

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

From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java

public void testContainsSynchronization() {

    // Create a synchronization to register, and call if successful
    final TrialTransactionSync txSync = new TrialTransactionSync();

    Object retVal = txTempl.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            TransactionSynchronizationManager.registerSynchronization(txSync);
            return txSyncManWrapper.containsSynchronization(TrialTransactionSync.class);
        }// w w w  .j a v  a  2 s . c o  m
    });

    assertEquals(true, retVal);
    assertTrue(txSync.wasCalled());
}

From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java

private EntityManager addThreadLocalEntityManager(EntityManager em) {
    TransactionSynchronizationManager.registerSynchronization(new SessionCloseSynchronizationManager());
    entityManagerLocal.set(em);/*from  w w  w .j a va2s.  c o m*/
    return em;
}

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

/**
 * Binds the Alfresco-specific to the transaction resources
 * /*  www  .  j  av  a 2 s.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.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.c om
 * 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.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.//  ww  w .  j ava2  s.  co  m
 *
 * @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:de.codecentric.batch.metrics.BatchMetricsImpl.java

private void initializeMetricContainerAndRegisterTransactionSynchronizationIfNecessary() {
    if (!TransactionSynchronizationManager.hasResource(serviceKey)) {
        TransactionSynchronizationManager.bindResource(serviceKey, new StringBuffer());
        TransactionSynchronizationManager.registerSynchronization(this);
    }/*from  ww  w .j a  v a2s.c  om*/
    if (metricContainer.get() == null) {
        metricContainer.set(new MetricContainer());
    }
}