Search in sources :

Example 36 with Transaction

use of javax.transaction.Transaction in project Activiti by Activiti.

the class JtaTransactionInterceptor method execute.

public <T> T execute(CommandConfig config, Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());
    if (config.getTransactionPropagation() == TransactionPropagation.NOT_SUPPORTED) {
        return next.execute(config, command);
    }
    boolean requiresNew = config.getTransactionPropagation() == TransactionPropagation.REQUIRES_NEW;
    Transaction oldTx = null;
    try {
        boolean existing = isExisting();
        boolean isNew = !existing || requiresNew;
        if (existing && requiresNew) {
            oldTx = doSuspend();
        }
        if (isNew) {
            doBegin();
        }
        T result;
        try {
            result = next.execute(config, command);
        } catch (RuntimeException ex) {
            doRollback(isNew, ex);
            throw ex;
        } catch (Error err) {
            doRollback(isNew, err);
            throw err;
        } catch (Exception ex) {
            doRollback(isNew, ex);
            throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
        }
        if (isNew) {
            doCommit();
        }
        return result;
    } finally {
        doResume(oldTx);
    }
}
Also used : Transaction(javax.transaction.Transaction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) InvalidTransactionException(javax.transaction.InvalidTransactionException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException)

Example 37 with Transaction

use of javax.transaction.Transaction in project aries by apache.

the class TranStrategyTest method testMandatoryBegin.

@Test
public void testMandatoryBegin() throws Exception {
    // MANDATORY strategy should throw IllegalStateException when tran manager 
    // status is Status.STATUS_NO_TRANSACTION it should not return null.
    expect(tm.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION);
    try {
        assertNotNull("TransactionStrategy.MANDATORY.begin(tm) returned null when manager " + "status is STATUS_NO_TRANSACTION", TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction());
    } catch (IllegalStateException ise) {
    // Expected to be in here
    } catch (Exception e) {
        fail("TransactionStrategy.MANDATORY.begin() threw an unexpected exception when tran manager status is STATUS_NO_TRANSACTION");
    }
    // MANDATORY strategy should return null for all tran manager states other
    // than Status.STATUS_NO_TRANSACTION.
    int[] invalids = new int[] { Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK, Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK, Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
    for (int i = 0; i < invalids.length; i++) {
        c.reset();
        expect(tm.getStatus()).andReturn(invalids[i]);
        expect(tm.getTransaction()).andReturn(null);
        c.replay();
        try {
            Transaction tran = TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction();
            assertNull("TransactionStrategy.MANDATORY.begin() did not return null when manager status value is " + invalids[i], tran);
        } catch (Exception ise) {
            fail("TransactionStrategy.MANDATORY.begin() threw Exception when manager status value is " + invalids[i]);
        }
        c.verify();
    }
}
Also used : Transaction(javax.transaction.Transaction) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) Test(org.junit.Test)

Example 38 with Transaction

use of javax.transaction.Transaction in project geode by apache.

the class FacetsJCAConnectionManagerImpl method connectionErrorOccurred.

/**
   * CallBack for Connection Error.
   * 
   * @param event ConnectionEvent
   */
public void connectionErrorOccurred(ConnectionEvent event) {
    if (isActive) {
        // If its an XAConnection
        ManagedConnection conn = (ManagedConnection) event.getSource();
        // XAResource xar = (XAResource) xaResourcesMap.get(conn);
        ((List) xalistThreadLocal.get()).remove(conn);
        TransactionManagerImpl transManager = TransactionManagerImpl.getTransactionManager();
        try {
            Transaction txn = transManager.getTransaction();
            if (txn == null) {
                mannPoolCache.returnPooledConnectionToPool(conn);
            } else {
            // do nothing.
            }
        } catch (Exception se) {
            se.printStackTrace();
        }
        try {
            mannPoolCache.expirePooledConnection(conn);
        // mannPoolCache.destroyPooledConnection(conn);
        } catch (Exception ex) {
            String exception = "FacetsJCAConnectionManagerImpl::connectionErrorOccurred: Exception occurred due to " + ex.getMessage();
            if (logger.isDebugEnabled()) {
                logger.debug(exception, ex);
            }
        }
    }
}
Also used : Transaction(javax.transaction.Transaction) TransactionManagerImpl(org.apache.geode.internal.jta.TransactionManagerImpl) ManagedConnection(javax.resource.spi.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List) ResourceException(javax.resource.ResourceException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException)

