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:nl.strohalm.cyclos.struts.CyclosRequestProcessor.java

private void commitOrRollbackTransaction(final HttpServletRequest request)
        throws IOException, ServletException {
    if (noTransaction(request)) {
        return;// w w  w.  j a  v a  2  s  . co  m
    }
    final ExecutionResult result = (ExecutionResult) request.getAttribute(EXECUTION_RESULT_KEY);
    final SessionHolder sessionHolder = getSessionHolder();
    // Commit or rollback the transaction
    boolean runCommitListeners = false;
    boolean lockingException = false;
    if (result.commit) {
        logDebug(request, "Committing transaction");
        runCommitListeners = true; // Marked as commit - should run commit listeners
        try {
            sessionHolder.getTransaction().commit();
        } catch (final Throwable t) {
            // In case of locking exceptions, we must make sure the correct exception type is returned, so the transaction will be retried
            lockingException = ExceptionHelper.isLockingException(t);
            result.error = t;
        }
    } else {
        if (result.error == null && !result.hasWrite) {
            // Transaction was semantically a commit, so, the commit listeners should run.
            // However, as there where no writes the transaction will be rolled back
            runCommitListeners = true;
            logDebug(request, "Nothing written to database. Rolling-back transaction");
        } else {
            logDebug(request, "Rolling-back transaction");
        }
        sessionHolder.getTransaction().rollback();
    }

    // Disconnect the session
    sessionHolder.getSession().disconnect();

    if (lockingException) {
        // There was a locking exception - throw it now, so the transaction will be retried
        cleanUpTransaction(request);
        throw new LockingException();
    }

    // Unbind the session holder, so that listeners which should open a new transaction on this same thread won't be messed up
    TransactionSynchronizationManager.unbindResourceIfPossible(sessionFactory);

    // Run the transaction listener
    CurrentTransactionData.detachListeners().runListeners(runCommitListeners);

    // Bind the session holder again
    TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);

    // Log the execution if a regular user is logged in and this is not an AJAX request
    if (result.traceLog) {
        traceLog(request, result.error, result.commit);
    }

    // The resulting error was not silenced (i.e, by the BaseAction's try / catch. Log and rethrow
    if (result.error != null && !result.errorWasSilenced) {
        actionHelper.generateLog(request, servlet.getServletContext(), result.error);
        ActionHelper.throwException(result.error);
    }
}

From source file:nl.strohalm.cyclos.struts.CyclosRequestProcessor.java

private void openReadWriteConnection(final HttpServletRequest request) throws IOException, ServletException {
    if (noTransaction(request)) {
        return;/*  w ww  .  j a v  a 2 s .co m*/
    }
    logDebug(request, "Opening a new read-write transaction");
    // Open a read-write transaction
    Connection connection = null;
    Session session = null;
    SessionHolder holder = null;
    Transaction transaction = null;
    try {
        connection = connectionProvider.getConnection();
        TransactionSynchronizationManager.bindResource(connectionProvider, connection);
        session = sessionFactory.openSession(connection);
        holder = new SessionHolder(session);
        transaction = session.beginTransaction();
        holder.setTransaction(transaction);
        TransactionSynchronizationManager.bindResource(sessionFactory, holder);
        holder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.setActualTransactionActive(true);
        TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
    } catch (final Exception e) {
        if (connection != null) {
            try {
                connectionProvider.closeConnection(connection);
            } catch (final SQLException e1) {
                LOG.warn("Error closing connection", e1);
            } finally {
                TransactionSynchronizationManager.unbindResourceIfPossible(connectionProvider);
                TransactionSynchronizationManager.unbindResourceIfPossible(sessionFactory);
            }
        }
        LOG.error("Couldn't open a transaction", e);
        ActionHelper.throwException(e);
    }
}

From source file:no.abmu.finances.domain.AbstractLocalHibernate3Test.java

