Example usage for javax.transaction Status STATUS_ACTIVE

List of usage examples for javax.transaction Status STATUS_ACTIVE

Introduction

In this page you can find the example usage for javax.transaction Status STATUS_ACTIVE.

Prototype

int STATUS_ACTIVE

To view the source code for javax.transaction Status STATUS_ACTIVE.

Click Source Link

Document

A transaction is associated with the target object and it is in the active state.

Usage

From source file:org.springframework.jdbc.support.lob.LobCreatorUtils.java

/**
 * Register a transaction synchronization for closing the given LobCreator,
 * preferring Spring transaction synchronization and falling back to
 * plain JTA transaction synchronization.
 * @param lobCreator the LobCreator to close after transaction completion
 * @param jtaTransactionManager the JTA TransactionManager to fall back to
 * when no Spring transaction synchronization is active (may be {@code null})
 * @throws IllegalStateException if there is neither active Spring transaction
 * synchronization nor active JTA transaction synchronization
 *///  w w w  .j  av  a  2  s  . co  m
public static void registerTransactionSynchronization(LobCreator lobCreator,
        TransactionManager jtaTransactionManager) throws IllegalStateException {

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering Spring transaction synchronization for LobCreator");
        TransactionSynchronizationManager
                .registerSynchronization(new SpringLobCreatorSynchronization(lobCreator));
    } else {
        if (jtaTransactionManager != null) {
            try {
                int jtaStatus = jtaTransactionManager.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    logger.debug("Registering JTA transaction synchronization for LobCreator");
                    jtaTransactionManager.getTransaction()
                            .registerSynchronization(new JtaLobCreatorSynchronization(lobCreator));
                    return;
                }
            } catch (Throwable ex) {
                throw new TransactionSystemException(
                        "Could not register synchronization with JTA TransactionManager", ex);
            }
        }
        throw new IllegalStateException("Active Spring transaction synchronization or active "
                + "JTA transaction with specified [javax.transaction.TransactionManager] required");
    }
}

From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java

/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.//from  w  w w .j a va 2 s.com
 * @param sessionHolder the SessionHolder to check
 * @param sessionFactory the SessionFactory to get the JTA TransactionManager from
 * @param jdbcExceptionTranslator SQLExceptionTranslator to use for flushing the
 * Session on transaction synchronization (may be <code>null</code>)
 * @return the associated Session, if any
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 */
private static Session getJtaSynchronizedSession(SessionHolder sessionHolder, SessionFactory sessionFactory,
        SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
    if (jtaTm != null) {
        // Check whether JTA transaction management is active ->
        // fetch pre-bound Session for the current JTA transaction, if any.
        // (just necessary for JTA transaction suspension, with an individual
        // Hibernate Session per currently active/suspended transaction)
        try {
            // Look for transaction-specific Session.
            Transaction jtaTx = jtaTm.getTransaction();
            if (jtaTx != null) {
                int jtaStatus = jtaTx.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    Session session = sessionHolder.getValidatedSession(jtaTx);
                    if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
                        // No transaction-specific Session found: If not already marked as
                        // synchronized with transaction, register the default thread-bound
                        // Session as JTA-transactional. If there is no default Session,
                        // we're a new inner JTA transaction with an outer one being suspended:
                        // In that case, we'll return null to trigger opening of a new Session.
                        session = sessionHolder.getValidatedSession();
                        if (session != null) {
                            logger.debug(
                                    "Registering JTA transaction synchronization for existing Hibernate Session");
                            sessionHolder.addSession(jtaTx, session);
                            jtaTx.registerSynchronization(new JtaSessionSynchronization(
                                    new SpringSessionSynchronization(sessionHolder, sessionFactory,
                                            jdbcExceptionTranslator, false),
                                    jtaTm));
                            sessionHolder.setSynchronizedWithTransaction(true);
                            // Switch to FlushMode.AUTO if we're not within a read-only transaction.
                            FlushMode flushMode = session.getFlushMode();
                            if (FlushMode.NEVER.equals(flushMode)) {
                                session.setFlushMode(FlushMode.AUTO);
                                sessionHolder.setPreviousFlushMode(flushMode);
                            }
                        }
                    }
                    return session;
                }
            }
            // No transaction active -> simply return default thread-bound Session, if any
            // (possibly from OpenSessionInViewFilter/Interceptor).
            return sessionHolder.getValidatedSession();
        } catch (Throwable ex) {
            throw new DataAccessResourceFailureException("Could not check JTA transaction", ex);
        }
    } else {
        // No JTA TransactionManager -> simply return default thread-bound Session, if any
        // (possibly from OpenSessionInViewFilter/Interceptor).
        return sessionHolder.getValidatedSession();
    }
}

