Search in sources :

Example 6 with RollbackException

use of javax.transaction.RollbackException in project spring-framework by spring-projects.

the class JtaTransactionManagerTests method jtaTransactionManagerWithRollbackExceptionOnCommit.

@Test
public void jtaTransactionManagerWithRollbackExceptionOnCommit() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    willThrow(new RollbackException("unexpected rollback")).given(ut).commit();
    try {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

                    @Override
                    public void afterCompletion(int status) {
                        assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_ROLLED_BACK);
                    }
                });
            }
        });
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
    // expected
    }
    verify(ut).begin();
}
Also used : UserTransaction(javax.transaction.UserTransaction) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) RollbackException(javax.transaction.RollbackException) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) TransactionSynchronizationAdapter(org.springframework.transaction.support.TransactionSynchronizationAdapter) Test(org.junit.Test)

Example 7 with RollbackException

use of javax.transaction.RollbackException in project hibernate-orm by hibernate.

the class TransactionRolledBackInDifferentThreadTest method testTransactionRolledBackInDifferentThreadFailure.

@Test
public void testTransactionRolledBackInDifferentThreadFailure() throws Exception {
    /**
		 * The three test threads share the same entity manager.
		 * The main test thread creates an EntityManager, joins it to the transaction and ends the transaction.
		 * Test thread 1 joins the EntityManager to its transaction, sets rollbackonly and ends the transaction.
		 * Test thread 2 attempts to join the EntityManager to its transaction but will fail with a
		 *   HibernateException("Transaction was rolled back in a different thread!")
		 */
    // main test thread
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    final EntityManager em = entityManagerFactory().createEntityManager();
    em.joinTransaction();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    // will be set to the failing exception
    final HibernateException[] transactionRolledBackInDifferentThreadException = new HibernateException[2];
    transactionRolledBackInDifferentThreadException[0] = transactionRolledBackInDifferentThreadException[1] = null;
    // background test thread 1
    final Runnable run1 = new Runnable() {

        @Override
        public void run() {
            try {
                TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
                em.joinTransaction();
                TestingJtaPlatformImpl.INSTANCE.getTransactionManager().setRollbackOnly();
                TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
            } catch (javax.persistence.PersistenceException e) {
                if (e.getCause() instanceof HibernateException && e.getCause().getMessage().equals("Transaction was rolled back in a different thread!")) {
                    /**
						 * Save the exception for the main test thread to fail
						 */
                    // show the error first
                    e.printStackTrace();
                    transactionRolledBackInDifferentThreadException[0] = (HibernateException) e.getCause();
                }
            } catch (RollbackException ignored) {
            // expected to see RollbackException: ARJUNA016053: Could not commit transaction.
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            } finally {
                try {
                    if (TestingJtaPlatformImpl.INSTANCE.getTransactionManager().getStatus() != Status.STATUS_NO_TRANSACTION) {
                        TestingJtaPlatformImpl.INSTANCE.getTransactionManager().rollback();
                    }
                } catch (SystemException ignore) {
                }
            }
        }
    };
    // test thread 2
    final Runnable run2 = new Runnable() {

        @Override
        public void run() {
            try {
                TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
                /**
					 * the following call to em.joinTransaction() will throw:
					 *   org.hibernate.HibernateException: Transaction was rolled back in a different thread!
					 */
                em.joinTransaction();
                TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
            } catch (javax.persistence.PersistenceException e) {
                if (e.getCause() instanceof HibernateException && e.getCause().getMessage().equals("Transaction was rolled back in a different thread!")) {
                    /**
						 * Save the exception for the main test thread to fail
						 */
                    // show the error first
                    e.printStackTrace();
                    transactionRolledBackInDifferentThreadException[1] = (HibernateException) e.getCause();
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            } finally {
                try {
                    if (TestingJtaPlatformImpl.INSTANCE.getTransactionManager().getStatus() != Status.STATUS_NO_TRANSACTION) {
                        TestingJtaPlatformImpl.INSTANCE.getTransactionManager().rollback();
                    }
                } catch (SystemException ignore) {
                }
            }
        }
    };
    Thread thread = new Thread(run1, "test thread1");
    thread.start();
    thread.join();
    Thread thread2 = new Thread(run2, "test thread2");
    thread2.start();
    thread2.join();
    // show failure for exception caught in run2.run()
    if (transactionRolledBackInDifferentThreadException[0] != null || transactionRolledBackInDifferentThreadException[1] != null) {
        fail("failure in test thread 1 = " + (transactionRolledBackInDifferentThreadException[0] != null ? transactionRolledBackInDifferentThreadException[0].getMessage() : "(none)") + ", failure in test thread 2 = " + (transactionRolledBackInDifferentThreadException[1] != null ? transactionRolledBackInDifferentThreadException[1].getMessage() : "(none)"));
    }
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) SystemException(javax.transaction.SystemException) HibernateException(org.hibernate.HibernateException) RollbackException(javax.transaction.RollbackException) Test(org.junit.Test)

Example 8 with RollbackException

use of javax.transaction.RollbackException 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 9 with RollbackException

use of javax.transaction.RollbackException 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)