protected void setUp() throws Exception {
    AnnotationConfiguration configuration = new AnnotationConfiguration();
    configuration.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver");
    configuration.setProperty(Environment.URL, "jdbc:hsqldb:mem:financeH3");
    configuration.setProperty(Environment.USER, "sa");
    configuration.setProperty(Environment.DIALECT, HSQLDialect.class.getName());
    configuration.setProperty(Environment.SHOW_SQL, "false");
    configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    configuration.setProperty(Environment.STATEMENT_BATCH_SIZE, "0");
    configuration.setProperty("hibernate.cache.use_second_level_cache", "false");

    configuration.addClass(ReportSchema.class);

    configuration.addClass(Account.class);
    configuration.addClass(Post.class);
    configuration.addClass(PostPeriod.class);
    configuration.addClass(PostType.class);
    configuration.addClass(PostValidator.class);

    configuration.addClass(ReportData.class);
    configuration.addClass(PostData.class);
    configuration.addClass(SubReportDataList.class);

    configuration.addClass(AccountOrgUnitMapping.class);
    configuration.addClass(ReportDataOrgUnitMapping.class);

    configuration.addAnnotatedClass(ContactRole.class);
    configuration.addAnnotatedClass(CountryName.class);
    configuration.addAnnotatedClass(OrganisationName.class);
    configuration.addAnnotatedClass(OrganisationRelationRole.class);
    configuration.addAnnotatedClass(OrganisationTypeName.class);
    configuration.addAnnotatedClass(POBoxAddress.class);
    configuration.addAnnotatedClass(StreetAddress.class);
    configuration.addAnnotatedClass(ExtendedContactPerson.class);
    configuration.addAnnotatedClass(BankAccountNumber.class);
    configuration.addAnnotatedClass(ContactPerson.class);
    configuration.addAnnotatedClass(EmailAddress.class);
    configuration.addAnnotatedClass(FaxNumber.class);
    configuration.addAnnotatedClass(TelephoneNumber.class);
    configuration.addAnnotatedClass(WebAddress.class);
    configuration.addAnnotatedClass(Muncipality.class);
    configuration.addAnnotatedClass(Country.class);
    configuration.addAnnotatedClass(MuncipalityRelation.class);
    configuration.addAnnotatedClass(OrganisationType.class);
    configuration.addAnnotatedClass(OrganisationTypeRelation.class);
    configuration.addAnnotatedClass(ContactRelation.class);
    configuration.addAnnotatedClass(OrganisationRelation.class);
    configuration.addAnnotatedClass(OrganisationUnit.class);

    String[] arr = configuration.generateSchemaCreationScript(new HSQLDialect());

    sessionFactory = configuration.buildSessionFactory();
    session = sessionFactory.openSession();
    session2 = sessionFactory.openSession();

    this.session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

From source file:no.abmu.finances.domain.AbstractLocalTest.java

protected void setUp() throws Exception {
    AnnotationConfiguration configuration = new AnnotationConfiguration();
    configuration.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver");
    configuration.setProperty(Environment.URL, "jdbc:hsqldb:mem:.");
    configuration.setProperty(Environment.USER, "sa");
    configuration.setProperty(Environment.DIALECT, HSQLDialect.class.getName());
    configuration.setProperty(Environment.SHOW_SQL, "false");
    configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    configuration.setProperty(Environment.STATEMENT_BATCH_SIZE, "0");
    configuration.setProperty("hibernate.cache.use_second_level_cache", "false");

    configuration.addClass(ReportSchema.class);

    configuration.addClass(Account.class);
    configuration.addClass(Post.class);
    configuration.addClass(PostPeriod.class);
    configuration.addClass(PostType.class);
    configuration.addClass(PostValidator.class);

    configuration.addClass(ReportData.class);
    configuration.addClass(PostData.class);
    configuration.addClass(SubReportDataList.class);

    configuration.addClass(AccountOrgUnitMapping.class);
    configuration.addClass(ReportDataOrgUnitMapping.class);

    configuration.addAnnotatedClass(ContactRole.class);
    configuration.addAnnotatedClass(CountryName.class);
    configuration.addAnnotatedClass(OrganisationName.class);
    configuration.addAnnotatedClass(OrganisationRelationRole.class);
    configuration.addAnnotatedClass(OrganisationTypeName.class);
    configuration.addAnnotatedClass(POBoxAddress.class);
    configuration.addAnnotatedClass(StreetAddress.class);
    configuration.addAnnotatedClass(ExtendedContactPerson.class);
    configuration.addAnnotatedClass(BankAccountNumber.class);
    configuration.addAnnotatedClass(ContactPerson.class);
    configuration.addAnnotatedClass(EmailAddress.class);
    configuration.addAnnotatedClass(FaxNumber.class);
    configuration.addAnnotatedClass(TelephoneNumber.class);
    configuration.addAnnotatedClass(WebAddress.class);
    configuration.addAnnotatedClass(Muncipality.class);
    configuration.addAnnotatedClass(Country.class);
    configuration.addAnnotatedClass(MuncipalityRelation.class);
    configuration.addAnnotatedClass(OrganisationType.class);
    configuration.addAnnotatedClass(OrganisationTypeRelation.class);
    configuration.addAnnotatedClass(ContactRelation.class);
    configuration.addAnnotatedClass(OrganisationRelation.class);
    configuration.addAnnotatedClass(OrganisationUnit.class);

    String[] arr = configuration.generateSchemaCreationScript(new HSQLDialect());

    sessionFactory = configuration.buildSessionFactory();
    session = sessionFactory.openSession();
    session2 = sessionFactory.openSession();

    this.session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

From source file:no.abmu.test.domainmodels.hibernate3.AbstractCommonHibernate3Tester.java

protected void setUp() throws Exception {
    session = sessionFactory.openSession();
    session2 = sessionFactory.openSession();

    session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

From source file:ome.tools.hibernate.SessionStatus.java

private void bindSession(Session session) {
    debug("Binding session to thread.");
    SessionHolder sessionHolder = new SessionHolder(session);
    sessionHolder.setTransaction(sessionHolder.getSession().beginTransaction()); // FIXME TODO
    // If we reach this point, it's ok to bind the new SessionHolder,
    // however the DUMMY EmptySessionHolder may be present so unbind
    // just in case.
    if (TransactionSynchronizationManager.hasResource(factory)) {
        TransactionSynchronizationManager.unbindResource(factory);
    }//from  w  w  w. j  a  va2s .  co  m
    TransactionSynchronizationManager.bindResource(factory, sessionHolder);
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new InternalException("Synchronization not active for " + "TransactionSynchronizationManager");
    }
}

From source file:ome.tools.hibernate.SessionStatus.java

private void resetThreadSession() {
    if (isSessionBoundToThread()) {
        debug("Session bound to thread. Reseting.");
        TransactionSynchronizationManager.unbindResource(factory);
        TransactionSynchronizationManager.bindResource(factory, DUMMY);
    } else {//  w  w  w  .  j  a v  a 2 s . c om
        debug("Session not bound to thread. No need to reset.");
    }
}

From source file:org.broadleafcommerce.common.util.tenant.IdentityExecutionUtils.java

private static void finalizeTransaction(PlatformTransactionManager transactionManager,
        TransactionContainer container, boolean error) {
    TransactionUtils.finalizeTransaction(container.status, transactionManager, error);
    for (Map.Entry<Object, Object> entry : container.usedResources.entrySet()) {
        if (!TransactionSynchronizationManager.hasResource(entry.getKey())) {
            TransactionSynchronizationManager.bindResource(entry.getKey(), entry.getValue());
        }/*from w  ww  . j  a  v  a 2s .c  o  m*/
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor.java

public void init() {
    if (incNestingCount() > 1) {
        return;//from w  w  w. j  a v  a 2s .  co  m
    }
    SessionFactory sf = getSessionFactory();
    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();
        GrailsHibernateUtil.enableDynamicFilterEnablerIfPresent(sf, session);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}

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

public void init() {
    if (incNestingCount() > 1) {
        return;/* w  w  w . j av  a2 s.c  om*/
    }
    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();
        GrailsHibernateUtil.enableDynamicFilterEnablerIfPresent(sf, session);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}