Example 39 with Transaction

use of javax.transaction.Transaction in project geode by apache.

the class JCAConnectionManagerImpl method allocateConnection.

/*
   * allocates a ManagedConnection from the ConnectionPool or creates a new
   * ManagedConnection. @param javax.resource.spi.ManagedConnectionFactory
   * 
   * @param javax.resource.spi.ConnectionRequestInfo
   * 
   * @throws ResourceException
   */
public Object allocateConnection(ManagedConnectionFactory mcf, ConnectionRequestInfo reqInfo) throws ResourceException {
    if (!isActive) {
        throw new ResourceException(LocalizedStrings.JCAConnectionManagerImpl_JCACONNECTIONMANAGERIMPLALLOCATECONNECTIONNO_VALID_CONNECTION_AVAILABLE.toLocalizedString());
    }
    ManagedConnection conn = null;
    try {
        conn = (ManagedConnection) mannPoolCache.getPooledConnectionFromPool();
    } catch (PoolException ex) {
        // ex.printStackTrace();
        throw new ResourceException(LocalizedStrings.JCAConnectionManagerImpl_JCACONNECTIONMANAGERIMPL_ALLOCATECONNECTION_IN_GETTING_CONNECTION_FROM_POOL_DUE_TO_0.toLocalizedString(ex.getMessage()), ex);
    }
    // Transaction Manager.
    try {
        synchronized (this) {
            if (transManager == null) {
                transManager = JNDIInvoker.getTransactionManager();
            }
        }
        Transaction txn = transManager.getTransaction();
        if (txn != null) {
            // Check if Data Source provides XATransaction
            // if(configs.getTransactionType = "XATransaction")
            XAResource xar = conn.getXAResource();
            txn.enlistResource(xar);
            // Asif :Add in the Map after successful registration of XAResource
            xaResourcesMap.put(conn, xar);
        // else throw a resource exception
        }
    } catch (RollbackException ex) {
        throw new ResourceException(LocalizedStrings.JCAConnectionManagerImpl_JCACONNECTIONMANAGERIMPL_ALLOCATECONNECTION_IN_TRANSACTION_DUE_TO_0.toLocalizedString(ex.getMessage()), ex);
    } catch (SystemException ex) {
        throw new ResourceException(LocalizedStrings.JCAConnectionManagerImpl_JCACONNECTIONMANAGERIMPL_ALLOCATECONNECTION_SYSTEM_EXCEPTION_DUE_TO_0.toLocalizedString(ex.getMessage()), ex);
    }
    return conn.getConnection(subject, reqInfo);
}
Also used : XAResource(javax.transaction.xa.XAResource) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) ResourceException(javax.resource.ResourceException) ManagedConnection(javax.resource.spi.ManagedConnection) RollbackException(javax.transaction.RollbackException)

Example 40 with Transaction

use of javax.transaction.Transaction in project geode by apache.

the class TransactionManagerImpl method commit.

