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

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

Introduction

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

Prototype

public static void bindResource(Object key, Object value) throws IllegalStateException 

Source Link

Document

Bind the given resource for the given key to the current thread.

Usage

From source file:org.grails.orm.hibernate3.support.HibernatePersistenceContextInterceptor.java

public void init() {
    if (incNestingCount() > 1) {
        return;/*from  ww  w  .j a  v a 2 s . com*/
    }
    SessionFactory sf = getSessionFactory();
    if (sf == null) {
        return;
    }
    if (TransactionSynchronizationManager.hasResource(sf)) {
        // Do not modify the Session: just set the participate flag.
        setParticipate(true);
    } else {
        setParticipate(false);
        LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
        Session session = getSession();
        HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}

From source file:org.hyperic.hq.hibernate.SessionManager.java

private void runInSessionInternal(final SessionRunner r) throws Exception {
    boolean participate = false;
    try {/*from  w  w  w.  j a v a2  s.  c om*/

        if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
            // Do not modify the Session: just set the participate flag.
            participate = true;
        } else {
            Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);
            session.setFlushMode(FlushMode.MANUAL);
            TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
        }
        HibernateTemplate template = getHibernateTemplate();
        template.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                try {
                    r.run();
                } catch (Exception e) {
                    throw new HibernateException(e);
                }
                return null;
            }
        });
    } finally {
        if (!participate) {

            // single session mode
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                    .unbindResource(getSessionFactory());
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
        }
    }

}

From source file:org.jasig.ssp.dao.external.ExternalCourseDao.java

@Override
public void afterPropertiesSet() throws Exception {
    try {/*ww w.  ja  v  a 2 s.c  o  m*/
        Session session = sessionFactory.openSession();
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
        flushAndLoadCache();
        lastCacheFlush = Calendar.getInstance();
    } finally {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .unbindResource(sessionFactory);
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

protected Runnable withHibernateSession(final Runnable work) {
    return new Runnable() {
        @Override//from w ww .  j  a v a  2s.  c  o  m
        public void run() {
            // Basically a copy/paste of Spring's
            // OpenSessionInViewFilter#doFilterInternal, with the
            // web-specific stuff removed
            boolean participate = false;
            try {
                if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
                    // Do not modify the Session: just set the participate flag.
                    LOGGER.debug("Scheduled task joining existing Hibernate session/transaction");
                    participate = true;
                } else {
                    LOGGER.debug("Scheduled task creating new Hibernate session");
                    Session session = sessionFactory.openSession();
                    session.setFlushMode(FlushMode.MANUAL);
                    SessionHolder sessionHolder = new SessionHolder(session);
                    TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
                }

                work.run();

            } finally {
                if (!participate) {
                    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                            .unbindResource(sessionFactory);
                    LOGGER.debug("Scheduled task closing Hibernate session");
                    SessionFactoryUtils.closeSession(sessionHolder.getSession());
                } else {
                    LOGGER.debug(
                            "Scheduled task joined existing Hibernate session/transaction so skipping that cleanup step");
                }
            }
        }
    };
}

From source file:org.openmrs.api.db.hibernate.HibernateContextDAO.java

public void openSession() {
    log.debug("HibernateContext: Opening Hibernate Session");
    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
        if (log.isDebugEnabled()) {
            log.debug("Participating in existing session (" + sessionFactory.hashCode() + ")");
        }/*  w ww. j  a v a2s.  c om*/
        participate = true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Registering session with synchronization manager (" + sessionFactory.hashCode() + ")");
        }
        Session session = sessionFactory.openSession();
        session.setFlushMode(FlushMode.MANUAL);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    }
}

From source file:org.osaf.cosmo.hibernate.ThrowAwayHibernateSessionOnErrorInterceptor.java

private void handleException() {

    // If session is bound to transaction, close it and create/bind
    // new session to prevent stale data when retrying transaction
    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {

        if (log.isDebugEnabled())
            log.debug("throwing away bad session and binding new one");

        // Get current session and close
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .unbindResource(sessionFactory);

        SessionFactoryUtils.closeSession(sessionHolder.getSession());

        // Open new session and bind (this session should be closed and
        // unbound elsewhere, for example OpenSessionInViewFilter)
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        session.setFlushMode(FlushMode.MANUAL);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    }/*  w w  w. ja  v  a 2  s. c o  m*/
}

From source file:org.osaf.cosmo.scheduler.HibernateSessionFilter.java

