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.grails.orm.hibernate.GrailsSessionContext.java

protected void registerJtaSynchronization(Session session, 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(session);
    if (jtaTm == null) {
        return;/*from   www . j a v a  2 s  .c om*/
    }

    try {
        Transaction jtaTx = jtaTm.getTransaction();
        if (jtaTx == null) {
            return;
        }

        int jtaStatus = jtaTx.getStatus();
        if (jtaStatus != Status.STATUS_ACTIVE && jtaStatus != Status.STATUS_MARKED_ROLLBACK) {
            return;
        }

        LOG.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(session);
        } else {
            // it's up to the caller to manage concurrent sessions
            // holderToUse.addSession(session);
        }
        jtaTx.registerSynchronization(
                new SpringJtaSynchronizationAdapter(createSpringSessionSynchronization(holderToUse), 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.enhydra.jdbc.pool.StandardXAPoolDataSource.java

/**
 * Invoked when the application calls close()
 * on its representation of the connection
 *//*from w  w  w  . j ava 2s.co  m*/
public void connectionClosed(ConnectionEvent event) {
    Object obj = event.getSource();
    log.debug("StandardXAPoolDataSource:connectionClosed");
    XAConnection xac = (XAConnection) obj; // cast it into an xaConnection

    Transaction tx = null;
    try {
        if (transactionManager == null) {
            TransactionManager tm = ((StandardXADataSource) xads).getTransactionManager();
            if (tm == null) {
                throw new NullPointerException("TM is null");
            } else
                // here we use tm instead to setup transactionManager = tm
                // if the current transactionManager property is null, it stays
                // there, and we continue to use the TM from the XADataSource
                tx = tm.getTransaction();
        } else {
            tx = transactionManager.getTransaction();
        }
        log.debug("StandardXAPoolDataSource:connectionClosed get a transaction");
    } catch (NullPointerException n) {
        // current is null: we are not in EJBServer.
        log.error("StandardXAPoolDataSource:connectionClosed should not be used outside an EJBServer");
    } catch (SystemException e) {
        log.error("StandardXAPoolDataSource:connectionClosed getTransaction failed:" + e);
    }

    // delist Resource if in transaction
    // We must keep the connection till commit or rollback
    if ((tx != null) && (((StandardXAConnection) xac).connectionHandle.isReallyUsed)) {
        try {
            tx.delistResource(xac.getXAResource(), XAResource.TMSUCCESS);
            // delist the xaResource
            log.debug("StandardXAPoolDataSource:connectionClosed the resourse is delisted");
        } catch (Exception e) {
            log.error("StandardXAPoolDataSource:connectionClosed Exception in connectionClosed:" + e);
        }
    }
    log.debug("StandardXAPoolDataSource:connectionClosed checkIn an object to the pool");
    pool.checkIn(obj); // return the connection to the pool
}

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

public void testSyncReplWithModficationsOnBothCachesWithRollback() throws Exception {
    TransactionManager tm;
    final Fqn fqn1 = Fqn.fromString("/one/two/three");
    final Fqn fqn2 = Fqn.fromString("/eins/zwei/drei");

    cache1.getConfiguration().setSyncRollbackPhase(true);
    cache2.getConfiguration().setSyncRollbackPhase(true);

    tm = beginTransaction();//from   w  ww . jav  a  2  s  . c  o m
    cache1.put(fqn1, "age", 38);
    cache2.put(fqn2, "age", 39);

    // this will rollback the transaction
    Transaction tx = tm.getTransaction();
    tx.registerSynchronization(new TransactionAborter(tx));

    try {
        tm.commit();
        fail("commit should throw a RollbackException, we should not get here");
    } catch (RollbackException rollback) {
    }

    assertEquals(0, cache1.getNumberOfLocksHeld());
    assertEquals(0, cache2.getNumberOfLocksHeld());

    assertEquals(0, cache1.getNumberOfNodes());
    assertEquals(0, cache2.getNumberOfNodes());
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception, ContextException {
    TransactionManager txm = _txm;
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }// w  ww.j av  a2 s  . c  om

    // The value of the timeout is in seconds. If the value is zero, the transaction service restores the default value.
    if (timeout < 0) {
        throw new IllegalArgumentException("Timeout must be positive, received: " + timeout);
    }

    boolean existingTransaction = false;
    try {
        existingTransaction = txm.getTransaction() != null;
    } catch (Exception ex) {
        String errmsg = "Internal Error, could not get current transaction.";
        throw new ContextException(errmsg, ex);
    }

    // already in transaction, execute and return directly
    if (existingTransaction) {
        return transaction.call();
    }

    // run in new transaction
    Exception ex = null;
    int immediateRetryCount = _immediateTransactionRetryLimit;

    _txm.setTransactionTimeout(timeout);
    if (__log.isDebugEnabled() && timeout != 0)
        __log.debug("Custom transaction timeout: " + timeout);
    try {
        do {
            try {
                if (__log.isDebugEnabled())
                    __log.debug("Beginning a new transaction");
                txm.begin();
            } catch (Exception e) {
                String errmsg = "Internal Error, could not begin transaction.";
                throw new ContextException(errmsg, e);
            }

            try {
                ex = null;
                return transaction.call();
            } catch (Exception e) {
                ex = e;
            } finally {
                if (ex == null) {
                    if (__log.isDebugEnabled())
                        __log.debug("Commiting on " + txm + "...");
                    try {
                        txm.commit();
                    } catch (Exception e2) {
                        ex = e2;
                    }
                } else {
                    if (__log.isDebugEnabled())
                        __log.debug("Rollbacking on " + txm + "...");
                    txm.rollback();
                }

                if (ex != null && immediateRetryCount > 0) {
                    if (__log.isDebugEnabled())
                        __log.debug("Will retry the transaction in " + _immediateTransactionRetryInterval
                                + " msecs on " + _txm + " for error: ", ex);
                    Thread.sleep(_immediateTransactionRetryInterval);
                }
            }
        } while (immediateRetryCount-- > 0);
    } finally {
        // 0 restores the default value
        _txm.setTransactionTimeout(0);
    }

    throw ex;
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public void registerSynchronizer(final Synchronizer synch) throws ContextException {
    TransactionManager txm = _txm;
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }/*from   ww  w  . j  a v a  2  s.  co  m*/

    try {
        txm.getTransaction().registerSynchronization(new Synchronization() {

            public void beforeCompletion() {
                synch.beforeCompletion();
            }

            public void afterCompletion(int status) {
                synch.afterCompletion(status == Status.STATUS_COMMITTED);
            }

        });
    } catch (Exception e) {
        throw new ContextException("Unable to register synchronizer.", e);
    }
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public boolean isTransacted() {
    TransactionManager txm = _txm;
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }/*from  ww w .ja v a  2 s.c o  m*/

    try {
        Transaction tx = txm.getTransaction();
        return (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION);
    } catch (SystemException e) {
        throw new ContextException("Internal Error: Could not obtain transaction status.");
    }
}

From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java

public static void enlistResource(XAResource resource) throws GenericTransactionException {
    if (resource == null) {
        return;// ww w .java  2s.c  o m
    }

    try {
        TransactionManager tm = TransactionFactoryLoader.getInstance().getTransactionManager();
        if (tm != null && tm.getStatus() == STATUS_ACTIVE) {
            Transaction tx = tm.getTransaction();
            if (tx != null) {
                tx.enlistResource(resource);
            }
        }
    } catch (RollbackException e) {
        //This is Java 1.4 only, but useful for certain debuggins: Throwable t = e.getCause() == null ? e : e.getCause();
        throw new GenericTransactionException(
                "Roll Back error, could not enlist resource in transaction even though transactions are available, current transaction rolled back",
                e);
    } catch (SystemException e) {
        //This is Java 1.4 only, but useful for certain debuggins: Throwable t = e.getCause() == null ? e : e.getCause();
        throw new GenericTransactionException(
                "System error, could not enlist resource in transaction even though transactions are available",
                e);
    }
}

From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java

public static void registerSynchronization(Synchronization sync) throws GenericTransactionException {
    if (sync == null) {
        return;//from   w  w  w .j  a  v  a  2 s .c o  m
    }

    try {
        TransactionManager tm = TransactionFactoryLoader.getInstance().getTransactionManager();
        if (tm != null && tm.getStatus() == STATUS_ACTIVE) {
            Transaction tx = tm.getTransaction();
            if (tx != null) {
                tx.registerSynchronization(sync);
            }
        }
    } catch (RollbackException e) {
        throw new GenericTransactionException(
                "Roll Back error, could not register synchronization in transaction even though transactions are available, current transaction rolled back",
                e);
    } catch (SystemException e) {
        throw new GenericTransactionException(
                "System error, could not register synchronization in transaction even though transactions are available",
                e);
    }
}

From source file:org.apache.openjpa.kernel.AbstractBrokerFactory.java

/**
 * Synchronize the given broker with a managed transaction,
 * optionally starting one if none is in progress.
 *
 * @return true if synched with transaction, false otherwise
 *///  w w  w. j ava 2  s.c  o m
boolean syncWithManagedTransaction(BrokerImpl broker, boolean begin) {
    Transaction trans;
    try {
        ManagedRuntime mr = broker.getManagedRuntime();
        TransactionManager tm = mr.getTransactionManager();
        if (tm == null) {
            throw new InternalException(_loc.get("null-transactionmanager", mr));
        }
        trans = tm.getTransaction();
        if (trans != null && (trans.getStatus() == Status.STATUS_NO_TRANSACTION
                || trans.getStatus() == Status.STATUS_UNKNOWN))
            trans = null;

        if (trans == null && begin) {
            tm.begin();
            trans = tm.getTransaction();
        } else if (trans == null)
            return false;

        // synch broker and trans
        trans.registerSynchronization(broker);

        // we don't need to synchronize on brokers or guard against multiple
        // threads using the same trans since one JTA transaction can never
        // be active on multiple concurrent threads.
        Object txKey = mr.getTransactionKey();
        Collection<Broker> brokers = _transactional.get(txKey);

        if (brokers == null) {
            brokers = new ArrayList<Broker>(2);
            _transactional.put(txKey, brokers);
            trans.registerSynchronization(new RemoveTransactionSync(txKey));
        }
        brokers.add(broker);

        return true;
    } catch (OpenJPAException ke) {
        throw ke;
    } catch (Exception e) {
        throw new GeneralException(e);
    }
}

From source file:org.apache.synapse.commons.transaction.TranscationManger.java

public static void beginTransaction() throws Exception {
    long key = Thread.currentThread().getId();
    try {/* w  ww  .  j  av  a  2  s .  com*/
        if (log.isDebugEnabled()) {
            log.debug("beginTransaction()");
        }

        TransactionManager txMgr = txManagers.get().get(key);
        txMgr.begin();
        Transaction tx = txMgr.getTransaction();
        transactions.get().put(key, tx);
        log.debug(" BEGIN  : " + transactions.get().get(key).getStatus());

    } catch (Exception ex) {
        log.debug(" BEGIN ERROR  : " + txManagers.get().get(key).getStatus());
        throw ex;
    }

}