Java Code Examples for javax.transaction.Transaction

The following examples show how to use javax.transaction.Transaction. These examples are extracted from open source projects. 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
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception {
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).begin();
	verify(tm).commit();
	verify(tm).resume(tx);
}
 
Example 2
Source Project: tomee   Source File: PseudoTransactionService.java    License: Apache License 2.0 6 votes vote down vote up
public void resume(final Transaction tx) throws InvalidTransactionException {
    if (tx == null) {
        throw new InvalidTransactionException("Transaction is null");
    }
    if (!(tx instanceof MyTransaction)) {
        throw new InvalidTransactionException("Unknown transaction type " + tx.getClass().getName());
    }
    final MyTransaction myTransaction = (MyTransaction) tx;

    if (threadTransaction.get() != null) {
        throw new IllegalStateException("A transaction is already active");
    }

    final int status = myTransaction.getStatus();
    if (status != Status.STATUS_ACTIVE && status != Status.STATUS_MARKED_ROLLBACK) {
        throw new InvalidTransactionException("Expected transaction to be STATUS_ACTIVE or STATUS_MARKED_ROLLBACK, but was " + status);
    }

    threadTransaction.set(myTransaction);
}
 
Example 3
Source Project: lams   Source File: TransactionManagerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void commit() throws RollbackException,
                            HeuristicMixedException,
                            HeuristicRollbackException,
                            SecurityException,
                            IllegalStateException,
                            SystemException
{
   Transaction tx = registry.getTransaction();

   if (tx == null)
      throw new SystemException();

   if (tx.getStatus() == Status.STATUS_ROLLEDBACK ||
       tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
      throw new RollbackException();

   registry.commitTransaction();
}
 
Example 4
Source Project: quarkus   Source File: ContextEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
@GET
@Path("/transaction-tc")
public CompletionStage<String> transactionThreadContextTest() throws SystemException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<String> ret = allTc.withContextCapture(CompletableFuture.completedFuture("OK"));

    ContextEntity entity = new ContextEntity();
    entity.name = "Stef";
    entity.persist();
    Transaction t1 = Panache.getTransactionManager().getTransaction();
    Assertions.assertNotNull(t1);

    return ret.thenApplyAsync(text -> {
        Assertions.assertEquals(1, ContextEntity.count());
        Transaction t2;
        try {
            t2 = Panache.getTransactionManager().getTransaction();
        } catch (SystemException e) {
            throw new RuntimeException(e);
        }
        Assertions.assertEquals(t1, t2);
        return text;
    }, executor);
}
 
Example 5
Source Project: tomee   Source File: ContextServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(this, args);
    }

    final Transaction suspendedTx;
    if (suspendTx) {
        suspendedTx = OpenEJB.getTransactionManager().suspend();
    } else {
        suspendedTx = null;
    }

    try {
        return invoke(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return method.invoke(instance, args);
            }
        });
    } finally {
        if (suspendedTx != null) {
            OpenEJB.getTransactionManager().resume(suspendedTx);
        }
    }
}
 
Example 6
Source Project: lams   Source File: TxUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Is the transaction uncommitted
 * @param tx The transaction
 * @return True if uncommitted; otherwise false
 */
public static boolean isUncommitted(Transaction tx)
{
   if (tx == null)
      return false;
   
   try
   {
      int status = tx.getStatus();

      return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
   }
   catch (SystemException error)
   {
      throw new RuntimeException("Error during isUncommitted()", error);
   }
}
 
Example 7
Source Project: quarkus   Source File: TransactionScopedTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void transactionScopedInTransaction() throws Exception {
    tx.begin();
    beanTransactional.setValue(42);
    assertEquals(42, beanTransactional.getValue(), "Transaction scope did not save the value");
    Transaction suspendedTransaction = tm.suspend();

    assertThrows(ContextNotActiveException.class, () -> {
        beanTransactional.getValue();
    }, "Not expecting to have available TransactionScoped bean outside of the transaction");

    tx.begin();
    beanTransactional.setValue(1);
    assertEquals(1, beanTransactional.getValue(), "Transaction scope did not save the value");
    tx.commit();

    assertThrows(ContextNotActiveException.class, () -> {
        beanTransactional.getValue();
    }, "Not expecting to have available TransactionScoped bean outside of the transaction");

    tm.resume(suspendedTransaction);
    assertEquals(42, beanTransactional.getValue(), "Transaction scope did not resumed correctly");
    tx.rollback();
}
 
Example 8
/**
 * {@inheritDoc}
 */
