Java Code Examples for javax.transaction.TransactionManager#getTransaction()

The following examples show how to use javax.transaction.TransactionManager#getTransaction() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
private void verifyNoTransaction() {
    try {
        TransactionManager transactionManager = CDI.current().select(TransactionManager.class).get();

        try {
            if (transactionManager.getTransaction() != null) {
                Assert.fail("transaction still active");
            }
        }
        catch (SystemException e) {
            Assert.fail("Could verify that no transaction is associated", e);
        }
    }
    catch (Exception ignore) {
        // the implementation does not expose a JTA TM as a CDI bean
    }
}
 
Example 2
Source File: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void doInTransaction(TransactionManager tm, Transaction tx, RunnableWithException f) throws Exception {
    // Verify if this thread's transaction is the right one
    Transaction currentTransaction = tm.getTransaction();
    // If not, install the right transaction
    if (currentTransaction != tx) {
        if (currentTransaction != null)
            tm.suspend();
        tm.resume(tx);
    }
    f.run();
    if (currentTransaction != tx) {
        tm.suspend();
        if (currentTransaction != null)
            tm.resume(currentTransaction);
    }
}
 
Example 3
Source File: SpringSessionSynchronization.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public SpringSessionSynchronization(
		SessionHolder sessionHolder, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) {

	this.sessionHolder = sessionHolder;
	this.sessionFactory = sessionFactory;
	this.jdbcExceptionTranslator = jdbcExceptionTranslator;
	this.newSession = newSession;

	// Check whether the SessionFactory has a JTA TransactionManager.
	TransactionManager jtaTm =
			SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
	if (jtaTm != null) {
		this.hibernateTransactionCompletion = true;
		// Fetch current JTA Transaction object
		// (just necessary for JTA transaction suspension, with an individual
		// Hibernate Session per currently active/suspended transaction).
		try {
			this.jtaTransaction = jtaTm.getTransaction();
		}
		catch (SystemException ex) {
			throw new DataAccessResourceFailureException("Could not access JTA transaction", ex);
		}
	}
}
 
Example 4
Source File: OpenEJBTransactionService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction getTransaction() {
    final TransactionManager manager = getTransactionManager();
    if (manager != null) {
        try {
            return manager.getTransaction();
        } catch (final SystemException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return null;
}
 
Example 5
Source File: JtaTransactionHelper.java    From snakerflow with Apache License 2.0 5 votes vote down vote up
public static javax.transaction.Transaction lookupJeeTransaction() {
	try {
		TransactionManager transactionManager = lookupJeeTransactionManager();
		return transactionManager.getTransaction();
	} catch (Exception e) {
		throw new SnakerException("无法从事务管理中获取事务对象["
				+ transactionManagerJndiName + "]:\n" + e.getMessage(), e);
	}
}
 
Example 6
Source File: TxUtils.java    From kumuluzee with MIT License 5 votes vote down vote up
public static Boolean isActive(TransactionManager transactionManager) {

        try {
            Transaction tx = transactionManager.getTransaction();

            return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
        } catch (SystemException e) {
            throw new CannotRetrieveTxException(e);
        }
    }
 
Example 7
Source File: GenericXaResource.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Enlists this resource in the current transaction
 * @throws XAException
 */
public void enlist() throws XAException {
    TransactionManager tm = TransactionFactoryLoader.getInstance().getTransactionManager();
    try {
        if (tm != null && tm.getStatus() == Status.STATUS_ACTIVE) {
            Transaction tx = tm.getTransaction();
            this.enlist(tx);
        } else {
            throw new XAException("No transaction manager or invalid status");
        }
    } catch (SystemException e) {
        throw new XAException("Unable to get transaction status");
    }
}
 
Example 8
Source File: ManagedDataSource.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected static Connection getTxConnection(final CommonDataSource delegate, final String u, final String p, final TransactionManager transactionManager, final TransactionSynchronizationRegistry registry) {
    try {
        final Transaction transaction = transactionManager.getTransaction();
        if (transaction != null && ManagedConnection.isUnderTransaction(transaction.getStatus())) {
            final Object resource = registry.getResource(new Key(delegate, u, p));
            if (Connection.class.isInstance(resource)) {
                return Connection.class.cast(resource);
            }
        }
    } catch (SystemException e) {
        // we wouldn't expect this to happen, but lets log it and fall through to the previous behaviour
        LOGGER.warning("Attempting to get the current transaction failed with an error: " + e.getMessage(), e);
    }
    return null;
}
 
Example 9
Source File: JtaTransactionWrapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public JtaTransactionWrapper(KeycloakSessionFactory factory, TransactionManager tm) {
    this.tm = tm;
    this.factory = factory;
    try {

        suspended = tm.suspend();
        logger.debug("new JtaTransactionWrapper");
        logger.debugv("was existing? {0}", suspended != null);
        tm.begin();
        ut = tm.getTransaction();
        //ended = new Exception();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
protected void endTransaction(TransactionManager tm, Transaction tx, RunnableWithException afterEndTransaction)
        throws Exception {
    if (tx != tm.getTransaction()) {
        throw new RuntimeException(jtaLogger.i18NLogger.get_wrong_tx_on_thread());
    }

    if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
        tm.rollback();
    } else {
        tm.commit();
    }

    afterEndTransaction.run();
}
 
Example 11
Source File: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Object intercept(InvocationContext ic) throws Exception {
    final TransactionManager tm = transactionManager;
    final Transaction tx = tm.getTransaction();

    boolean previousUserTransactionAvailability = setUserTransactionAvailable(userTransactionAvailable);
    try {
        return doIntercept(tm, tx, ic);
    } finally {
        resetUserTransactionAvailability(previousUserTransactionAvailability);
    }
}
 
Example 12
Source File: SessionFactoryUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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})
 */
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);
		}
	}
}
 
