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

The following examples show how to use javax.transaction.TransactionManager#getStatus() . 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: DSSXATransactionManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public boolean isInDTX() {
    TransactionManager txManager = getTransactionManager();
    if (txManager == null) {
           return false;
       }
	try {
	    return txManager.getStatus() != Status.STATUS_NO_TRANSACTION;
	} catch (Exception e) {
		log.error("Error at 'hasNoActiveTransaction'", e);
		return false;
	}
}
 
Example 2
Source File: LobCreatorUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a transaction synchronization for closing the given LobCreator,
 * preferring Spring transaction synchronization and falling back to
 * plain JTA transaction synchronization.
 * @param lobCreator the LobCreator to close after transaction completion
 * @param jtaTransactionManager the JTA TransactionManager to fall back to
 * when no Spring transaction synchronization is active (may be {@code null})
 * @throws IllegalStateException if there is neither active Spring transaction
 * synchronization nor active JTA transaction synchronization
 */
public static void registerTransactionSynchronization(
		LobCreator lobCreator, TransactionManager jtaTransactionManager) throws IllegalStateException {

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering Spring transaction synchronization for LobCreator");
		TransactionSynchronizationManager.registerSynchronization(
			new SpringLobCreatorSynchronization(lobCreator));
	}
	else {
		if (jtaTransactionManager != null) {
			try {
				int jtaStatus = jtaTransactionManager.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for LobCreator");
					jtaTransactionManager.getTransaction().registerSynchronization(
							new JtaLobCreatorSynchronization(lobCreator));
					return;
				}
			}
			catch (Throwable ex) {
				throw new TransactionSystemException(
						"Could not register synchronization with JTA TransactionManager", ex);
			}
		}
		throw new IllegalStateException("Active Spring transaction synchronization or active " +
			"JTA transaction with specified [javax.transaction.TransactionManager] required");
	}
}
 
Example 3
Source File: JtaStatusHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract the status code from the current {@link javax.transaction.Transaction} associated with the
 * given {@link TransactionManager}
 *
 * @param transactionManager The {@link TransactionManager} from which to extract the status.
 *
 * @return The transaction status
 *
 * @throws TransactionException If the {@link TransactionManager} reports the status as unknown
 */
public static int getStatus(TransactionManager transactionManager) {
	try {
		final int status = transactionManager.getStatus();
		if ( status == Status.STATUS_UNKNOWN ) {
			throw new TransactionException( "TransactionManager reported transaction status as unknwon" );
		}
		return status;
	}
	catch ( SystemException se ) {
		throw new TransactionException( "Could not determine transaction status", se );
	}
}
 
Example 4
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 5
Source File: LobCreatorUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register a transaction synchronization for closing the given LobCreator,
 * preferring Spring transaction synchronization and falling back to
 * plain JTA transaction synchronization.
 * @param lobCreator the LobCreator to close after transaction completion
 * @param jtaTransactionManager the JTA TransactionManager to fall back to
 * when no Spring transaction synchronization is active (may be {@code null})
 * @throws IllegalStateException if there is neither active Spring transaction
 * synchronization nor active JTA transaction synchronization
 */
public static void registerTransactionSynchronization(
		LobCreator lobCreator, TransactionManager jtaTransactionManager) throws IllegalStateException {

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering Spring transaction synchronization for LobCreator");
		TransactionSynchronizationManager.registerSynchronization(
			new SpringLobCreatorSynchronization(lobCreator));
	}
	else {
		if (jtaTransactionManager != null) {
			try {
				int jtaStatus = jtaTransactionManager.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for LobCreator");
					jtaTransactionManager.getTransaction().registerSynchronization(
							new JtaLobCreatorSynchronization(lobCreator));
					return;
				}
			}
			catch (Throwable ex) {
				throw new TransactionSystemException(
						"Could not register synchronization with JTA TransactionManager", ex);
			}
		}
		throw new IllegalStateException("Active Spring transaction synchronization or active " +
			"JTA transaction with specified [javax.transaction.TransactionManager] required");
	}
}
 