/**
   * Complete the transaction associated with the current thread by calling the
   * GlobalTransaction.commit(). When this method completes, the thread is no longer associated with
   * a transaction.
   * 
   * @throws RollbackException - Thrown to indicate that the transaction has been rolled back rather
   *         than committed.
   * @throws HeuristicMixedException - Thrown to indicate that a heuristic decision was made and
   *         that some relevant updates have been committed while others have been rolled back.
   * @throws HeuristicRollbackException - Thrown to indicate that a heuristic decision was made and
   *         that all relevant updates have been rolled back.
   * @throws java.lang.SecurityException - Thrown to indicate that the thread is not allowed to
   *         commit the transaction.
   * @throws java.lang.IllegalStateException - Thrown if the current thread is not associated with a
   *         transaction.
   * @throws SystemException - Thrown if the transaction manager encounters an unexpected error
   *         condition.
   * 
   * @see javax.transaction.TransactionManager#commit()
   */
public void commit() throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException {
    if (!isActive) {
        throw new SystemException(LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGER_INVALID.toLocalizedString());
    }
    int cozOfException = -1;
    Transaction transactionImpl = getTransaction();
    if (transactionImpl == null) {
        String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_IS_NULL_CANNOT_COMMIT_A_NULL_TRANSACTION.toLocalizedString();
        LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
        if (VERBOSE)
            writer.fine(exception);
        throw new IllegalStateException(exception);
    }
    GlobalTransaction gtx = getGlobalTransaction(transactionImpl);
    if (gtx == null) {
        String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_GLOBAL_TRANSACTION_IS_NULL_CANNOT_COMMIT_A_NULL_GLOBAL_TRANSACTION.toLocalizedString();
        LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
        if (VERBOSE)
            writer.fine(exception);
        throw new SystemException(exception);
    }
    boolean isCommit = false;
    // ensure only one thread can commit. Use a synchronized block
    // Asif
    int status = -1;
    if (((status = gtx.getStatus()) == Status.STATUS_ACTIVE) || status == Status.STATUS_MARKED_ROLLBACK) {
        synchronized (gtx) {
            if ((status = gtx.getStatus()) == Status.STATUS_ACTIVE) {
                gtx.setStatus(Status.STATUS_COMMITTING);
                isCommit = true;
            } else if (status == Status.STATUS_MARKED_ROLLBACK) {
                gtx.setStatus(Status.STATUS_ROLLING_BACK);
                cozOfException = MARKED_ROLLBACK;
            } else {
                String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_NOT_ACTIVE_CANNOT_BE_COMMITTED_TRANSACTION_STATUS_0.toLocalizedString(Integer.valueOf(status));
                LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
                if (VERBOSE)
                    writer.fine(exception);
                throw new IllegalStateException(exception);
            }
        }
    } else {
        String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_IS_NOT_ACTIVE_AND_CANNOT_BE_COMMITTED.toLocalizedString();
        LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
        if (VERBOSE)
            writer.fine(exception);
        throw new IllegalStateException(exception);
    }
    // Only one thread can call commit (the first thread to do reach the block
    // above).
    // Before commiting the notifications to be done before the done are called
    // the global transaction is called and then the after completion
    // notifications
    // are taken care of. The transactions associated to the global
    // transactions are
    // removed from the map and also the tread to transaction.
    //
    // Asif : Store the thrown Exception in case of commit .
    // Reuse it for thrwing later.
    // Asif TODO:Verify if it is a good practise
    boolean isClean = false;
    Exception e = null;
    try {
        ((TransactionImpl) transactionImpl).notifyBeforeCompletion();
        isClean = true;
    } catch (Exception ge) {
        // Asif : Just mark the Tranxn to setRollbackOnly to ensure Rollback
        setRollbackOnly();
        cozOfException = EXCEPTION_IN_NOTIFY_BEFORE_COMPLETION;
        e = ge;
    }
    // will be harmless
    if (isCommit) {
        synchronized (gtx) {
            if ((status = gtx.getStatus()) == Status.STATUS_COMMITTING) {
                // and appropriately mark the exception code
                try {
                    gtx.commit();
                } catch (RollbackException rbe) {
                    e = rbe;
                    cozOfException = COMMIT_FAILED_SO_ROLLEDBAK;
                } catch (SystemException se) {
                    e = se;
                    cozOfException = COMMIT_FAILED_ROLLBAK_ALSO_FAILED;
                }
            } else if (status == Status.STATUS_ROLLING_BACK) {
                try {
                    gtx.rollback();
                    if (isClean)
                        cozOfException = MARKED_ROLLBACK;
                } catch (SystemException se) {
                    e = se;
                    cozOfException = ROLLBAK_FAILED;
                }
            }
        }
    } else {
        try {
            gtx.rollback();
        } catch (SystemException se) {
            e = se;
            cozOfException = ROLLBAK_FAILED;
        }
    }
    try {
        ((TransactionImpl) transactionImpl).notifyAfterCompletion(status = gtx.getStatus());
    } catch (Exception ge) {
        LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
        if (writer.infoEnabled())
            writer.info(LocalizedStrings.TransactionManagerImpl_EXCEPTION_IN_NOTIFY_AFTER_COMPLETION_DUE_TO__0, ge.getMessage(), ge);
    }
    Thread thread = Thread.currentThread();
    transactionMap.remove(thread);
    this.gtxSet.remove(gtx);
    if (status != Status.STATUS_COMMITTED) {
        switch(cozOfException) {
            case EXCEPTION_IN_NOTIFY_BEFORE_COMPLETION:
                {
                    String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_ROLLED_BACK_BECAUSE_OF_EXCEPTION_IN_NOTIFYBEFORECOMPLETION_FUNCTION_CALL_ACTUAL_EXCEPTION_0.toLocalizedString();
                    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
                    if (VERBOSE)
                        writer.fine(exception, e);
                    RollbackException re = new RollbackException(exception);
                    re.initCause(e);
                    throw re;
                }
            case MARKED_ROLLBACK:
                {
                    String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_ROLLED_BACK_BECAUSE_A_USER_MARKED_IT_FOR_ROLLBACK.toLocalizedString();
                    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
                    if (VERBOSE)
                        writer.fine(exception, e);
                    throw new RollbackException(exception);
                }
            case COMMIT_FAILED_SO_ROLLEDBAK:
                {
                    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
                    if (VERBOSE)
                        writer.fine(e);
                    throw (RollbackException) e;
                }
            case COMMIT_FAILED_ROLLBAK_ALSO_FAILED:
            case ROLLBAK_FAILED:
                {
                    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
                    if (VERBOSE)
                        writer.fine(e);
                    throw (SystemException) e;
                }
        }
    }
    gtx.setStatus(Status.STATUS_NO_TRANSACTION);
}
Also used : SystemException(javax.transaction.SystemException) Transaction(javax.transaction.Transaction) LogWriterI18n(org.apache.geode.i18n.LogWriterI18n) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) RollbackException(javax.transaction.RollbackException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) InvalidTransactionException(javax.transaction.InvalidTransactionException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException) CancelException(org.apache.geode.CancelException)

Aggregations

Transaction (javax.transaction.Transaction)160 SystemException (javax.transaction.SystemException)55 Test (org.junit.Test)42 RollbackException (javax.transaction.RollbackException)26 TransactionManager (javax.transaction.TransactionManager)24 UserTransaction (javax.transaction.UserTransaction)19 NotInTransactionException (org.neo4j.graphdb.NotInTransactionException)14 NotSupportedException (javax.transaction.NotSupportedException)13 Synchronization (javax.transaction.Synchronization)10 XAResource (javax.transaction.xa.XAResource)10 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)10 HazelcastXAResource (com.hazelcast.transaction.HazelcastXAResource)8 InvalidTransactionException (javax.transaction.InvalidTransactionException)7 TransactionContext (com.hazelcast.transaction.TransactionContext)6 RemoteException (java.rmi.RemoteException)6 ResourceException (javax.resource.ResourceException)6 ManagedConnection (javax.resource.spi.ManagedConnection)6 SQLException (java.sql.SQLException)5 HeuristicMixedException (javax.transaction.HeuristicMixedException)5 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)5