Example 13
Source File: TxConnectionListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void dissociate() throws ResourceException
{
   log.tracef("dissociate: %s", this);

   try
   {
      TransactionManager tm = getConnectionManager().getTransactionIntegration().getTransactionManager();
      int status = tm.getStatus();

      log.tracef("dissociate: status=%s", TxUtils.getStatusAsString(status));

      if (status != Status.STATUS_NO_TRANSACTION)
      {
         if (isEnlisted())
         {
            if (doDelistResource)
            {
               Transaction tx = tm.getTransaction();
               boolean delistResult = tx.delistResource(getXAResource(), XAResource.TMSUCCESS);

               log.tracef("dissociate: delistResult=%s", delistResult);
            }
         }
         else
         {
            log.tracef("dissociate: not enlisted (%s)", this);
         }

         if (isTrackByTx())
         {
            ManagedConnectionPool mcp = getManagedConnectionPool();
            TransactionSynchronizationRegistry tsr =
               getConnectionManager().getTransactionIntegration().getTransactionSynchronizationRegistry();

            Lock lock = (Lock)tsr.getResource(LockKey.INSTANCE);
            if (lock != null)
            {
               try
               {
                  lock.lockInterruptibly();
               }
               catch (InterruptedException ie)
               {
                  Thread.interrupted();
                  
                  throw new ResourceException(bundle.unableObtainLock(), ie);
               }

               try
               {
                  tsr.putResource(mcp, null);
               }
               finally
               {
                  lock.unlock();
               }
            }
         }
      }

      localTransaction.set(false);
      setTrackByTx(false);
   
      if (transactionSynchronization != null)
      {
         transactionSynchronization.cancel();
         transactionSynchronization = null;
      }

      setEnlisted(false);
   }
   catch (Throwable t)
   {
      throw new ResourceException(bundle.errorInDissociate(), t);
   }
}
 
Example 14
Source File: SessionFactoryUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.
 * @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();
	}
}
 
Example 15
Source File: SessionFactoryUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * 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})
 */
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);
		}
	}
}
 
Example 16
Source File: JCALocalTransaction.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void begin() throws ResourceException
{
  if (DEBUG) {
    try {
      throw new NullPointerException("Asif:JCALocalTransaction:begin");
    }
    catch (NullPointerException npe) {
      npe.printStackTrace();
    }
  }
  try {
    if (!initDone || this.cache.isClosed()) {
      this.init();
    }
    // System.out.println("JCALocalTransaction:Asif: cache is ="+cache +
    // " for tx ="+this);
    LogWriter logger = cache.getLogger();
    if (logger.fineEnabled()) {
      logger.fine("JCALocalTransaction::begin:");
    }
    TransactionManager tm = cache.getJTATransactionManager();
    if (this.tid != null) {
      throw new LocalTransactionException(
          " A transaction is already in progress");
    }
    if (tm != null && tm.getTransaction() != null) {
      if (logger.fineEnabled()) {
        logger.fine("JCAManagedConnection: JTA transaction is on");
      }
      // This is having a JTA transaction. Assuming ignore jta flag is true,
      // explicitly being a gemfire transaction.
      TXStateInterface tsp = this.gfTxMgr.getTXState();
      if (tsp == null) {
        this.gfTxMgr.begin();
        tsp = this.gfTxMgr.getTXState();
        tsp.getProxy().setJCA(true);
        this.tid = tsp.getTransactionId();
        if (logger.fineEnabled()) {
          logger.fine("JCALocalTransaction:begun GFE transaction");
        }
      }
      else {
        throw new LocalTransactionException(
            "GemFire is already associated with a transaction");
      }
    }
    else {
      if (logger.fineEnabled()) {
        logger.fine("JCAManagedConnection: JTA Transaction does not exist.");
      }
    }
  }
  catch (SystemException e) {
    // this.onError();
    throw new ResourceException(e);
  }
  // Not to be invoked for local transactions managed by the container
  // Iterator<ConnectionEventListener> itr = this.listeners.iterator();
  // ConnectionEvent ce = new ConnectionEvent(this,
  // ConnectionEvent.LOCAL_TRANSACTION_STARTED);
  // while (itr.hasNext()) {
  // itr.next().localTransactionStarted(ce);
  // }

}
 