Example 6
Source File: LobCreatorUtils.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Register a transaction synchronization for closing the given LobCreator,
 * preferring Spring transaction synchronization and falling back to
 * plain JTA transaction synchronization.
 * @param lobCreator the LobCreator to close after transaction completion
 * @param jtaTransactionManager the JTA TransactionManager to fall back to
 * when no Spring transaction synchronization is active (may be {@code null})
 * @throws IllegalStateException if there is neither active Spring transaction
 * synchronization nor active JTA transaction synchronization
 */
public static void registerTransactionSynchronization(
		LobCreator lobCreator, TransactionManager jtaTransactionManager) throws IllegalStateException {

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering Spring transaction synchronization for LobCreator");
		TransactionSynchronizationManager.registerSynchronization(
			new SpringLobCreatorSynchronization(lobCreator));
	}
	else {
		if (jtaTransactionManager != null) {
			try {
				int jtaStatus = jtaTransactionManager.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for LobCreator");
					jtaTransactionManager.getTransaction().registerSynchronization(
							new JtaLobCreatorSynchronization(lobCreator));
					return;
				}
			}
			catch (Throwable ex) {
				throw new TransactionSystemException(
						"Could not register synchronization with JTA TransactionManager", ex);
			}
		}
		throw new IllegalStateException("Active Spring transaction synchronization or active " +
			"JTA transaction with specified [javax.transaction.TransactionManager] required");
	}
}
 
Example 7
Source File: ManagedBeanTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private boolean inTransaction() {
    try {
        final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
        final int status = transactionManager.getStatus();
        return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
    } catch (final SystemException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
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 9
Source File: CommonDataAccess.java    From mdw with Apache License 2.0 4 votes vote down vote up
/**
 * Should only be used with MDW data source
 */
@SuppressWarnings("squid:S2095")
public TransactionWrapper startTransaction() throws DataAccessException {
    TransactionWrapper transaction = new TransactionWrapper();
    TransactionUtil transUtil = TransactionUtil.getInstance();
    TransactionManager transManager = transUtil.getTransactionManager();
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("startTransaction - transaction manager=" + transManager.hashCode() + " (status=" + transManager.getStatus() + ")");
        }
        transaction.setDatabaseAccess(db);
        if (transManager.getStatus()==Status.STATUS_NO_TRANSACTION) {
            transaction.setTransactionAlreadyStarted(false);
            // Get connection BEFORE beginning transaction to avoid transaction timeout (10 minutes) exceptions (Fail to stop the transaction)
            db.openConnection().setAutoCommit(false); // Also set autoCommit to false
            transManager.begin();
            transUtil.setCurrentConnection(db.getConnection());
        } else {
            if (logger.isTraceEnabled())
                logger.trace("   ... transaction already started, status=" + transManager.getStatus());
            transaction.setTransactionAlreadyStarted(true);
            if (db.connectionIsOpen()) {
                transaction.setDatabaseConnectionAlreadyOpened(true);
            } else {
                if (logger.isTraceEnabled())
                    logger.trace("   ... but database is not open");
                // not opened through this DatabaseAccess
                transaction.setDatabaseConnectionAlreadyOpened(false);
                if (transUtil.getCurrentConnection() == null) {
                    db.openConnection().setAutoCommit(false);  // Set autoCommit to false
                    transUtil.setCurrentConnection(db.getConnection());
                } else {
                    db.setConnection(transUtil.getCurrentConnection());
                }
            }
        }
        transaction.setTransaction(transManager.getTransaction());
        return transaction;
    } catch (Throwable e) {
        if (transaction.getTransaction()!=null) stopTransaction(transaction);
        throw new DataAccessException(0, "Fail to start transaction", e);
    }
}
 
Example 10
Source File: TransactionUtil.java    From mdw with Apache License 2.0 4 votes vote down vote up
public boolean isInTransaction() throws SystemException {
    TransactionManager transManager = getTransactionManager();
    return (transManager.getStatus()==Status.STATUS_ACTIVE);
}
 