From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java

/**
 * Register a JTA synchronization for the given Session, if any.
 * @param sessionHolder the existing thread-bound SessionHolder, if any
 * @param session the Session to register
 * @param sessionFactory the SessionFactory that the Session was created with
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be <code>null</code>)
 *///from   w w  w.  j a  v  a 2  s.c o  m
private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory,
        SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session);
    if (jtaTm != null) {
        try {
            Transaction jtaTx = jtaTm.getTransaction();
            if (jtaTx != null) {
                int jtaStatus = jtaTx.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    logger.debug("Registering JTA transaction synchronization for new Hibernate Session");
                    SessionHolder holderToUse = sessionHolder;
                    // Register JTA Transaction with existing SessionHolder.
                    // Create a new SessionHolder if none existed before.
                    if (holderToUse == null) {
                        holderToUse = new SessionHolder(jtaTx, session);
                    } else {
                        holderToUse.addSession(jtaTx, session);
                    }
                    jtaTx.registerSynchronization(
                            new JtaSessionSynchronization(new SpringSessionSynchronization(holderToUse,
                                    sessionFactory, jdbcExceptionTranslator, true), jtaTm));
                    holderToUse.setSynchronizedWithTransaction(true);
                    if (holderToUse != sessionHolder) {
                        TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
                    }
                }
            }
        } catch (Throwable ex) {
            throw new DataAccessResourceFailureException(
                    "Could not register synchronization with JTA TransactionManager", ex);
        }
    }
}

From source file:org.springframework.orm.hibernate.support.AbstractLobType.java

/**
 * This implementation delegates to nullSafeSetInternal,
 * passing in a transaction-synchronized LobCreator for the
 * LobHandler of this type./*ww  w  .  j  av  a2 s . com*/
 * @see #nullSafeSetInternal
 */
public final void nullSafeSet(PreparedStatement st, Object value, int index)
        throws HibernateException, SQLException {

    if (this.lobHandler == null) {
        throw new IllegalStateException("No LobHandler found for configuration - "
                + "lobHandler property must be set on LocalSessionFactoryBean");
    }

    LobCreator lobCreator = this.lobHandler.getLobCreator();
    try {
        nullSafeSetInternal(st, index, value, lobCreator);
    } catch (IOException ex) {
        throw new HibernateException("I/O errors during LOB access", ex);
    }
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering Spring transaction synchronization for Hibernate LOB type");
        TransactionSynchronizationManager
                .registerSynchronization(new SpringLobCreatorSynchronization(lobCreator));
    } else {
        if (this.jtaTransactionManager != null) {
            try {
                int jtaStatus = this.jtaTransactionManager.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    logger.debug("Registering JTA transaction synchronization for Hibernate LOB type");
                    this.jtaTransactionManager.getTransaction()
                            .registerSynchronization(new JtaLobCreatorSynchronization(lobCreator));
                    return;
                }
            } catch (Exception ex) {
                throw new DataAccessResourceFailureException(
                        "Could not register synchronization with JTA TransactionManager", ex);
            }
        }
        throw new IllegalStateException("Active Spring transaction synchronization or active "
                + "JTA transaction with 'jtaTransactionManager' on LocalSessionFactoryBean required");
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java