public void commit() throws RollbackException,
                            HeuristicMixedException,
                            HeuristicRollbackException,
                            SecurityException,
                            IllegalStateException,
                            SystemException
{
   Transaction tx = registry.getTransaction();

   if (tx == null)
      throw new SystemException();

   if (tx.getStatus() == Status.STATUS_ROLLEDBACK ||
       tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
      throw new RollbackException();

   registry.commitTransaction();
}
 
Example 9
/**
 * Callback for Connection Closed.
 * 
 * @param event ConnectionEvent Object.
 */
public void connectionClosed(ConnectionEvent event) {
  if (isActive) {
    ManagedConnection conn = (ManagedConnection) event.getSource();
    TransactionManagerImpl transManager = TransactionManagerImpl
        .getTransactionManager();
    try {
      Transaction txn = transManager.getTransaction();
      if (txn == null) {
        mannPoolCache.returnPooledConnectionToPool(conn);
      }
    }
    catch (Exception se) {
      String exception = "FacetsJCAConnectionManagerImpl::connectionClosed: Exception occured due to "
          + se;
      LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
      if (writer.fineEnabled()) writer.fine(exception, se);
    }
  }
}
 
Example 10
Source Project: quarkus   Source File: TransactionalInterceptorBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void handleExceptionNoThrow(InvocationContext ic, Throwable e, Transaction tx)
        throws IllegalStateException, SystemException {

    Transactional transactional = getTransactional(ic);

    for (Class<?> dontRollbackOnClass : transactional.dontRollbackOn()) {
        if (dontRollbackOnClass.isAssignableFrom(e.getClass())) {
            return;
        }
    }

    for (Class<?> rollbackOnClass : transactional.rollbackOn()) {
        if (rollbackOnClass.isAssignableFrom(e.getClass())) {
            tx.setRollbackOnly();
            return;
        }
    }

    if (e instanceof RuntimeException) {
        tx.setRollbackOnly();
        return;
    }
}
 
Example 11
Source Project: quarkus   Source File: TransactionContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The transaction scoped context is active when a transaction is active.
 */
@Override
public boolean isActive() {
    Transaction transaction = getCurrentTransaction();
    if (transaction == null) {
        return false;
    }

    try {
        int currentStatus = transaction.getStatus();
        return currentStatus == Status.STATUS_ACTIVE ||
                currentStatus == Status.STATUS_MARKED_ROLLBACK ||
                currentStatus == Status.STATUS_PREPARED ||
                currentStatus == Status.STATUS_UNKNOWN ||
                currentStatus == Status.STATUS_PREPARING ||
                currentStatus == Status.STATUS_COMMITTING ||
                currentStatus == Status.STATUS_ROLLING_BACK;
    } catch (SystemException e) {
        throw new RuntimeException("Error getting the status of the current transaction", e);
    }
}
 
Example 12
/**
 * Callback for Connection Closed.
 * 
 * @param event ConnectionEvent Object.
 */
public void connectionClosed(ConnectionEvent event) {
  if (isActive) {
    ManagedConnection conn = (ManagedConnection) event.getSource();
    TransactionManagerImpl transManager = TransactionManagerImpl
        .getTransactionManager();
    try {
      Transaction txn = transManager.getTransaction();
      if (txn == null) {
        mannPoolCache.returnPooledConnectionToPool(conn);
      }
    }
    catch (Exception se) {
      String exception = "FacetsJCAConnectionManagerImpl::connectionClosed: Exception occured due to "
          + se;
      LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
      if (writer.fineEnabled()) writer.fine(exception, se);
    }
  }
}
 
Example 13
Source Project: lams   Source File: UserTransactionImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void commit() throws RollbackException,
                            HeuristicMixedException,
                            HeuristicRollbackException,
                            SecurityException,
                            IllegalStateException,
                            SystemException
{
   Transaction tx = registry.getTransaction();

   if (tx == null)
      throw new SystemException();

   if (tx.getStatus() == Status.STATUS_ROLLING_BACK ||
       tx.getStatus() == Status.STATUS_ROLLEDBACK ||
       tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
      throw new RollbackException();

   registry.commitTransaction();
}
 
Example 14
Source Project: lastaflute   Source File: ConnectionPoolViewBuilder.java    License: Apache License 2.0 6 votes vote down vote up
protected void setupTransactionViewListByReflection(ConnectionPool pool, List<String> txViewList) {
    final Field field = DfReflectionUtil.getWholeField(pool.getClass(), "txActivePool");
    @SuppressWarnings("unchecked")
    final Map<Transaction, ConnectionWrapper> txActivePool =
            (Map<Transaction, ConnectionWrapper>) DfReflectionUtil.getValueForcedly(field, pool);
    synchronized (pool) { // just in case
        for (Entry<Transaction, ConnectionWrapper> entry : txActivePool.entrySet()) {
            final Transaction tx = entry.getKey();
            final ConnectionWrapper wrapper = entry.getValue();
            final String romantic;
            if (tx instanceof RomanticTransaction) {
                romantic = ((RomanticTransaction) tx).toRomanticSnapshot(wrapper);
            } else {
                romantic = tx.toString();
            }
            txViewList.add(romantic);
        }
    }
}
 
Example 15
@Override
public void run(final Runnable runnable) throws Throwable {
    Transaction suspendedTransaction = null;
    try {
        suspendedTransaction = suspendTransaction();
        runWithTransaction(runnable, true);
    } finally {
        resumeTransaction(suspendedTransaction);
    }
}
 
Example 16
Source Project: tomee   Source File: TxBeanManaged.java    License: Apache License 2.0 5 votes vote down vote up
public void commit() throws ApplicationException, SystemException {
    try {
        // The Container must detect the case in which a transaction was started, but
        // not completed, in the business method, and handle it as follows:
        final Transaction currentTx = getTransaction();
        if (currentTx != null) {
            final String message = "The EJB started a transaction but did not complete it.";

            /* [1] Log this as an application error ********/
            logger.error(message);

            /* [2] Roll back the started transaction *******/
            try {
                rollbackTransaction(currentTx);
            } catch (final Throwable t) {
                // no-op
            }

            /* [3] Throw the RemoteException to the client */
            throw new ApplicationException(new RemoteException(message));
        }

        fireNonTransactionalCompletion();
    } finally {
        resumeTransaction(clientTx);
    }
}
 
Example 17
Source Project: gemfirexd-oss   Source File: JCAConnectionManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    xaResourcesMap.remove(conn);
    TransactionManagerImpl transManager = TransactionManagerImpl
        .getTransactionManager();
    try {
      Transaction txn = transManager.getTransaction();
      if (txn != null && xar != null)
          txn.delistResource(xar, XAResource.TMSUCCESS);
    }
    catch (SystemException se) {
      se.printStackTrace();
    }
    try {
      mannPoolCache.expirePooledConnection(conn);
      //mannPoolCache.destroyPooledConnection(conn);
    }
    catch (Exception ex) {
      String exception = "JCAConnectionManagerImpl::connectionErrorOccured: Exception occured due to "
          + ex;
      LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
      if (writer.fineEnabled()) writer.fine(exception, ex);
    }
  }
}
 
