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.zenoss.zep.dao.impl.DaoCacheImpl.java

private <T> T getNameFromId(final DaoTableCache<T> cache, final int id) {
    T cached = cache.getCache().getNameFromId(id);
    if (cached == null) {
        final T name = cache.findNameFromId(id);
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override//from   ww  w. j  ava  2 s.  co  m
                public void afterCommit() {
                    cache.getCache().cache(name, id);
                }
            });
        } else {
            // Not part of a transaction - can safely cache
            cache.getCache().cache(name, id);
        }
        cached = name;
    }
    return cached;
}

From source file:org.grails.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.grails.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.  jav a2s.  com
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 */
public 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.getValidatedSession();
            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;
            }
        } else {
            session = sessionHolder.getValidatedSession();
            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.sakaiproject.orm.ibatis.support.AbstractLobTypeHandler.java

/**
 * This implementation delegates to setParameterInternal,
 * passing in a transaction-synchronized LobCreator for the
 * LobHandler of this type.// w w w.j  ava2 s  . c o m
 * @see #setParameterInternal
 */
public final void setParameter(PreparedStatement ps, int i, Object parameter, String jdbcType)
        throws SQLException {

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("Spring transaction synchronization needs to be active for "
                + "setting values in iBATIS TypeHandlers that delegate to a Spring LobHandler");
    }
    final LobCreator lobCreator = this.lobHandler.getLobCreator();
    try {
        setParameterInternal(ps, i, parameter, jdbcType, lobCreator);
    } catch (IOException ex) {
        throw new SQLException("I/O errors during LOB access: " + ex.getMessage());
    }

    TransactionSynchronizationManager.registerSynchronization(new LobCreatorSynchronization(lobCreator));
}

From source file:org.vader.common.spring.TransactionScope.java

private static void registerSynchronization() {
    LOG.debug("Registers transaction synchronization");
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override//from   w  w w .  j av  a 2  s .c  o  m
        public void suspend() {
            LOG.debug("Push new transaction scope");
            SCOPES.get().push(new HashMap<String, ScopeEntry>());
        }

        @Override
        public void resume() {
            LOG.debug("Pop old transaction scope");
            SCOPES.get().pop();
        }

        @Override
        public void afterCompletion(int status) {
            final Map<String, ScopeEntry> scope = getCurrentScope();
            LOG.debug("Destroying {} beans", scope.size());
            for (Map.Entry<String, ScopeEntry> entry : scope.entrySet()) {
                for (Runnable runnable : entry.getValue().getCallbacks()) {
                    LOG.debug("Executes destruction callback for bean={}", entry.getKey());
                    runnable.run();
                }
            }
            scope.clear();
            LOG.debug("Destruction completed");
        }
    });
}

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

/**
 * Actually obtain a XDBC Session from the given ContentSource.
 * Same as {@link #getSession}, but throwing the original XccException.
 * <p>Is aware of a corresponding Session bound to the current thread, for example
 * when using {@link ContentSourceTransactionManager}. Will bind a Session to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareContentSourceProxy}.
 * @param contentSource the ContentSource to obtain Sessions from
 * @return a XDBC Session from the given ContentSource
 * @throws XccException if thrown by XDBC methods
 * @see #doReleaseSession// w ww . j  a v  a2s. c o  m
 */
public static Session doGetSession(ContentSource contentSource) throws XccException {
    Assert.notNull(contentSource, "No ContentSource specified");

    SessionHolder sesHolder = (SessionHolder) TransactionSynchronizationManager.getResource(contentSource);
    if (sesHolder != null && (sesHolder.hasSession() || sesHolder.isSynchronizedWithTransaction())) {
        sesHolder.requested();
        if (!sesHolder.hasSession()) {
            logger.debug("Fetching resumed XDBC Session from ContentSource");
            sesHolder.setSession(contentSource.newSession());
        }
        return sesHolder.getSession();
    }
    // Else we either got no holder or an empty thread-bound holder here.

    logger.debug("Fetching XDBC Session from ContentSource");
    Session ses = contentSource.newSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for XDBC Session");
        // Use same Session for further XDBC actions within the transaction.
        // Thread-bound object will get removed by synchronization at transaction completion.
        SessionHolder holderToUse = sesHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(ses);
        } else {
            holderToUse.setSession(ses);
        }
        holderToUse.requested();
        TransactionSynchronizationManager
                .registerSynchronization(new SessionSynchronization(holderToUse, contentSource));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sesHolder) {
            TransactionSynchronizationManager.bindResource(contentSource, holderToUse);
        }
    }

    return ses;
}

From source file:com.avaje.ebean.springsupport.txn.SpringAwareJdbcTransactionManager.java

/**
 * Looks for a current Spring managed transaction and wraps/returns that as a Ebean transaction.
 * <p>//  w  w w  .j a v  a  2 s.  com
 * Returns null if there is no current spring transaction (lazy loading outside a spring txn etc).
 * </p>
 */