private void bindSession() {
    log.debug("binding session to thread");

    // Get a reference to the Session and bind it to the TransactionManager
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

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 ww.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.amqp.rabbit.listener.AbstractMessageListenerContainer.java

/**
 * Invoke the specified listener: either as standard MessageListener or (preferably) as SessionAwareMessageListener.
 * @param channel the Rabbit Channel to operate on
 * @param message the received Rabbit Message
 * @throws Exception if thrown by Rabbit API methods
 * @see #setMessageListener//from  w w  w  .j  av a2s .  c om
 */
protected void actualInvokeListener(Channel channel, Message message) throws Exception {
    Object listener = getMessageListener();
    if (listener instanceof ChannelAwareMessageListener) {
        doInvokeListener((ChannelAwareMessageListener) listener, channel, message);
    } else if (listener instanceof MessageListener) {
        boolean bindChannel = isExposeListenerChannel() && isChannelLocallyTransacted();
        if (bindChannel) {
            RabbitResourceHolder resourceHolder = new RabbitResourceHolder(channel, false);
            resourceHolder.setSynchronizedWithTransaction(true);
            TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder);
        }
        try {
            doInvokeListener((MessageListener) listener, message);
        } finally {
            if (bindChannel) {
                // unbind if we bound
                TransactionSynchronizationManager.unbindResource(this.getConnectionFactory());
            }
        }
    } else if (listener != null) {
        throw new FatalListenerExecutionException(
                "Only MessageListener and SessionAwareMessageListener supported: " + listener);
    } else {
        throw new FatalListenerExecutionException(
                "No message listener specified - see property 'messageListener'");
    }
}

From source file:org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.java

/**
 * Invoke the specified listener as Spring ChannelAwareMessageListener, exposing a new Rabbit Session (potentially
 * with its own transaction) to the listener if demanded.
 * @param listener the Spring ChannelAwareMessageListener to invoke
 * @param channel the Rabbit Channel to operate on
 * @param message the received Rabbit Message
 * @throws Exception if thrown by Rabbit API methods or listener itself.
 * <p>/* w w  w  .  ja v  a 2s  .c o m*/
 * Exception thrown from listener will be wrapped to {@link ListenerExecutionFailedException}.
 * @see ChannelAwareMessageListener
 * @see #setExposeListenerChannel(boolean)
 */
protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Message message)
        throws Exception {

    RabbitResourceHolder resourceHolder = null;
    Channel channelToUse = channel;
    boolean boundHere = false;
    try {
        if (!isExposeListenerChannel()) {
            // We need to expose a separate Channel.
            resourceHolder = getTransactionalResourceHolder();
            channelToUse = resourceHolder.getChannel();
            /*
             * If there is a real transaction, the resource will have been bound; otherwise
             * we need to bind it temporarily here. Any work done on this channel
             * will be committed in the finally block.
             */
            if (isChannelLocallyTransacted()
                    && !TransactionSynchronizationManager.isActualTransactionActive()) {
                resourceHolder.setSynchronizedWithTransaction(true);
                TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder);
                boundHere = true;
            }
        } else {
            // if locally transacted, bind the current channel to make it available to RabbitTemplate
            if (isChannelLocallyTransacted()) {
                RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false);
                localResourceHolder.setSynchronizedWithTransaction(true);
                TransactionSynchronizationManager.bindResource(this.getConnectionFactory(),
                        localResourceHolder);
                boundHere = true;
            }
        }
        // Actually invoke the message listener...
        try {
            listener.onMessage(message, channelToUse);
        } catch (Exception e) {
            throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message);
        }
    } finally {
        if (resourceHolder != null && boundHere) {
            // so the channel exposed (because exposeListenerChannel is false) will be closed
            resourceHolder.setSynchronizedWithTransaction(false);
        }
        ConnectionFactoryUtils.releaseResources(resourceHolder);
        if (boundHere) {
            // unbind if we bound
            TransactionSynchronizationManager.unbindResource(this.getConnectionFactory());
            if (!isExposeListenerChannel() && isChannelLocallyTransacted()) {
                /*
                 *  commit the temporary channel we exposed; the consumer's channel
                 *  will be committed later. Note that when exposing a different channel
                 *  when there's no transaction manager, the exposed channel is committed
                 *  on each message, and not based on txSize.
                 */
                RabbitUtils.commitIfNecessary(channelToUse);
            }
        }
    }
}