Example 18
Source Project: seed   Source File: TransactionManagerMock.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Transaction suspend() throws SystemException {
    TransactionMock suspendedTransaction = new TransactionMock(new UserTransactionMock(userTransaction));
    userTransaction.setStatus(Status.STATUS_NO_TRANSACTION);
    suspendCallCount++;
    return suspendedTransaction;
}
 
Example 19
private void loadWebLogicTransactionClasses() throws TransactionSystemException {
	try {
		Class<?> userTransactionClass = getClass().getClassLoader().loadClass(USER_TRANSACTION_CLASS_NAME);
		this.weblogicUserTransactionAvailable = userTransactionClass.isInstance(getUserTransaction());
		if (this.weblogicUserTransactionAvailable) {
			this.beginWithNameMethod = userTransactionClass.getMethod("begin", String.class);
			this.beginWithNameAndTimeoutMethod = userTransactionClass.getMethod("begin", String.class, int.class);
			logger.debug("Support for WebLogic transaction names available");
		}
		else {
			logger.debug("Support for WebLogic transaction names not available");
		}

		// Obtain WebLogic ClientTransactionManager interface.
		Class<?> transactionManagerClass =
				getClass().getClassLoader().loadClass(CLIENT_TRANSACTION_MANAGER_CLASS_NAME);
		logger.trace("WebLogic ClientTransactionManager found");

		this.weblogicTransactionManagerAvailable = transactionManagerClass.isInstance(getTransactionManager());
		if (this.weblogicTransactionManagerAvailable) {
			Class<?> transactionClass = getClass().getClassLoader().loadClass(TRANSACTION_CLASS_NAME);
			this.forceResumeMethod = transactionManagerClass.getMethod("forceResume", Transaction.class);
			this.setPropertyMethod = transactionClass.getMethod("setProperty", String.class, Serializable.class);
			logger.debug("Support for WebLogic forceResume available");
		}
		else {
			logger.debug("Support for WebLogic forceResume not available");
		}
	}
	catch (Exception ex) {
		throw new TransactionSystemException(
				"Could not initialize WebLogicJtaTransactionManager because WebLogic API classes are not available",
				ex);
	}
}
 