Example 17
Source File: JCALocalTransaction.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void begin() throws ResourceException
{
  if (DEBUG) {
    try {
      throw new NullPointerException("Asif:JCALocalTransaction:begin");
    }
    catch (NullPointerException npe) {
      npe.printStackTrace();
    }
  }
  try {
    if (!initDone || this.cache.isClosed()) {
      this.init();
    }
    // System.out.println("JCALocalTransaction:Asif: cache is ="+cache +
    // " for tx ="+this);
    LogWriter logger = cache.getLogger();
    if (logger.fineEnabled()) {
      logger.fine("JCALocalTransaction::begin:");
    }
    TransactionManager tm = cache.getJTATransactionManager();
    if (this.tid != null) {
      throw new LocalTransactionException(
          " A transaction is already in progress");
    }
    if (tm != null && tm.getTransaction() != null) {
      if (logger.fineEnabled()) {
        logger.fine("JCAManagedConnection: JTA transaction is on");
      }
      // This is having a JTA transaction. Assuming ignore jta flag is true,
      // explicitly being a gemfire transaction.
      TXStateInterface tsp = this.gfTxMgr.getTXState();
      if (tsp == null) {
        this.gfTxMgr.begin();
        tsp = this.gfTxMgr.getTXState();
        tsp.getProxy().setJCA(true);
        this.tid = tsp.getTransactionId();
        if (logger.fineEnabled()) {
          logger.fine("JCALocalTransaction:begun GFE transaction");
        }
      }
      else {
        throw new LocalTransactionException(
            "GemFire is already associated with a transaction");
      }
    }
    else {
      if (logger.fineEnabled()) {
        logger.fine("JCAManagedConnection: JTA Transaction does not exist.");
      }
    }
  }
  catch (SystemException e) {
    // this.onError();
    throw new ResourceException(e);
  }
  // Not to be invoked for local transactions managed by the container
  // Iterator<ConnectionEventListener> itr = this.listeners.iterator();
  // ConnectionEvent ce = new ConnectionEvent(this,
  // ConnectionEvent.LOCAL_TRANSACTION_STARTED);
  // while (itr.hasNext()) {
  // itr.next().localTransactionStarted(ce);
  // }

}
 
Example 18
Source File: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 4 votes vote down vote up
protected Object invokeInOurTx(InvocationContext ic, TransactionManager tm, RunnableWithException afterEndTransaction)
        throws Exception {

    TransactionConfiguration configAnnotation = getTransactionConfiguration(ic);
    int currentTmTimeout = ((CDIDelegatingTransactionManager) transactionManager).getTransactionTimeout();
    if (configAnnotation != null && configAnnotation.timeout() != TransactionConfiguration.UNSET_TIMEOUT) {
        tm.setTransactionTimeout(configAnnotation.timeout());
    }
    Transaction tx;
    try {
        tm.begin();
        tx = tm.getTransaction();
    } finally {
        if (configAnnotation != null && configAnnotation.timeout() != TransactionConfiguration.UNSET_TIMEOUT) {
            //restore the default behaviour
            tm.setTransactionTimeout(currentTmTimeout);
        }
    }

    boolean throwing = false;
    Object ret = null;

    try {
        ret = ic.proceed();
    } catch (Exception e) {
        throwing = true;
        handleException(ic, e, tx);
    } finally {
        // handle asynchronously if not throwing
        if (!throwing && ret != null) {
            ReactiveTypeConverter<Object> converter = null;
            if (ret instanceof CompletionStage == false
                    && (ret instanceof Publisher == false || ic.getMethod().getReturnType() != Publisher.class)) {
                @SuppressWarnings({ "rawtypes", "unchecked" })
                Optional<ReactiveTypeConverter<Object>> lookup = Registry.lookup((Class) ret.getClass());
                if (lookup.isPresent()) {
                    converter = lookup.get();
                    if (converter.emitAtMostOneItem()) {
                        ret = converter.toCompletionStage(ret);
                    } else {
                        ret = converter.toRSPublisher(ret);
                    }
                }
            }
            if (ret instanceof CompletionStage) {
                ret = handleAsync(tm, tx, ic, ret, afterEndTransaction);
                // convert back
                if (converter != null)
                    ret = converter.fromCompletionStage((CompletionStage<?>) ret);
            } else if (ret instanceof Publisher) {
                ret = handleAsync(tm, tx, ic, ret, afterEndTransaction);
                // convert back
                if (converter != null)
                    ret = converter.fromPublisher((Publisher<?>) ret);
            } else {
                // not async: handle synchronously
                endTransaction(tm, tx, afterEndTransaction);
            }
        } else {
            // throwing or null: handle synchronously
            endTransaction(tm, tx, afterEndTransaction);
        }
    }
    return ret;
}
 
