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

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

Introduction

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

Prototype

public static Object unbindResource(Object key) throws IllegalStateException 

Source Link

Document

Unbind a resource for the given key from the current thread.

Usage

From source file:org.parancoe.web.ParancoeOpenSessionInViewInterceptor.java

@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex)
        throws Exception {
    Session session = sessionFactory.getCurrentSession();
    try {/*w w w.  j av a  2  s.  co m*/
        if (ex == null) {
            logger.debug("Committing the database transaction");
            if (session.getTransaction().isActive() && !session.getTransaction().wasRolledBack()) {
                session.getTransaction().commit();
            }
        } else {
            logger.error("Error occurrend in request handling", ex);
            logger.debug("Rolling back the database transaction");
            if (session.getTransaction().isActive() && !session.getTransaction().wasRolledBack()) {
                session.getTransaction().rollback();
            }
        }
        if (session.isOpen()) {
            session.close();
        }
    } catch (Exception e) {
        logger.error("Error occurrend in request completion", ex);
        throw e;
    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (Exception e) {/*do nothing*/

        }
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        TransactionSynchronizationManager.clearSynchronization();
    }
}

From source file:ch.algotrader.dao.AbstractDaoTest.java

@After
public void cleanup() throws Exception {

    if (this.session != null) {

        this.session.close();

        ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
        dbPopulator.addScript(new ByteArrayResource("TRUNCATE TABLE GenericItem".getBytes(Charsets.US_ASCII)));

        DatabasePopulatorUtils.execute(dbPopulator, DATABASE.getDataSource());
        TransactionSynchronizationManager.unbindResource(DATABASE.getSessionFactory());
    }/*from w w w .  j  a v a 2 s . c o  m*/
}

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  ww. j av a  2  s  .  com*/
    }
    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.springextensions.neodatis.NeoDatisTransactionManager.java

@Override
protected Object doSuspend(Object transaction) throws TransactionException {
    NeoDatisTransactionObject transactionObject = (NeoDatisTransactionObject) transaction;
    transactionObject.setODBHolder(null);
    ODBHolder odbHolder = (ODBHolder) TransactionSynchronizationManager.unbindResource(getOdb());
    return new SuspendedResourcesHolder(odbHolder);
}

From source file:org.openplans.delayfeeder.RouteStatus.java

/**
 * Main entry point for the route status server
 *///w  w w  .  j ava2  s. c  om
@GET
@Produces("application/x-javascript")
public JSONWithPadding getStatus(@QueryParam("route") List<String> routes,
        @QueryParam("callback") String callback) {

    RouteStatusResponse response = new RouteStatusResponse();

    try {
        Session session = sessionFactory.getCurrentSession();
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));

        session.beginTransaction();

        response.items = new ArrayList<RouteStatusItem>(routes.size());
        for (String routeId : routes) {
            String[] parts = routeId.split(",");

            if (parts.length != 2)
                continue;

            String agency = parts[0];
            String route = parts[1];

            if (agency == null || route == null)
                continue;

            /* get data from cache */
            RouteFeedItem item = getLatestItem(agency, route, session);
            RouteStatusItem status = new RouteStatusItem();
            response.items.add(status);

            /* serve data */
            status.agency = agency;
            status.route = route;
            if (item != null) {
                status.status = item.title;
                status.date = item.date;
                status.link = item.link;
                status.category = item.category;
            }
        }

        session.flush();
        session.getTransaction().commit();
    } finally {
        TransactionSynchronizationManager.unbindResource(sessionFactory);
    }

    return new JSONWithPadding(response, callback);
}

From source file:hr.fer.zemris.vhdllab.dao.impl.support.AbstractDaoSupport.java

protected void closeEntityManager() {
    if (entityManager != null) {
        entityManager.close();/*from  www .j  a  va2  s.  c  o  m*/
        TransactionSynchronizationManager.unbindResource(entityManagerFactory);
        entityManager = null;
    }
}

From source file:org.inbio.m3s.service.AbstractServiceTest.java

/**
 * One time teardown which closes the session opened for the tests.
 *///from   w  w w .  j a  v  a  2s.  c o  m
protected void onTearDown() throws Exception {
    //logger.trace("onTearDown(): entered method.");
    super.onTearDown();

    SessionFactory sessionFactory = (SessionFactory) getBean("sessionFactory");
    SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    Session session = holder.getSession();
    if (session.isOpen()) {
        if (session.isDirty()) {
            session.flush();
        }
        session.close();
    }
    if (session.isConnected()) {
        session.connection().close();
    }
    holder.removeSession(session);
    TransactionSynchronizationManager.unbindResource(sessionFactory);
}

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

@Override
protected void doCleanupAfterCompletion(Object transaction) {
    OrientTransaction tx = (OrientTransaction) transaction;
    if (!tx.getDatabase().isClosed()) {
        tx.getDatabase().close();//w ww.  ja  v a  2  s. co m
    }
    TransactionSynchronizationManager.unbindResource(dbf);
}

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;/*  www  .jav  a  2  s.  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:com.mobileman.projecth.TestCaseBase.java

/**
 * @throws Exception/*from w w  w .  ja  v  a2  s.  c  om*/
 */
@After
public void tearDown() throws Exception {
    if (sessionOwner && session != null) {
        SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
        Session s = holder.getSession();
        s.flush();
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        SessionFactoryUtils.closeSession(s);
    }

    if (wiser != null) {
        wiser.stop();
    }
}