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

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

Introduction

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

Prototype

public static boolean hasResource(Object key) 

Source Link

Document

Check if there is a resource for the given key bound to the current thread.

Usage

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

/**
 * @see org.openmrs.api.context.Context#closeSession()
 *///from ww w.j  a  va 2 s .com
public void closeSession() {
    log.debug("HibernateContext: closing Hibernate Session");
    if (!participate) {
        log.debug("Unbinding session from synchronization manager (" + sessionFactory.hashCode() + ")");

        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            Object value = TransactionSynchronizationManager.unbindResource(sessionFactory);
            try {
                if (value instanceof SessionHolder) {
                    Session session = ((SessionHolder) value).getSession();
                    SessionFactoryUtils.closeSession(session);
                }
            } catch (RuntimeException e) {
                log.error("Unexpected exception on closing Hibernate Session", e);
            }
        }
    } else {
        log.debug(
                "Participating in existing session, so not releasing session through synchronization manager");
    }
}

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  ww  .  j av  a2 s . com
}

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  www . ja  v a2s . c  om
    }
    TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolder);
    resourceHolder.setSynchronizedWithTransaction(true);
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(
                new RabbitResourceSynchronization(resourceHolder, connectionFactory, synched));
    }
}

From source file:org.springframework.data.neo4j.web.support.OpenSessionInViewInterceptor.java

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
            return;
        }//from   w ww .  j  a  v a  2  s.c o  m
    }

    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Neo4j OGM Session in OpenSessionInViewInterceptor");
        Session session = sessionFactory.openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

        AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
    }
}

From source file:org.springframework.jms.connection.JmsResourceHolder.java

public void commitAll() throws JMSException {
    for (Session session : this.sessions) {
        try {/*  w ww. j a  va 2  s  . c  om*/
            session.commit();
        } catch (TransactionInProgressException ex) {
            // Ignore -> can only happen in case of a JTA transaction.
        } catch (javax.jms.IllegalStateException ex) {
            if (this.connectionFactory != null) {
                try {
                    Method getDataSourceMethod = this.connectionFactory.getClass().getMethod("getDataSource");
                    Object ds = ReflectionUtils.invokeMethod(getDataSourceMethod, this.connectionFactory);
                    while (ds != null) {
                        if (TransactionSynchronizationManager.hasResource(ds)) {
                            // IllegalStateException from sharing the underlying JDBC Connection
                            // which typically gets committed first, e.g. with Oracle AQ --> ignore
                            return;
                        }
                        try {
                            // Check for decorated DataSource a la Spring's DelegatingDataSource
                            Method getTargetDataSourceMethod = ds.getClass().getMethod("getTargetDataSource");
                            ds = ReflectionUtils.invokeMethod(getTargetDataSourceMethod, ds);
                        } catch (NoSuchMethodException nsme) {
                            ds = null;
                        }
                    }
                } catch (Throwable ex2) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("No working getDataSource method found on ConnectionFactory: " + ex2);
                    }
                    // No working getDataSource method - cannot perform DataSource transaction check
                }
            }
            throw ex;
        }
    }
}

From source file:org.springframework.jms.core.JmsTemplate.java

protected void doSend(Session session, Destination destination, MessageCreator messageCreator)
        throws JMSException {
    MessageProducer producer = createProducer(session, destination);
    Message message = messageCreator.createMessage(session);
    if (logger.isDebugEnabled()) {
        logger.debug("Sending created message [" + message + "]");
    }/*from w  w  w . j av  a 2 s  . c om*/
    doSend(producer, message);
    if (session.getTransacted() && !TransactionSynchronizationManager.hasResource(getConnectionFactory())) {
        // transacted session created by this template -> commit
        session.commit();
    }
}

From source file:org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor.java

/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link org.springframework.transaction.support.TransactionSynchronizationManager}.
 *///from   w w  w  .  j a v a2 s  .  com
@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
            return;
        }
    }

    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
        Session session = openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

        AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(getSessionFactory(),
                sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
    }
}

From source file:org.springframework.orm.hibernate43.support.OpenSessionInViewInterceptor.java

/**
 * Open a new Hibernate {@code Session} according to the settings of this
 * {@code HibernateAccessor} and bind it to the thread via the
 * {@link org.springframework.transaction.support.TransactionSynchronizationManager}.
 */// ww w . j av a  2 s. c  o m
public void preHandle(WebRequest request) throws DataAccessException {

    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
            return;
        }
    }

    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
        Session session = openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

        AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(getSessionFactory(),
                sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
    }
}

From source file:org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor.java

/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 *///from w  ww.j ava  2s.co  m
@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
            return;
        }
    }

    if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
        Session session = openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

        AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(),
                sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
    }
}

From source file:org.springframework.orm.jdo.support.OpenPersistenceManagerInViewInterceptor.java

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) {
        // Do not modify the PersistenceManager: just mark the request accordingly.
        String participateAttributeName = getParticipateAttributeName();
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {/*from  w ww .jav a  2s  .com*/
        logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
        PersistenceManager pm = PersistenceManagerFactoryUtils
                .getPersistenceManager(getPersistenceManagerFactory(), true);
        TransactionSynchronizationManager.bindResource(getPersistenceManagerFactory(),
                new PersistenceManagerHolder(pm));
    }
}