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.codehaus.groovy.grails.plugins.springsecurity.GrailsWebApplicationObjectSupport.java

/**
 * Set up hibernate session./*from  ww w . jav  a2  s. c om*/
 * @return  the session container, which holds the session and a boolean indicating if the session was pre-existing
 */
protected SessionContainer setUpSession() {
    SessionFactory sessionFactory = getSessionFactory();

    Session session;
    boolean existing;
    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
        logger.debug("Session already has transaction attached");
        existing = true;
        session = ((SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
    } else {
        logger.debug("Session does not have transaction attached... Creating new one");
        existing = false;
        session = SessionFactoryUtils.getSession(sessionFactory, true);
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return new SessionContainer(session, existing);
}

From source file:org.codehaus.groovy.grails.plugins.acegi.GrailsWebApplicationObjectSupport.java

/**
 * set up hibernate session//from  w w w.ja v a2 s.co  m
 */
protected void setUpSession() {
    try {
        sessionFactory = (SessionFactory) getWebApplicationContext().getBean("sessionFactory");

        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            if (logger.isDebugEnabled())
                logger.debug("Session already has transaction attached");
            containerManagedSession = true;
            this.session = ((SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory))
                    .getSession();
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Session does not have transaction attached... Creating new one");
            containerManagedSession = false;
            session = SessionFactoryUtils.getSession(sessionFactory, true);
            SessionHolder sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:podd.dataaccess.AbstractDAOUnitTest.java

@Before
public void setUp() throws Exception {

    // To avoid LazyInitializationException
    SessionFactory sessionFactory = PODD_CONTEXT.getSessionFactory();
    if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    }//  w ww  . java2 s .c o m

    pidDao = PODD_CONTEXT.getPIDHolderDAO();
    fedoraUtil = PODD_CONTEXT.getFedoraUtil();
    entityFactory = PODD_CONTEXT.getEntityFactory();
    ontologyHelper = PODD_CONTEXT.getOntologyHelper();
    entityValidator = PODD_CONTEXT.getEntityValidator();
    pidGenerator = PODD_CONTEXT.getHibernatePIDGenerator();

    clearDB(PoddEntity.class);
    clearDB(UserSearchCriteria.class);
    clearDB(User.class);
    clearDB("RepositoryRole");
    setupDefaultRepoRoles();

    user = entityFactory.createUser(null);
    populateUser(user);
    userDAO = getUserDAO();
    userDAO.save(user);
    entity = getEntity();

}

From source file:corner.orm.tapestry.filter.OneSessionPerServletRequestFilter.java

public void service(WebRequest request, WebResponse response, WebRequestServicer servicer) throws IOException {
    //      String pathInfo=request.getPathInfo();
    if (request.getActivationPath().startsWith("/assets")) { //assetsopen session in view
        servicer.service(request, response);
        return;//from   w  w w  .j  a v  a2s .co  m
    }
    Session session = null;
    boolean participate = false;

    if (isSingleSession()) {

        // single session mode
        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            // Do not modify the Session: just set the participate flag.
            participate = true;
        } else {
            log.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
            session = getSession(sessionFactory);
            TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
        }
    } else {
        // deferred close mode
        if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
            // Do not modify deferred close: just set the participate flag.
            participate = true;
        } else {
            SessionFactoryUtils.initDeferredClose(sessionFactory);
        }
    }

    try {
        servicer.service(request, response);
    }

    finally {
        if (!participate) {
            if (isSingleSession()) {
                // single session mode
                TransactionSynchronizationManager.unbindResource(sessionFactory);
                log.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
                try {
                    closeSession(session, sessionFactory);
                } catch (RuntimeException ex) {
                    log.error("Unexpected exception on closing Hibernate Session", ex);
                }
            } else {
                // deferred close mode
                SessionFactoryUtils.processDeferredClose(sessionFactory);
            }
        }
    }
}

From source file:hsa.awp.common.test.OpenEntityManagerInTest.java

/**
 * Opens an {@link EntityManager} per test.
 *//*from   w w  w.  j a  v  a  2 s  . c  o  m*/
@Before
public final void openEntityManager() {

    create = !TransactionSynchronizationManager.hasResource(emf);

    if (create) {
        log.debug("Opening EntityManager");
        em = emf.createEntityManager();

        log.trace("Binding EntityManager to thread '{}'", Thread.currentThread().getName());
        TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
    } else {
        log.debug("Don't open EntityManager because of @Transactional annotation");
    }
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java

@Test
public void testTransactionRollback() {
    final ODB odb = Mockito.mock(ODB.class);
    Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException());
    PlatformTransactionManager tm = new NeoDatisTransactionManager(odb);
    TransactionTemplate tmpl = new TransactionTemplate(tm);

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    try {// ww w.j a v a 2s .  c  om
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
                NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
                neoDatisTemplate.store(null);
            }
        });
    } catch (RuntimeException e) {
        // is ok
    }

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    Mockito.verify(odb, Mockito.times(1)).rollback();
}