Example 20
Source Project: scipio-erp   Source File: TransactionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
* Remove the stamp from stack (when resuming)
*/
private static void popTransactionStartStamp() {
    ListOrderedMap<Transaction, Timestamp> map = (ListOrderedMap<Transaction, Timestamp>) suspendedTxStartStamps.get();
    if (map.size() > 0) {
        transactionStartStamp.set((Timestamp) map.remove(map.lastKey()));
    } else {
        Debug.logError("Error in transaction handling - no saved start stamp found - using NOW.", module);
        transactionStartStamp.set(UtilDateTime.nowTimestamp());
    }
}
 
Example 21
Source Project: spring-analysis-note   Source File: JtaTransactionManager.java    License: MIT License 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(@Nullable JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example 22
Source Project: spring-analysis-note   Source File: JtaTransactionManager.java    License: MIT License 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations a List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 23
/**
 * {@inheritDoc}
 */
public void begin() throws NotSupportedException,
                           SystemException
{
   Transaction tx = registry.getTransaction();
   
   if (tx != null)
      throw new NotSupportedException();

   registry.startTransaction();
}
 
Example 24
Source Project: tomee   Source File: StatefulContainer.java    License: Apache License 2.0 5 votes vote down vote up
private Transaction getTransaction(final ThreadContext callContext) {
    final TransactionPolicy policy = callContext.getTransactionPolicy();

    Transaction currentTransaction = null;
    if (policy instanceof JtaTransactionPolicy) {
        final JtaTransactionPolicy jtaPolicy = (JtaTransactionPolicy) policy;

        currentTransaction = jtaPolicy.getCurrentTransaction();
    }
    return currentTransaction;
}
 
Example 25
Source Project: spring-analysis-note   Source File: JtaTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);
	willThrow(new SystemException()).given(ut).begin();

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	verify(tm).resume(tx);
}
 
Example 26
Source Project: AsuraFramework   Source File: JTANonClusteredSemaphore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Release the lock on the identified resource if it is held by the calling
 * thread, unless currently in a JTA transaction.
 * 
 * @param fromSynchronization True if this method is being invoked from
 *      <code>{@link Synchronization}</code> notified of the enclosing 
 *      transaction having completed.
 * 
 * @throws LockException Thrown if there was a problem accessing the JTA 
 *      <code>Transaction</code>.  Only relevant if <code>fromSynchronization</code>
 *      is false.
 */
protected synchronized void releaseLock(
    String lockName, boolean fromSynchronization) throws LockException {
    lockName = lockName.intern();

    if (isLockOwner(null, lockName)) {
        
        if (fromSynchronization == false) {
            Transaction t = getTransaction();
            if (t != null) {
                if(getLog().isDebugEnabled()) {
                    getLog().debug(
                        "Lock '" + lockName + "' is in a JTA transaction.  " + 
                        "Return deferred by: " + Thread.currentThread().getName());
                }
                
                // If we are still in a transaction, then we don't want to 
                // actually release the lock.
                return;
            }
        }
        
        if(getLog().isDebugEnabled()) {
            getLog().debug(
                "Lock '" + lockName + "' returned by: "
                        + Thread.currentThread().getName());
        }
        getThreadLocks().remove(lockName);
        locks.remove(lockName);
        this.notify();
    } else if (getLog().isDebugEnabled()) {
        getLog().debug(
            "Lock '" + lockName + "' attempt to return by: "
                    + Thread.currentThread().getName()
                    + " -- but not owner!",
            new Exception("stack-trace of wrongful returner"));
    }
}
 
Example 27
Source Project: java-technology-stack   Source File: JtaTransactionManager.java    License: MIT License 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(@Nullable JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example 28
Source Project: tomee   Source File: Instance.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void setTransaction(final Transaction transaction) {
    if (this.transaction.size() == 0 && transaction != null) {
        lock.lock();
        this.transaction.push(transaction);
    } else if (this.transaction.size() != 0 && transaction == null) {
        this.transaction.pop();
        lock.unlock();
    } else if (transaction != null) {
        this.transaction.push(transaction);
    }
}
 
Example 29
Source Project: gemfirexd-oss   Source File: TXManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public static void setCurrentJTA(final Transaction tx) {
  TXContext context = txContext.get();
  if (tx != null) {
    if (context == null) {
      context = TXContext.newContext();
    }
    context.setJTA(tx);
    return;
  }
  if (context != null) {
    context.clearJTA();
  }
}
 
Example 30
Source Project: ignite   Source File: WebSphereTmFactory.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Transaction getTransaction() throws SystemException {
    Transaction tx = mgr.getTransaction();

    if (tx == null)
        return null;

    return new WebSphereTransaction(tx);
}