Example 11
Source File: LazyUserTransaction.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected static String buildLazyTxExp() {
    final int status;
    try {
        final TransactionManager manager = ContainerUtil.getComponent(TransactionManager.class); // for static use
        status = manager.getStatus();
    } catch (SystemException e) {
        throw new IllegalStateException("Failed to get status from transaction manager.", e);
    }
    final String statusExp;
    if (status == Status.STATUS_ACTIVE) {
        statusExp = "Active";
    } else if (status == Status.STATUS_MARKED_ROLLBACK) {
        statusExp = "MarkedRollback";
    } else if (status == Status.STATUS_PREPARED) {
        statusExp = "Prepared";
    } else if (status == Status.STATUS_COMMITTED) {
        statusExp = "Committed";
    } else if (status == Status.STATUS_ROLLEDBACK) {
        statusExp = "RolledBack";
    } else if (status == Status.STATUS_UNKNOWN) {
        statusExp = "Unknown";
    } else if (status == Status.STATUS_NO_TRANSACTION) {
        statusExp = "NoTransaction";
    } else if (status == Status.STATUS_PREPARING) {
        statusExp = "Preparing";
    } else if (status == Status.STATUS_COMMITTING) {
        statusExp = "Committing";
    } else if (status == Status.STATUS_ROLLING_BACK) {
        statusExp = "RollingBack";
    } else {
        statusExp = String.valueOf(status);
    }
    final StringBuilder sb = new StringBuilder();
    sb.append("[").append(statusExp).append("]");
    boolean secondOrMore = false;
    if (isLazyTransactionReadyLazy()) {
        sb.append(secondOrMore ? ", " : "").append("readyLazy");
        secondOrMore = true;
    }
    if (isLazyTransactionLazyBegun()) {
        sb.append(secondOrMore ? ", " : "").append("lazyBegun");
        secondOrMore = true;
    }
    if (isLazyTransactionRealBegun()) {
        sb.append(secondOrMore ? ", " : "").append("realBegun");
        secondOrMore = true;
    }
    final Integer hierarchyLevel = getCurrentHierarchyLevel();
    if (hierarchyLevel != null) {
        sb.append(secondOrMore ? ", " : "").append("hierarchy=").append(hierarchyLevel);
        secondOrMore = true;
    }
    final List<IndependentProcessor> lazyProcessList = getLazyProcessList();
    if (!lazyProcessList.isEmpty()) {
        sb.append(secondOrMore ? ", " : "").append("lazyProcesses=").append(lazyProcessList.size());
        secondOrMore = true;
    }
    final ForcedlyBegunResumer resumer = getForcedlyBegunResumer();
    if (resumer != null) {
        sb.append(secondOrMore ? ", " : "").append("resumer=").append(DfTypeUtil.toClassTitle(resumer));
        secondOrMore = true;
    }
    return sb.toString();
}
 
Example 12
Source File: AbstractTransactionalConnectionListener.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void delist() throws ResourceException
{
   log.tracef("Delisting: %s", this);
   
   try
   {
      TransactionalConnectionManager txCM = (TransactionalConnectionManager)cm;
      TransactionManager tm = txCM.getTransactionIntegration().getTransactionManager();
      int status = tm.getStatus();

      if (status != Status.STATUS_NO_TRANSACTION && enlisted)
      {
         Transaction tx = tm.getTransaction();
         boolean delistResult = tx.delistResource(xaResource, XAResource.TMSUCCESS);

         if (Tracer.isEnabled())
            Tracer.delistConnectionListener(cm.getPool().getConfiguration().getId(),
                                            getManagedConnectionPool(),
                                            this, tx.toString(),
                                            true, false, false);

         if (delistResult)
         {
            log.tracef("delist-success: %s", this);
         }
         else
         {
            log.debugf("delist-success failed: %s", this);
         }
      }

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

      enlisted = false;
      log.tracef("Delisted: %s", this);
   }
   catch (Exception e)
   {
      throw new ResourceException(e);
   }
}