From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java

@Test
public void testTransactionRollback() throws Exception {
    final ExtObjectContainer container = mock(ExtObjectContainer.class);
    when(container.identity()).thenReturn(null);
    when(container.ext()).thenReturn(container);

    PlatformTransactionManager tm = new Db4oTransactionManager(container);
    TransactionTemplate tt = new TransactionTemplate(tm);

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    try {/*from  ww  w  . j av a2  s  .  co  m*/
        tt.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(container),
                        "Has thread session");
                Db4oTemplate template = new Db4oTemplate(container);
                template.execute(new Db4oCallback() {
                    public Object doInDb4o(ObjectContainer cont) {
                        cont.ext().identity();
                        throw new RuntimeException();
                    }

                });
            }
        });
    } catch (RuntimeException e) {
        // it's okay
    }

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    verify(container).rollback();
}

From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java

/** @see Closure#execute(Object) */
public final void execute(final T t) {
    if (dryrun) {
        //permite evitar que se hagan commit() en el ambiente de test
        target.execute(t);/*  w  w w  .j a  v  a2s . c o m*/
    } else {
        boolean participate = false;
        EntityTransaction transaction = null;

        if (TransactionSynchronizationManager.hasResource(emf)) {
            // Do not modify the EntityManager: just set the participate flag.
            participate = true;
        } else {
            try {
                final EntityManager em = emf.createEntityManager();
                if (openTx) {
                    if (!warningPrinted) {
                        logger.warn(
                                "The OpenEntityManagerClosure has Transactions enabled and is not recommended"
                                        + ". This behaviour will change in the future. Check setOpenTx(), ");
                    }
                    transaction = em.getTransaction();
                    transaction.begin();
                }

                TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
            } catch (PersistenceException ex) {
                throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
            }
        }

        if (transaction != null) {
            try {
                target.execute(t);
                if (transaction.getRollbackOnly()) {
                    transaction.rollback();
                } else {
                    transaction.commit();
                }
            } catch (final Throwable e) {
                if (transaction != null && transaction.isActive()) {
                    transaction.rollback();
                }
                throw new UnhandledException(e);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }
        } else {
            try {
                target.execute(t);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }

        }
    }
}

From source file:org.openvpms.component.business.dao.hibernate.im.common.Context.java

/**
 * Returns the context for the given assembler and session and current
 * thread./*from   w  w  w  .  j a va2s .  c o  m*/
 * <p/>
 * If one does not exist, it will be created.
 *
 * @param assembler the assembler
 * @param session   the hibernate session
 * @return the context
 */
public static Context getContext(Assembler assembler, Session session) {
    Context context;
    ResourceKey key = new ResourceKey(session);
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!TransactionSynchronizationManager.hasResource(key)) {
            context = new Context(assembler, session, true);
            TransactionSynchronizationManager.bindResource(context.getResourceKey(), context);
            TransactionSynchronizationManager.registerSynchronization(new ContextSynchronization(context));
        } else {
            context = (Context) TransactionSynchronizationManager.getResource(key);
        }
    } else {
        context = new Context(assembler, session, false);
    }
    return context;
}

From source file:org.codehaus.groovy.grails.webflow.persistence.SessionAwareHibernateFlowExecutionListener.java

private boolean isSessionAlreadyBound() {
    return TransactionSynchronizationManager.hasResource(localSessionFactory);
}