Example 10 with RollbackException

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

the class RemoteTransactionDUnitTest method testBug43081.

@Test
public void testBug43081() throws Exception {
    createRegion(false, 0, null);
    Context ctx = getCache().getJNDIContext();
    UserTransaction tx = (UserTransaction) ctx.lookup("java:/UserTransaction");
    assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
    Region pr = getCache().getRegion(CUSTOMER);
    Region rr = getCache().getRegion(D_REFERENCE);
    // test all ops
    for (int i = 0; i < 6; i++) {
        pr.put(new CustId(1), new Customer("name1", "address1"));
        rr.put("key1", "value1");
        tx.begin();
        switch(i) {
            case 0:
                pr.get(new CustId(1));
                rr.get("key1");
                break;
            case 1:
                pr.put(new CustId(1), new Customer("nameNew", "addressNew"));
                rr.put("key1", "valueNew");
                break;
            case 2:
                pr.invalidate(new CustId(1));
                rr.invalidate("key1");
                break;
            case 3:
                pr.destroy(new CustId(1));
                rr.destroy("key1");
                break;
            case 4:
                Map m = new HashMap();
                m.put(new CustId(1), new Customer("nameNew", "addressNew"));
                pr.putAll(m);
                m = new HashMap();
                m.put("key1", "valueNew");
                rr.putAll(m);
                break;
            case 5:
                Set s = new HashSet();
                s.add(new CustId(1));
                pr.getAll(s);
                s = new HashSet();
                s.add("key1");
                pr.getAll(s);
                break;
            case 6:
                pr.getEntry(new CustId(1));
                rr.getEntry("key1");
                break;
            default:
                break;
        }
        // Putting a string key causes this, the partition resolver
        // doesn't handle it.
        IgnoredException.addIgnoredException("IllegalStateException");
        assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
        final CountDownLatch latch = new CountDownLatch(1);
        Thread t = new Thread(new Runnable() {

            public void run() {
                Context ctx = getCache().getJNDIContext();
                try {
                    UserTransaction tx = (UserTransaction) ctx.lookup("java:/UserTransaction");
                } catch (NamingException e) {
                    e.printStackTrace();
                }
                Region pr = getCache().getRegion(CUSTOMER);
                Region rr = getCache().getRegion(D_REFERENCE);
                pr.put(new CustId(1), new Customer("name11", "address11"));
                rr.put("key1", "value1");
                latch.countDown();
            }
        });
        t.start();
        latch.await();
        try {
            pr.put(new CustId(1), new Customer("name11", "address11"));
            tx.commit();
            fail("expected exception not thrown");
        } catch (RollbackException e) {
        }
    }
}
Also used : FunctionContext(org.apache.geode.cache.execute.FunctionContext) Context(javax.naming.Context) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) UserTransaction(javax.transaction.UserTransaction) Set(java.util.Set) HashSet(java.util.HashSet) Customer(org.apache.geode.internal.cache.execute.data.Customer) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) RollbackException(javax.transaction.RollbackException) CustId(org.apache.geode.internal.cache.execute.data.CustId) Region(org.apache.geode.cache.Region) NamingException(javax.naming.NamingException) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) TXExpiryJUnitTest(org.apache.geode.TXExpiryJUnitTest) Test(org.junit.Test)

Aggregations

RollbackException (javax.transaction.RollbackException)57 SystemException (javax.transaction.SystemException)25 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)15 Transaction (javax.transaction.Transaction)14 UserTransaction (javax.transaction.UserTransaction)14 HeuristicMixedException (javax.transaction.HeuristicMixedException)12 Test (org.junit.Test)11 Connection (java.sql.Connection)8 XAException (javax.transaction.xa.XAException)8 PreparedStatement (java.sql.PreparedStatement)7 NotSupportedException (javax.transaction.NotSupportedException)7 IOException (java.io.IOException)6 EJBException (javax.ejb.EJBException)6 Account (org.apache.openejb.test.object.Account)6 RemoteException (java.rmi.RemoteException)5 CreateException (javax.ejb.CreateException)5 DataSource (javax.sql.DataSource)5 SQLException (java.sql.SQLException)4 Synchronization (javax.transaction.Synchronization)4 XAResource (javax.transaction.xa.XAResource)4