/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization./* w  w w.j a v  a 2s.c  om*/
 * @param sessionHolder the SessionHolder to check
 * @param sessionFactory the SessionFactory to get the JTA TransactionManager from
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @return the associated Session, if any
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 */
private static Session getJtaSynchronizedSession(SessionHolder sessionHolder, SessionFactory sessionFactory,
        SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
    if (jtaTm != null) {
        // Check whether JTA transaction management is active ->
        // fetch pre-bound Session for the current JTA transaction, if any.
        // (just necessary for JTA transaction suspension, with an individual
        // Hibernate Session per currently active/suspended transaction)
        try {
            // Look for transaction-specific Session.
            Transaction jtaTx = jtaTm.getTransaction();
            if (jtaTx != null) {
                int jtaStatus = jtaTx.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    Session session = sessionHolder.getValidatedSession(jtaTx);
                    if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
                        // No transaction-specific Session found: If not already marked as
                        // synchronized with transaction, register the default thread-bound
                        // Session as JTA-transactional. If there is no default Session,
                        // we're a new inner JTA transaction with an outer one being suspended:
                        // In that case, we'll return null to trigger opening of a new Session.
                        session = sessionHolder.getValidatedSession();
                        if (session != null) {
                            logger.debug(
                                    "Registering JTA transaction synchronization for existing Hibernate Session");
                            sessionHolder.addSession(jtaTx, session);
                            jtaTx.registerSynchronization(new SpringJtaSynchronizationAdapter(
                                    new SpringSessionSynchronization(sessionHolder, sessionFactory,
                                            jdbcExceptionTranslator, false),
                                    jtaTm));
                            sessionHolder.setSynchronizedWithTransaction(true);
                            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
                            // with FlushMode.NEVER, which needs to allow flushing within the transaction.
                            FlushMode flushMode = session.getFlushMode();
                            if (flushMode.lessThan(FlushMode.COMMIT)) {
                                session.setFlushMode(FlushMode.AUTO);
                                sessionHolder.setPreviousFlushMode(flushMode);
                            }
                        }
                    }
                    return session;
                }
            }
            // No transaction active -> simply return default thread-bound Session, if any
            // (possibly from OpenSessionInViewFilter/Interceptor).
            return sessionHolder.getValidatedSession();
        } catch (Throwable ex) {
            throw new DataAccessResourceFailureException("Could not check JTA transaction", ex);
        }
    } else {
        // No JTA TransactionManager -> simply return default thread-bound Session, if any
        // (possibly from OpenSessionInViewFilter/Interceptor).
        return sessionHolder.getValidatedSession();
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java

/**
 * Register a JTA synchronization for the given Session, if any.
 * @param sessionHolder the existing thread-bound SessionHolder, if any
 * @param session the Session to register
 * @param sessionFactory the SessionFactory that the Session was created with
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 *///w  w w. j a va2 s.  c  o m
private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory,
        SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session);
    if (jtaTm != null) {
        try {
            Transaction jtaTx = jtaTm.getTransaction();
            if (jtaTx != null) {
                int jtaStatus = jtaTx.getStatus();
                if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
                    logger.debug("Registering JTA transaction synchronization for new Hibernate Session");
                    SessionHolder holderToUse = sessionHolder;
                    // Register JTA Transaction with existing SessionHolder.
                    // Create a new SessionHolder if none existed before.
                    if (holderToUse == null) {
                        holderToUse = new SessionHolder(jtaTx, session);
                    } else {
                        holderToUse.addSession(jtaTx, session);
                    }
                    jtaTx.registerSynchronization(
                            new SpringJtaSynchronizationAdapter(new SpringSessionSynchronization(holderToUse,
                                    sessionFactory, jdbcExceptionTranslator, true), jtaTm));
                    holderToUse.setSynchronizedWithTransaction(true);
                    if (holderToUse != sessionHolder) {
                        TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
                    }
                }
            }
        } catch (Throwable ex) {
            throw new DataAccessResourceFailureException(
                    "Could not register synchronization with JTA TransactionManager", ex);
        }
    }
}

