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

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

Introduction

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

Prototype

@Nullable
public static Object getResource(Object key) 

Source Link

Document

Retrieve a resource for the given key that is bound to the current thread.

Usage

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   w  w  w. j ava2  s . c o  m*/
 * @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");
        }
    }
}

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

/**
 * {@inheritDoc}/*from   w ww  .j  av  a2s  .c  o  m*/
 */
@Override
protected Object doGetTransaction() {
    CayenneTransactionObject txObject = new CayenneTransactionObject();
    txObject.setSavepointAllowed(isNestedTransactionAllowed());
    ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager
            .getResource(this.dataSource);
    txObject.setConnectionHolder(conHolder, false);
    return txObject;
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}//from  w  w w  .j  a  va 2  s  .  c  om
 */
@Override
public void saveUser(User user) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    em.persist(user);
    tx.commit();
}

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//from w ww  .j  av  a  2  s .c  o m
 * @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:org.guzz.web.context.spring.GuzzTransactionManager.java

@Override
protected Object doGetTransaction() {
    GuzzTransactionObject txObject = new GuzzTransactionObject();

    WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager
            .getResource(getTransactionManager());

    if (writeTranSessionHolder != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found thread-bound WriteTranSession ["
                    + TransactionManagerUtils.toString(writeTranSessionHolder.getWriteTranSession())
                    + "] for Guzz transaction");
        }/*from ww w .  j  a va  2s  .co  m*/
        txObject.setWriteTranSessionHolder(writeTranSessionHolder);
    }

    return txObject;
}

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

/**
 * Binds the Alfresco-specific to the transaction resources
 * /*  w ww .  j  ava  2s.  c  o 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:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}//from ww  w. ja  va 2  s.c o  m
 */
@Override
public User activateUser(User user, String licenseCode) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    License l = getLicenseByCode(em, licenseCode);
    if (l != null) {
        if (!tx.isActive()) {
            tx.begin();
        }
        user.setType(User.Type.valueOf(l.getType().name()));
        user.setStatus(User.Status.ACTIVE);
        user = em.merge(user);
        em.remove(l);
        tx.commit();
    }
    return user;
}

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

/**
 * Return whether the given Datastore Session is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param session the Datastore Session to check
 * @param datastore Datastore that the Session was created with
 * (may be <code>null</code>)
 * @return whether the Session is transactional
 */// w  w w.j av a 2 s .c o m
public static boolean isSessionTransactional(Session session, Datastore datastore) {
    if (datastore == null) {
        return false;
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(datastore);
    return (sessionHolder != null && sessionHolder.containsSession(session));
}

From source file:org.apacheextras.camel.component.wmq.WMQConsumer.java

/**
 * {@inheritDoc}/* ww w .j a v a  2  s.com*/
 * 
 * 
 * Creates a new TransactionCallback object which will contain our transaction which follows:
 * 
 *  Get the MQQueueManager for this transaction
 *  Open a connection to the destination
 *  Get a message
 *  Process message
 */
@Override
protected int poll() throws Exception {
    LOGGER.debug("Poll invoked on WMQConsumer");
    getTransactionTemplate().execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus status) {

            LOGGER.trace("Get the MQQueueManager for this transaction");
            MQQueueManager manager = (MQQueueManager) TransactionSynchronizationManager
                    .getResource("queueManager");
            String id = (String) TransactionSynchronizationManager.getResource("id");

            LOGGER.debug("Consumer transaction started with id " + id + " and mananger " + manager.toString());

            Exchange exchange = getEndpoint().createExchange();

            Message in = exchange.getIn();

            MQDestination destination = null;
            try {
                LOGGER.trace("Consuming from {}", getEndpoint().getDestinationName());

                String destinationName = getEndpoint().getDestinationName();
                int MQOO;

                if (destinationName.startsWith("topic:")) {
                    MQOO = CMQC.MQSO_CREATE | CMQC.MQSO_RESUME | CMQC.MQSO_DURABLE
                            | CMQC.MQSO_FAIL_IF_QUIESCING;
                } else {
                    if (destinationName.startsWith("queue:")) {
                        MQOO = MQConstants.MQOO_INPUT_AS_Q_DEF;
                    } else {
                        MQOO = -1;
                    }
                }

                LOGGER.trace("Create connection to the destination {}", destinationName);
                destination = wmqUtilities.accessDestination(getEndpoint().getDestinationName(), MQOO, manager);

                MQMessage message = new MQMessage();
                MQGetMessageOptions options = new MQGetMessageOptions();
                options.options = MQConstants.MQGMO_WAIT + MQConstants.MQGMO_PROPERTIES_COMPATIBILITY
                        + MQConstants.MQGMO_ALL_SEGMENTS_AVAILABLE + MQConstants.MQGMO_COMPLETE_MSG
                        + MQConstants.MQGMO_ALL_MSGS_AVAILABLE;
                options.waitInterval = MQConstants.MQWI_UNLIMITED;
                LOGGER.trace("Waiting for message ...");

                LOGGER.trace("DESTINATION OPEN? " + destination.isOpen());
                LOGGER.trace(
                        "QUEUE MANAGER OPEN? CONNECTED?" + manager.isConnected() + ", " + manager.isOpen());

                destination.get(message, options);

                LOGGER.trace("Message consumed");

                LOGGER.trace("Dealing with MQMD headers");
                populateHeaders(message, in);

                LOGGER.trace("Reading body");
                byte[] buffer = new byte[message.getDataLength()];
                message.readFully(buffer);
                String body = new String(buffer, "UTF-8");

                in.setBody(body, String.class);

                getProcessor().process(exchange);
                LOGGER.debug(
                        "Consumer transaction finished with id " + id + " and mananger " + manager.toString());
            } catch (Exception e) {
                exchange.setException(e);
            } /* finally {
                /* if (destination != null) {
                destination.close();
                 }
              }*/

            if (exchange.getException() != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange,
                        exchange.getException());
            }

            return 1;
        }
    });

    return 1;
}