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.develspot.data.orientdb.transaction.OrientDBTransactionManager.java

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {

    OrientDBTransactionObject txObject = (OrientDBTransactionObject) transaction;

    try {/*  w ww .  j  av  a  2 s .  c om*/

        if (txObject.getConnectionHolder() == null) {
            OGraphDatabase con = this.orientDataSource.getConnection();
            txObject.setConnectionHolder(new GraphDatabaseHolder(con));
        }

        txObject.getConnectionHolder().setTransactionActive(true);
        TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        txObject.getConnectionHolder().getConnection().begin();
    } catch (Exception e) {
        release(txObject);
        throw new CannotCreateTransactionException(e.getMessage(), e);
    }
}

From source file:hsa.awp.common.util.OpenEntityManagerTimerTaskFactory.java

/**
 * Opens an {@link EntityManager} per execution.
 *//*from www  .ja v  a 2s  . c  o  m*/
private void openEntityManager() {

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

    log.trace("Binding EntityManager to thread '{}'", Thread.currentThread().getName());
    TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
}

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

/**
 * Set up hibernate session./*  w ww .  j a v  a  2 s  . c  o  m*/
 * @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.parancoe.web.PopulateInitialDataContextListener.java

@Override
public void contextInitialized(ServletContextEvent evt) {
    ctx = (ApplicationContext) evt.getServletContext()
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    Set<Class> fixtureClasses = new LinkedHashSet<Class>(getFixtureClasses());
    if (fixtureClasses.isEmpty()) {
        log.info("Skipping initial data population (no models)");
        return;//from   w w w  .  j  ava 2s  .c  o m
    }

    Map<Class, List> fixtures = YamlFixtureHelper.loadFixturesFromResource("initialData/", fixtureClasses);
    log.info("Populating initial data for models...");

    SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    //Attach transaction to thread
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    TransactionSynchronizationManager.initSynchronization();

    try {
        for (Class clazz : fixtures.keySet()) {
            List modelFixtures = fixtures.get(clazz);
            if (modelFixtures.isEmpty()) {
                log.warn("No data for {}, did you created the fixture file?",
                        YamlFixtureHelper.getModelName(clazz));
                continue;
            }
            populateTableForModel(clazz, modelFixtures);
        }
        fixtures.clear();
        log.info("Populating initial data for models done!");
        session.getTransaction().commit();
        if (session.isOpen()) {
            session.close();
        }
    } catch (Exception e) {
        log.error("Error while populating initial data for models {}", e.getMessage(), e);
        log.debug("Rolling back the populating database transaction");
        session.getTransaction().rollback();
    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (Exception e) {
            /*do nothing*/
        }
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        TransactionSynchronizationManager.clearSynchronization();
    }
}

From source file:org.ops4j.orient.spring.tx.OrientTransactionManager.java

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
    OrientTransaction tx = (OrientTransaction) transaction;

    ODatabaseInternal<?> db = tx.getDatabase();
    if (db == null || db.isClosed()) {
        db = dbf.openDatabase();/*  w ww  . jav a2  s. com*/
        tx.setDatabase(db);
        TransactionSynchronizationManager.bindResource(dbf, db);
    }
    log.debug("beginning transaction, db.hashCode() = {}", db.hashCode());
    db.begin();
}

From source file:org.tsm.concharto.OpenSessionInViewIntegrationTest.java

@Before
public void setupTransactionFactory() {
    ApplicationContext appCtx = ContextUtil.getCtx();
    if (null == sessionFactory) {
        sessionFactory = (SessionFactory) appCtx.getBean("mySessionFactory");
    }//from   w w w  .  jav a2s.co m
    AuditInterceptor auditInterceptor = (AuditInterceptor) appCtx.getBean("auditInterceptor");
    Session session = SessionFactoryUtils.getSession(sessionFactory, auditInterceptor, null);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

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

public PersistenceContext getApplicationScopedPersistenceContext() {
    if (this.appScopedEntityManager == null) {
        // Use the App scoped EntityManager if the user has provided it, and it is open.
        this.appScopedEntityManager = (EntityManager) this.env.get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
        if (this.appScopedEntityManager != null && !this.appScopedEntityManager.isOpen()) {
            throw new RuntimeException("Provided APP_SCOPED_ENTITY_MANAGER is not open");
        }//from   w w w.j a v  a2s . com

        if (this.appScopedEntityManager == null) {
            EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                    .getResource(this.emf);
            if (emHolder == null) {
                this.appScopedEntityManager = this.emf.createEntityManager();
                emHolder = new EntityManagerHolder(this.appScopedEntityManager);
                TransactionSynchronizationManager.bindResource(this.emf, emHolder);
                internalAppScopedEntityManager = true;
            } else {
                this.appScopedEntityManager = emHolder.getEntityManager();
            }

            this.env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER, emHolder.getEntityManager());
        }
    }
    if (TransactionSynchronizationManager.isActualTransactionActive()) {
        this.appScopedEntityManager.joinTransaction();
    }
    return new JpaPersistenceContext(this.appScopedEntityManager);
}

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;/*www  .java2 s .  c  om*/
    }
    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:org.codehaus.groovy.grails.plugins.acegi.GrailsWebApplicationObjectSupport.java

/**
 * set up hibernate session/*  w  w w.j  ava  2s  .c  om*/
 */
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:org.jasig.jpa.OpenEntityManagerAspect.java

@Around("anyPublicMethod() && @annotation(openEntityManager)")
public Object openEntityManager(ProceedingJoinPoint pjp, OpenEntityManager openEntityManager) throws Throwable {
    final EntityManagerFactory emf = getEntityManagerFactory(openEntityManager);

    EntityManager em = getTransactionalEntityManager(emf);
    boolean isNewEm = false;
    if (em == null) {
        logger.debug("Opening JPA EntityManager in OpenEntityManagerAspect");
        em = createEntityManager(emf);//ww  w  .  ja v  a  2  s  . c o m
        isNewEm = true;
        TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
    } else {
        logger.debug("Using Existing JPA EntityManager in OpenEntityManagerAspect");
    }
    try {
        return pjp.proceed();
    } finally {
        if (isNewEm) {
            logger.debug("Closing JPA EntityManager in OpenEntityManagerAspect");
            TransactionSynchronizationManager.unbindResource(emf);
            EntityManagerFactoryUtils.closeEntityManager(em);
        }
    }
}