From source file:org.springframework.orm.hibernate4.SpringSessionContext.java

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *//* w  w w.  j a va2  s  . com*/
@Override
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (!sessionHolder.isSynchronizedWithTransaction()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();
            if (flushMode.equals(FlushMode.MANUAL)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }

    if (this.transactionManager != null) {
        try {
            if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                Session session = this.jtaSessionContext.currentSession();
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager
                            .registerSynchronization(new SpringFlushSynchronization(session));
                }
                return session;
            }
        } catch (SystemException ex) {
            throw new HibernateException("JTA TransactionManager found but status check failed", ex);
        }
    }

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(
                new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

From source file:org.springframework.orm.hibernate5.SpringSessionContext.java

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///  ww  w.j  a v a 2s.  co  m
@Override
@SuppressWarnings("deprecation")
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (!sessionHolder.isSynchronizedWithTransaction()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
            if (flushMode.equals(FlushMode.MANUAL)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }

    if (this.transactionManager != null && this.jtaSessionContext != null) {
        try {
            if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                Session session = this.jtaSessionContext.currentSession();
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager
                            .registerSynchronization(new SpringFlushSynchronization(session));
                }
                return session;
            }
        } catch (SystemException ex) {
            throw new HibernateException("JTA TransactionManager found but status check failed", ex);
        }
    }

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(
                new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

From source file:org.tolven.web.servlet.InternalErrorHandleServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //check if a transaction is already started, if not redirect to the servlet
    UserTransaction ut = null;/* ww w .  j  ava 2  s.  c  om*/
    try {
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        if (ut.getStatus() != Status.STATUS_ACTIVE) {
            ut.begin();
        }
        //check if the error.email is configured. If found send an email
        Object accountUser = TolvenRequest.getInstance().getAccountUser();
        if (accountUser != null) {
            String errorEmail = ((AccountUser) accountUser).getAccount().getProperty()
                    .get("org.tolven.error.email.to");
            if (!StringUtils.isBlank(errorEmail)) {
                System.out.println("Send an email to " + errorEmail);
            }
        }
        if (ut != null) {
            ut.commit();
        }
        RequestDispatcher dispatcher = this.config.getServletContext().getRequestDispatcher("/error.jsp");
        if (dispatcher != null)
            dispatcher.forward(req, resp);
    } catch (Exception e) {
        throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
    } finally {
        if (ut != null) {
            try {
                ut.rollback();
            } catch (Exception e) {
                throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
            }
        }
    }
}

From source file:org.xchain.namespaces.jta.TransactionCommand.java

public boolean execute(JXPathContext context) throws Exception {
    boolean managingTransaction = false;
    boolean result = false;
    UserTransaction transaction = ContainerContext.getJtaLookupStrategy().getUserTransaction();

    if (transaction != null) {
        try {//from   w ww  .ja  v a  2s .c o m
            // if there is not a transaction running, then start one.
            if (Status.STATUS_ACTIVE != transaction.getStatus()) {
                managingTransaction = true;
                transaction.setTransactionTimeout(this.getTimeout(context));
                transaction.begin();
            }

            // put the transaction into the context.
            ((ScopedQNameVariables) context.getVariables()).declareVariable(getResult(context), transaction,
                    Scope.execution);

            // execute the chain 
            result = super.execute(context);

            // roll back the transaction.
            if (managingTransaction) {
                transaction.commit();
            }
        } catch (Exception e) {
            if (managingTransaction) {
                if (transaction.getStatus() != Status.STATUS_NO_TRANSACTION) {
                    transaction.rollback();
                }
            }
            throw e;
        } finally {
            // TODO: If we defined the transaction variable, then we should remove it.
        }
    } else {
        // TODO: Should this throw an IllegalStateException?  Returning true seems like the wrong behavior.
        result = true;
    }
    return result;
}