Example 19
Source File: GridJtaTransactionManagerSelfTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Test for switching tx context by JTA Manager.
 *
 * @throws Exception If failed.
 */
@Test
public void testJtaTxContextSwitch() throws Exception {
    for (TransactionIsolation isolation : TransactionIsolation.values()) {
        TransactionConfiguration cfg = grid().context().config().getTransactionConfiguration();

        cfg.setDefaultTxConcurrency(txConcurrency);
        cfg.setDefaultTxIsolation(isolation);

        TransactionManager jtaTm = jotm.getTransactionManager();

        IgniteCache<Integer, String> cache = jcache();

        assertNull(grid().transactions().tx());

        jtaTm.begin();

        Transaction tx1 = jtaTm.getTransaction();

        cache.put(1, Integer.toString(1));

        assertNotNull(grid().transactions().tx());

        assertEquals(ACTIVE, grid().transactions().tx().state());

        assertEquals(Integer.toString(1), cache.get(1));

        jtaTm.suspend();

        assertNull(grid().transactions().tx());

        assertNull(cache.get(1));

        jtaTm.begin();

        Transaction tx2 = jtaTm.getTransaction();

        assertNotSame(tx1, tx2);

        cache.put(2, Integer.toString(2));

        assertNotNull(grid().transactions().tx());

        assertEquals(ACTIVE, grid().transactions().tx().state());

        assertEquals(Integer.toString(2), cache.get(2));

        jtaTm.commit();

        assertNull(grid().transactions().tx());

        assertEquals(Integer.toString(2), cache.get(2));

        jtaTm.resume(tx1);

        assertNotNull(grid().transactions().tx());

        assertEquals(ACTIVE, grid().transactions().tx().state());

        cache.put(3, Integer.toString(3));

        jtaTm.commit();

        assertEquals("1", cache.get(1));
        assertEquals("2", cache.get(2));
        assertEquals("3", cache.get(3));

        assertNull(grid().transactions().tx());

        cache.removeAll();
    }
}
 
Example 20
Source File: GridJtaTransactionManagerSelfTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testJtaTxContextSwitchWithExistingTx() throws Exception {
    for (TransactionIsolation isolation : TransactionIsolation.values()) {
        TransactionConfiguration cfg = grid().context().config().getTransactionConfiguration();

        cfg.setDefaultTxConcurrency(txConcurrency);
        cfg.setDefaultTxIsolation(isolation);

        TransactionManager jtaTm = jotm.getTransactionManager();

        IgniteCache<Integer, String> cache = jcache();

        jtaTm.begin();

        Transaction tx1 = jtaTm.getTransaction();

        cache.put(1, Integer.toString(1));

        assertNotNull(grid().transactions().tx());

        assertEquals(ACTIVE, grid().transactions().tx().state());

        assertEquals(Integer.toString(1), cache.get(1));

        jtaTm.suspend();

        jtaTm.begin();

        Transaction tx2 = jtaTm.getTransaction();

        assertNotSame(tx1, tx2);

        cache.put(2, Integer.toString(2));

        try {
            jtaTm.resume(tx1);

            fail("jtaTm.resume shouldn't success.");
        }
        catch (IllegalStateException ignored) {
            // No-op.
        }
        finally {
            jtaTm.rollback(); //rolling back tx2
        }

        jtaTm.resume(tx1);
        jtaTm.rollback();

        cache.removeAll();
    }
}