public Object getCurrentTransaction() {

    // Get the current Spring ConnectionHolder associated to the current spring managed transaction
    ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);

    if (holder == null || !holder.isSynchronizedWithTransaction()) {
        // no current Spring transaction
        SpiTransaction currentEbeanTransaction = DefaultTransactionThreadLocal.get(serverName);
        if (currentEbeanTransaction != null) {
            // NOT expecting this so log WARNING
            String msg = "SpringTransaction - no current spring txn BUT using current Ebean one "
                    + currentEbeanTransaction.getId();
            logger.log(Level.WARNING, msg);

        } else if (logger.isLoggable(Level.FINEST)) {
            logger.log(Level.FINEST, "Spring Txn - no current transaction ");
        }
        return currentEbeanTransaction;
    }

    SpringTxnListener springTxnLister = getSpringTxnListener();

    if (springTxnLister != null) {
        // we have already seen this transaction 
        return springTxnLister.getTransaction();

    } else {
        // This is a new spring transaction that we have not seen before.
        // "wrap" it in a SpringJdbcTransaction for use with Ebean 
        SpringJdbcTransaction newTrans = new SpringJdbcTransaction(holder, transactionManager);

        // Create and register a Spring TransactionSynchronization for this transaction
        springTxnLister = createSpringTxnListener(newTrans);
        TransactionSynchronizationManager.registerSynchronization(springTxnLister);

        // also put in Ebean ThreadLocal
        DefaultTransactionThreadLocal.set(serverName, newTrans);
        return newTrans;
    }
}

From source file:org.apache.servicemix.transaction.GeronimoPlatformTransactionManager.java

protected void registerTransactionAssociationListener() {
    addTransactionAssociationListener(new TransactionManagerMonitor() {
        public void threadAssociated(Transaction transaction) {
            try {
                if (transaction.getStatus() == Status.STATUS_ACTIVE) {
                    SuspendedResourcesHolder holder = suspendedResources.remove(transaction);
                    if (holder != null && holder.getSuspendedSynchronizations() != null) {
                        TransactionSynchronizationManager.setActualTransactionActive(true);
                        TransactionSynchronizationManager.setCurrentTransactionReadOnly(holder.isReadOnly());
                        TransactionSynchronizationManager.setCurrentTransactionName(holder.getName());
                        TransactionSynchronizationManager.initSynchronization();
                        for (Iterator<?> it = holder.getSuspendedSynchronizations().iterator(); it.hasNext();) {
                            TransactionSynchronization synchronization = (TransactionSynchronization) it.next();
                            synchronization.resume();
                            TransactionSynchronizationManager.registerSynchronization(synchronization);
                        }//from w w w .ja  v  a2 s  .c o  m
                    }
                }
            } catch (SystemException e) {
                return;
            }
        }

        public void threadUnassociated(Transaction transaction) {
            try {
                if (transaction.getStatus() == Status.STATUS_ACTIVE) {
                    if (TransactionSynchronizationManager.isSynchronizationActive()) {
                        List<?> suspendedSynchronizations = TransactionSynchronizationManager
                                .getSynchronizations();
                        for (Iterator<?> it = suspendedSynchronizations.iterator(); it.hasNext();) {
                            ((TransactionSynchronization) it.next()).suspend();
                        }
                        TransactionSynchronizationManager.clearSynchronization();
                        String name = TransactionSynchronizationManager.getCurrentTransactionName();
                        TransactionSynchronizationManager.setCurrentTransactionName(null);
                        boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
                        TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
                        TransactionSynchronizationManager.setActualTransactionActive(false);
                        SuspendedResourcesHolder holder = new SuspendedResourcesHolder(null,
                                suspendedSynchronizations, name, readOnly);
                        suspendedResources.put(transaction, holder);
                    }
                }
            } catch (SystemException e) {
                return;
            }
        }
    });
}

From source file:org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager.java

public void registerTransactionSynchronization(TransactionSynchronization ts) {
    TransactionSynchronizationManager.registerSynchronization(new SpringTransactionSynchronizationAdapter(ts));
}

From source file:org.mybatis.spring.SqlSessionUtils.java

/**
 * Register session holder if synchronization is active (i.e. a Spring TX is active).
 *
 * Note: The DataSource used by the Environment 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.
 * /*from  ww w .j  av a2  s.com*/
 * @param sessionFactory sqlSessionFactory used for registration.
 * @param executorType executorType used for registration.
 * @param exceptionTranslator persistenceExceptionTranslater used for registration.
 * @param session sqlSession used for registration.
 */
private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator, SqlSession session) {
    SqlSessionHolder holder;
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Environment environment = sessionFactory.getConfiguration().getEnvironment();

        if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
            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 (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("SqlSession [" + session
                            + "] was not registered for synchronization because DataSource is not transactional");
                }
            } else {
                throw new TransientDataAccessResourceException(
                        "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }
}