javax.transaction.Transaction Java Examples

The following examples show how to use javax.transaction.Transaction. 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: ConnectionPoolViewBuilder.java    From lastaflute with 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 #2
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: TxUtils.java    From lams with 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 #4
Source File: PseudoTransactionService.java    From tomee with 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 #5
Source File: TransactionManagerImpl.java    From lams with 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 #6
Source File: ContextEndpoint.java    From quarkus with 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 #7
Source File: ContextServiceImpl.java    From tomee with 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 #8
Source File: TransactionScopedTest.java    From quarkus with 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 #9
Source File: TransactionManagerImpl.java    From ironjacamar with Eclipse Public License 1.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 #10
Source File: FacetsJCAConnectionManagerImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: TransactionalInterceptorBase.java    From quarkus with 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 #12
Source File: TransactionContext.java    From quarkus with 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 #13
Source File: FacetsJCAConnectionManagerImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source File: UserTransactionImpl.java    From lams with 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 #15
Source File: TransactionManagerMock.java    From seed with 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 #16
Source File: WebLogicJtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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.info("Support for WebLogic transaction names available");
		}
		else {
			logger.info("Support for WebLogic transaction names not available");
		}

		// Obtain WebLogic ClientTransactionManager interface.
		Class<?> transactionManagerClass =
				getClass().getClassLoader().loadClass(CLIENT_TRANSACTION_MANAGER_CLASS_NAME);
		logger.debug("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.warn("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 #17
Source File: TransactionContext.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Transaction getCurrentTransaction() {
    try {
        return transactionManager.getTransaction();
    } catch (SystemException e) {
        throw new RuntimeException("Error getting the current transaction", e);
    }
}
 
Example #18
Source File: JtaTransactionContext.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected Transaction getTransaction() {
  try {
    return transactionManager.getTransaction();
  } catch (SystemException e) {
    throw new ActivitiException("SystemException while getting transaction ", e);
  }
}
 
Example #19
Source File: WebLogicJtaTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 File: GlobalTransactionTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testSuspend() {
    try {
      utx.begin();
//      Transaction txn = tm.getTransaction();
      tm.suspend();
      Transaction txn1 = tm.getTransaction();
      if (txn1 != null)
        fail("suspend failed to suspend the transaction");
    }
    catch (Exception e) {
      fail("exception in testSuspend due to " + e);
      e.printStackTrace();
    }
  }
 
Example #21
Source File: TransactionUtil.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current transaction
 */
public Transaction getTransaction() {
    try {
        return getTransactionManager().getTransaction();
    }
    catch (Exception ex) {
        StandardLogger logger = LoggerUtil.getStandardLogger();
        logger.error(ex.getMessage(), ex);
        return null;
    }
}
 
Example #22
Source File: JtaTransactionManager.java    From spring-analysis-note with 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
Source File: JtaTransactionInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private Transaction doSuspend() {
  try {
    return transactionManager.suspend();
  } catch (SystemException e) {
    throw new TransactionException("Unable to suspend transaction", e);
  }
}
 
Example #24
Source File: RequiresNewJtaTransactionPolicy.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final Runnable runnable) throws Throwable {
    Transaction suspendedTransaction = null;
    try {
        suspendedTransaction = suspendTransaction();
        runWithTransaction(runnable, true);
    } finally {
        resumeTransaction(suspendedTransaction);
    }
}
 
Example #25
Source File: JCAConnectionManagerImpl.java    From gemfirexd-oss with 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 #26
Source File: XAStatementHandler.java    From clearpool with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void beforeInvoke(String methodName) throws XAException, SystemException {
  if (this.needTransaction(methodName)) {
    Transaction ts = TransactionManagerImpl.getManager().getTransaction();
    if (ts != null) {
      try {
        XAResource xaRes = this.xaCon.getXAResource();
        ts.enlistResource(xaRes);
      } catch (Exception e) {
        throw new ConnectionPoolException(e);
      }
    }
  }
}
 
Example #27
Source File: SimpleTransactionSynchronizationRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
public Object getResource(final Object key) {
    final Transaction transaction = getActiveTransaction();
    final Map<Object, Object> resources = transactionResources.get(transaction);
    if (resources == null) {
        return null;
    }
    return resources.get(key);
}
 
Example #28
Source File: TransactionManagerImpl.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void begin() throws NotSupportedException,
                           SystemException
{
   Transaction tx = registry.getTransaction();
   
   if (tx != null)
      throw new NotSupportedException();

   registry.startTransaction();
}
 
Example #29
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Transaction createTransaction(String name, int timeout) throws NotSupportedException, SystemException {
	TransactionManager tm = getTransactionManager();
	Assert.state(tm != null, "No JTA TransactionManager available");
	if (timeout >= 0) {
		tm.setTransactionTimeout(timeout);
	}
	tm.begin();
	return new ManagedTransactionAdapter(tm);
}
 
Example #30
Source File: JtaTransactionInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private Transaction doSuspend() {
  try {
    return transactionManager.suspend();
  } catch (SystemException e) {
    throw new TransactionException("Unable to suspend transaction", e);
  }
}