Example usage for javax.transaction TransactionManager getTransaction

List of usage examples for javax.transaction TransactionManager getTransaction

Introduction

In this page you can find the example usage for javax.transaction TransactionManager getTransaction.

Prototype

public Transaction getTransaction() throws SystemException;

Source Link

Document

Get the transaction object that represents the transaction context of the calling thread.

Usage

From source file:org.nuxeo.runtime.transaction.TransactionHelper.java

public static Transaction suspendTransaction() {
    TransactionManager tm = NuxeoContainer.getTransactionManager();
    if (tm == null) {
        return null;
    }/*from  w  ww . java  2s  .  com*/
    try {
        Transaction tx = tm.getTransaction();
        if (tx != null) {
            tx = tm.suspend();
        }
        return tx;
    } catch (SystemException e) {
        throw new TransactionRuntimeException("Cannot suspend tx", e);
    }
}

From source file:org.openejb.transaction.TxRequired.java

public InvocationResult invoke(Interceptor interceptor, EjbInvocation ejbInvocation,
        TransactionManager transactionManager) throws Throwable {
    Transaction transaction = transactionManager.getTransaction();
    if (transaction != null) {
        try {//from  w w  w.j a  v  a 2s  .c  o m
            return interceptor.invoke(ejbInvocation);
        } catch (Throwable t) {
            transactionManager.setRollbackOnly();
            if (ejbInvocation.getType().isLocal()) {
                throw new TransactionRolledbackLocalException().initCause(t);
            } else {
                // can't set an initCause on a TransactionRolledbackException
                throw new TransactionRolledbackException(t.getMessage());
            }
        }
    }

    transactionManager.begin();
    try {
        InvocationResult result = interceptor.invoke(ejbInvocation);
        return result;
    } catch (RollbackException re) {
        throw re;
    } catch (Throwable t) {
        try {
            transactionManager.setRollbackOnly();
        } catch (Exception e) {
            log.warn("Unable to roll back", e);
        }
        throw t;
    } finally {
        if (transactionManager.getStatus() == Status.STATUS_ACTIVE) {
            transactionManager.commit();
        } else {
            transactionManager.rollback();
        }
    }
}

From source file:org.quartz.impl.jdbcjobstore.JTANonClusteredSemaphore.java

/**
 * Helper method to get the current <code>{@link javax.transaction.Transaction}</code>
 * from the <code>{@link javax.transaction.TransactionManager}</code> in JNDI.
 * //from ww  w .  ja v a2s.  co  m
 * @return The current <code>{@link javax.transaction.Transaction}</code>, null if
 * not currently in a transaction.
 */
protected Transaction getTransaction() throws LockException {
    InitialContext ic = null;
    try {
        ic = new InitialContext();
        TransactionManager tm = (TransactionManager) ic.lookup(transactionManagerJNDIName);

        return tm.getTransaction();
    } catch (SystemException e) {
        throw new LockException("Failed to get Transaction from TransactionManager", e);
    } catch (NamingException e) {
        throw new LockException(
                "Failed to find TransactionManager in JNDI under name: " + transactionManagerJNDIName, e);
    } finally {
        if (ic != null) {
            try {
                ic.close();
            } catch (NamingException ignored) {
            }
        }
    }
}

From source file:org.sakaiproject.kernel.jcr.jackrabbit.sakai.SakaiXASessionImpl.java

/**
 * @param transactionManager/* w  w  w  . j  av  a  2 s  .com*/
 * @throws RepositoryException
 */
private void bind(TransactionManager transactionManager) throws RepositoryException {
    try {
        Transaction transaction = transactionManager.getTransaction();
        if (transaction != null) {
            transaction.enlistResource(getXAResource());
        }
    } catch (IllegalStateException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (RollbackException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (SystemException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (Exception e) {
        throw new RepositoryException(e.getMessage(), e);
    }
}

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
 *//*from  w  ww  . j a  va  2  s  . c  o 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  .  ja 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  .  jav 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.hibernate3.SessionFactoryUtils.java

/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.//from w ww .j  a va2s .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})
 *///from   w  w  w . j a v  a  2s. 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.topazproject.otm.impl.AbstractSession.java

private void ensureTxActive(boolean start, int txTimeout) throws OtmException {
    if (jtaTxn != null)
        return;/*www.j a  va 2  s  . c  o m*/

    try {
        TransactionManager tm = getSessionFactory().getTransactionManager();

        jtaTxn = tm.getTransaction();
        if (jtaTxn == null) {
            if (!start)
                throw new OtmException("No active transaction");

            tm.setTransactionTimeout(txTimeout > 0 ? txTimeout : 0);
            tm.begin();
            jtaTxn = tm.getTransaction();
        }

        jtaTxn.registerSynchronization(new Synchronization() {
            public void beforeCompletion() {
                if (getFlushMode().implies(FlushMode.commit) && !isRollback())
                    flush();
            }

            public void afterCompletion(int status) {
                endTransaction();
            }

            private boolean isRollback() throws OtmException {
                try {
                    return (jtaTxn.getStatus() == Status.STATUS_MARKED_ROLLBACK);
                } catch (Exception e) {
                    throw new OtmException("Error getting rollback-only status", e);
                }
            }
        });
    } catch (OtmException oe) {
        throw oe;
    } catch (Exception e) {
        throw new OtmException("Error setting up transaction", e);
    }
}