Java 类javax.transaction.Transaction 实例源码

项目:Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update    文件:TestClass.java   
public static void main(String[] args) {
    Configuration cfg=null;
    SessionFactory factory=null;
    Session ses=null;
    Transaction tx=null;
            cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
            factory=cfg.buildSessionFactory();
        ses=factory.openSession();

         String hql="select item_name from bigbazarModel where bazarid=:id";
         Query q=ses.createQuery(hql);
                q.setParameter("id", 1001);
                    String s=(String) q.uniqueResult();
                    System.out.println("\t\t"+s);

                    factory.close();

}
项目:alfresco-repository    文件:AbstractLuceneIndexerAndSearcherFactory.java   
/**
 * Get the transaction identifier used to store it in the transaction map.
 * 
 * @param tx Transaction
 * @param storeRef StoreRef
 * @return - the transaction id
 */
@SuppressWarnings("unchecked")
private String getTransactionId(Transaction tx, StoreRef storeRef)
{
    if (tx instanceof SimpleTransaction)
    {
        SimpleTransaction simpleTx = (SimpleTransaction) tx;
        return simpleTx.getGUID();
    }
    else if (TransactionSynchronizationManager.isSynchronizationActive())
    {
        Map<StoreRef, LuceneIndexer> indexers = (Map<StoreRef, LuceneIndexer>) AlfrescoTransactionSupport.getResource(indexersKey);
        if (indexers != null)
        {
            LuceneIndexer indexer = indexers.get(storeRef);
            if (indexer != null)
            {
                return indexer.getDeltaId();
            }
        }
    }
    return null;
}
项目:oscm    文件:TransactionInvocationHandlers.java   
/**
 * Suspends the current transaction (if any) during the given handler is
 * called.
 * 
 * @param delegate
 * @return
 */
private static IInvocationHandler suspend(final IInvocationHandler delegate) {
    return new IInvocationHandler() {

        public Object call(Callable<Object> callable,
                IInvocationHandler.IInvocationCtx ctx) throws Exception {
            final Transaction suspended = ctx.getTransactionManager()
                    .suspend();
            try {
                return delegate.call(callable, ctx);
            } finally {
                if (suspended != null) {
                    ctx.getTransactionManager().resume(suspended);
                }
            }
        }
    };
}
项目:monarch    文件:GemFireTransactionDataSource.java   
/**
 * Implementation of call back function from ConnectionEventListener interface. This callback will
 * be invoked on connection close event.
 * 
 * @param event Connection event object
 */
public void connectionClosed(ConnectionEvent event) {
  if (isActive) {
    try {
      XAConnection conn = (XAConnection) event.getSource();
      XAResource xar = (XAResource) xaResourcesMap.get(conn);
      xaResourcesMap.remove(conn);
      Transaction txn = transManager.getTransaction();
      if (txn != null && xar != null)
        txn.delistResource(xar, XAResource.TMSUCCESS);
      provider.returnConnection(conn);
    } catch (Exception e) {
      String exception =
          "GemFireTransactionDataSource::connectionClosed: Exception occured due to " + e;
      if (logger.isDebugEnabled()) {
        logger.debug(exception, e);
      }
    }
  }
}
项目:monarch    文件:GemFireTransactionDataSource.java   
/**
 *  
 */
void registerTranxConnection(XAConnection xaConn) throws Exception {
  try {
    synchronized (this) {
      if (transManager == null) {
        transManager = JNDIInvoker.getTransactionManager();
      }
    }
    Transaction txn = transManager.getTransaction();
    if (txn != null) {
      XAResource xar = xaConn.getXAResource();
      txn.enlistResource(xar);
      // Add in the Map after successful registration of XAResource
      this.xaResourcesMap.put(xaConn, xar);
    }
  } catch (Exception ex) {
    Exception e = new Exception(
        LocalizedStrings.GemFireTransactionDataSource_GEMFIRETRANSACTIONDATASOURCEREGISTERTRANXCONNECTION_EXCEPTION_IN_REGISTERING_THE_XARESOURCE_WITH_THE_TRANSACTIONEXCEPTION_OCCURED_0
            .toLocalizedString(ex));
    e.initCause(ex);
    throw e;
  }
}
项目:monarch    文件:FacetsJCAConnectionManagerImpl.java   
/**
 * 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.getMessage();
      if (logger.isDebugEnabled()) {
        logger.debug(exception, se);
      }
    }
  }
}
项目:monarch    文件:TransactionManagerImpl.java   
/**
 * @see javax.transaction.TransactionManager#suspend()
 */
public Transaction suspend() throws SystemException {
  if (!isActive) {
    throw new SystemException(
        LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGER_INVALID.toLocalizedString());
  }
  Transaction txn = getTransaction();

  if (null != txn) {
    GlobalTransaction gtx = getGlobalTransaction(txn);
    gtx.suspend();
    transactionMap.remove(Thread.currentThread());
    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
    if (writer.infoEnabled())
      writer.info(
          LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPLSUSPENDTRANSACTION_SUSPENDED);
  }

  return txn;
}
项目:monarch    文件:JtaIntegrationJUnitTest.java   
@Test
public void testBug46169() throws Exception {
  String tableName = CacheUtils.init("CacheTest");
  assertFalse(tableName == null || tableName.equals(""));
  logger.debug("Table name: " + tableName);

  logger.debug("init for bug46169 Successful!");
  Cache cache = CacheUtils.getCache();

  TransactionManager xmanager =
      (TransactionManager) cache.getJNDIContext().lookup("java:/TransactionManager");
  assertNotNull(xmanager);

  Transaction trans = xmanager.suspend();
  assertNull(trans);

  try {
    logger.debug("Destroying table: " + tableName);
    CacheUtils.destroyTable(tableName);
    logger.debug("Closing cache...");
    logger.debug("destroyTable for bug46169 Successful!");
  } finally {
    CacheUtils.closeCache();
  }
}
项目:openjdk9    文件:Main.java   
public static void main(String[] args) {

        ClassLoader scl = ClassLoader.getSystemClassLoader();
        ClassLoader pcl = ClassLoader.getPlatformClassLoader();
        assertTrue(pcl.getParent() == null);

        Transaction transaction = new Transaction();
        Scope scope = transaction.getScope();

        // javax.transaction.Transaction should be in module java.transaction
        // and defined by the platform class loader
        assertTrue(Transaction.class.getModule().getName().equals("java.transaction"));
        assertTrue(Transaction.class.getClassLoader() == pcl);

        // javax.enterprise.context.Scope should be in module java.enterprise
        // and defined by the application class loader
        assertTrue(Scope.class.getModule().getName().equals("java.enterprise"));
        assertTrue(Scope.class.getClassLoader() == scl);
    }
项目:scipio-erp    文件:TransactionUtil.java   
public static Transaction suspend() throws GenericTransactionException {
    try {
        if (TransactionUtil.getStatus() != STATUS_NO_TRANSACTION) {
            TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
            if (txMgr != null) {
                pushTransactionBeginStackSave(clearTransactionBeginStack());
                pushSetRollbackOnlyCauseSave(clearSetRollbackOnlyCause());
                Transaction trans = txMgr.suspend();
                pushSuspendedTransaction(trans);
                return trans;
            } else {
                return null;
            }
        } else {
            Debug.logWarning("No transaction in place, so not suspending.", module);
            return null;
        }
    } catch (SystemException e) {
        throw new GenericTransactionException("System error, could not suspend transaction", e);
    }
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithPropagationNotSupported() 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);

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

    verify(tm).resume(tx);
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExisting() 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);

    JtaTransactionManager ptm = newJtaTransactionManager(ut, 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(ut).begin();
    verify(ut).commit();
    verify(tm).resume(tx);
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@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);
}
项目:gemfirexd-oss    文件:JCAConnectionManagerImpl.java   
/**
 * Callback for Connection Closed.
 * 
 * @param event ConnectionEvent Object.
 */
public void connectionClosed(ConnectionEvent event) {
  if (isActive) {
    ManagedConnection conn = (ManagedConnection) event.getSource();
    XAResource xar = null;
    if (xaResourcesMap.get(conn) != null)
        xar = (XAResource) xaResourcesMap.get(conn);
    xaResourcesMap.remove(conn);
    try {
      Transaction txn = transManager.getTransaction();
      if (txn != null && xar != null) {
        txn.delistResource(xar, XAResource.TMSUCCESS);
      }
    }
    catch (Exception se) {
      String exception = "JCAConnectionManagerImpl::connectionClosed: Exception occured due to "
          + se;
      LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
      if (writer.fineEnabled()) writer.fine(exception, se);
    }
    mannPoolCache.returnPooledConnectionToPool(conn);
  }
}
项目:gemfirexd-oss    文件:FacetsJCAConnectionManagerImpl.java   
/**
 * 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);
    }
  }
}
项目:gemfirexd-oss    文件:GlobalTransactionTest.java   
public void testSetRollbackOnly() {
  try {
    utx.begin();
    utx.setRollbackOnly();
    Transaction txn = tm.getTransaction();
    if (txn.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
      utx.rollback();
      fail("testSetRollbackonly failed");
    }
    utx.rollback();
  }
  catch (Exception e) {
    fail("exception in testSetRollbackonly due to " + e);
    e.printStackTrace();
  }
}
项目:JmsTools    文件:XAJmsResourceManager.java   
/**
 * {@inheritDoc}
 */
@Override
public void close() {
    super.close();
    try {
        if (_session != null) {
            Transaction tx = _transactionManager.getTransaction();
            if (tx != null) {
                tx.delistResource(_session.getXAResource(), XAResource.TMFAIL);
                tx.rollback();
            }
        }
    }
    catch (SystemException e) {
        // Ignore
    }
    closeSafely(_session);
    closeSafely(_conn);
}
项目:switchyard    文件:TransactionHandlerTest.java   
@Test
public void propagateRequiredAndProvided() throws Exception {
    PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION);
    PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION);
    exchange.setPhase(ExchangePhase.IN);

    tm.begin();
    Transaction tx = tm.getTransaction();

    handler.handleMessage(exchange);
    exchange.setPhase(ExchangePhase.OUT);
    handler.handleMessage(exchange);

    Transaction tx2 = tm.getTransaction();
    Assert.assertEquals(tx, tx2);
    Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus());
}
项目:cacheonix-core    文件:TreeCache.java   
public void put(Object key, Object value) throws CacheException {
    Transaction tx = suspend();
    try {
        //do the failfast put outside the scope of the JTA txn
        cache.putFailFast( new Fqn( regionFqn, key ), ITEM, value, 0 );
    }
    catch (TimeoutException te) {
        //ignore!
        log.debug("ignoring write lock acquisition failure");
    }
    catch (Exception e) {
        throw new CacheException(e);
    }
    finally {
        resume( tx );
    }
}
项目:lastaflute    文件:ConnectionPoolViewBuilder.java   
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);
        }
    }
}
项目:elpi    文件:TransactionUtil.java   
public static Transaction suspend() throws GenericTransactionException {
    try {
        if (TransactionUtil.getStatus() != STATUS_NO_TRANSACTION) {
            TransactionManager txMgr = TransactionFactory.getTransactionManager();
            if (txMgr != null) {
                pushTransactionBeginStackSave(clearTransactionBeginStack());
                pushSetRollbackOnlyCauseSave(clearSetRollbackOnlyCause());
                Transaction trans = txMgr.suspend();
                pushSuspendedTransaction(trans);
                return trans;
            } else {
                return null;
            }
        } else {
            Debug.logWarning("No transaction in place, so not suspending.", module);
            return null;
        }
    } catch (SystemException e) {
        throw new GenericTransactionException("System error, could not suspend transaction", e);
    }
}
项目:switchyard    文件:TransactionHandlerTest.java   
@Test
public void suspendsAndManagedLocalRequired() throws Exception {
    PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION);
    PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL);
    exchange.setPhase(ExchangePhase.IN);
    tm.begin();
    Transaction tx1 = tm.getTransaction();

    handler.handleMessage(exchange);
    Transaction tx2 = tm.getTransaction();
    Assert.assertNotSame(tx1, tx2);
    Assert.assertEquals(Status.STATUS_ACTIVE, tx1.getStatus());
    Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus());
    Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION));
    Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL));

    exchange.setPhase(ExchangePhase.OUT);
    handler.handleMessage(exchange);
    Transaction tx3 = tm.getTransaction();
    Assert.assertEquals(tx1, tx3);
    Assert.assertEquals(Status.STATUS_COMMITTED, tx2.getStatus());
    Assert.assertEquals(Status.STATUS_ACTIVE, tx3.getStatus());
}
项目:jacis    文件:AbstractJacisTransactionAdapterJTA.java   
protected boolean isJtaTransactionActive(Transaction tx) {
  try {
    if (tx == null) {
      return false;
    }
    int status = tx.getStatus();
    status = Status.STATUS_UNKNOWN == status ? tx.getStatus() : status; // if status unknown (transient state) -> call again
    switch (status) {
    case Status.STATUS_NO_TRANSACTION:
      return false;
    case Status.STATUS_COMMITTED:
      return transactionMap.get(tx) != null; // if state is committed we consider the Jacis TX to be still active (if there is one) since the sync committing the Jacis changes may still stand out
    case Status.STATUS_ROLLEDBACK:
      return transactionMap.get(tx) != null;
    }
    return true;
  } catch (SystemException e) {
    throw new JacisTransactionException(e);
  }
}
项目:gemfirexd-oss    文件:JCAConnectionManagerImpl.java   
/**
 * Callback for Connection Closed.
 * 
 * @param event ConnectionEvent Object.
 */
public void connectionClosed(ConnectionEvent event) {
  if (isActive) {
    ManagedConnection conn = (ManagedConnection) event.getSource();
    XAResource xar = null;
    if (xaResourcesMap.get(conn) != null)
        xar = (XAResource) xaResourcesMap.get(conn);
    xaResourcesMap.remove(conn);
    try {
      Transaction txn = transManager.getTransaction();
      if (txn != null && xar != null) {
        txn.delistResource(xar, XAResource.TMSUCCESS);
      }
    }
    catch (Exception se) {
      String exception = "JCAConnectionManagerImpl::connectionClosed: Exception occured due to "
          + se;
      LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
      if (writer.fineEnabled()) writer.fine(exception, se);
    }
    mannPoolCache.returnPooledConnectionToPool(conn);
  }
}
项目:gemfirexd-oss    文件:FacetsJCAConnectionManagerImpl.java   
/**
 * 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);
    }
  }
}
项目:lasta-di    文件:SimpleConnectionPool.java   
protected ConnectionWrapper checkOutFreePool(Transaction tx) {
    if (freePool.isEmpty()) {
        return null;
    }
    final FreeItem item = (FreeItem) freePool.removeLast();
    final ConnectionWrapper wrapper = item.getConnection();
    wrapper.init(tx);
    item.destroy();
    if (validationQuery == null || validationQuery.isEmpty()) {
        return wrapper;
    }
    if (validateConnection(wrapper, item.getPooledTime())) {
        return wrapper;
    }
    return null;
}
项目:switchyard    文件:TransactionHandler.java   
@Override
public void handleFault(Exchange exchange) {
    // if no TM is available, there's nothing to do
    if (_transactionManager == null) {
        return;
    }

    try {
        Property rollbackOnFaultProperty = exchange.getContext().getProperty(Exchange.ROLLBACK_ON_FAULT);
        if (rollbackOnFaultProperty != null && rollbackOnFaultProperty.getValue() != null
                && Boolean.class.cast(rollbackOnFaultProperty.getValue())) {
                Transaction transaction = getCurrentTransaction();
                if (transaction != null) {
                    transaction.setRollbackOnly();
                }
        }
        handleAfter(exchange);
    } catch (Exception e) {
        _log.error(e);
    }
}
项目:activemq-artemis    文件:JMSBridgeImpl.java   
private void enlistResources(final Transaction tx) throws Exception {
   if (JMSBridgeImpl.trace) {
      ActiveMQJMSBridgeLogger.LOGGER.trace("Enlisting resources in tx");
   }

   XAResource resSource = ((XASession) sourceSession).getXAResource();

   tx.enlistResource(resSource);

   XAResource resDest = ((XASession) targetSession).getXAResource();

   tx.enlistResource(resDest);

   if (JMSBridgeImpl.trace) {
      ActiveMQJMSBridgeLogger.LOGGER.trace("Enlisted resources in tx");
   }
}
项目:genericconnector    文件:BasicTransactionAssistanceFactoryImpl.java   
/** before calling this method, please ensure you have called {@link TransactionConfigurator#setup(String, CommitRollbackCallback)} */
@Override
public TransactionAssistant getTransactionAssistant() throws ResourceException {
    //enlist a new resource into the transaction. it will be delisted, when its closed.
    final CommitRollbackCallback commitRollbackCallback = TransactionConfigurator.getCommitRollbackCallback(jndiName);
    MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
    UserTransactionManager utm = getTM();
    try {
        if(utm.getStatus() == Status.STATUS_NO_TRANSACTION){
            throw new ResourceException("no transaction found. please start one before getting the transaction assistant. status was: " + utm.getStatus());
        }
        Transaction tx = utm.getTransaction();
        tx.enlistResource(ms);
        return new AtomikosTransactionAssistantImpl(ms);
    } catch (Exception e) {
        throw new ResourceException("Unable to get transaction status", e);
    }
}
项目:alfresco-repository    文件:SimpleTransactionManager.java   
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException
{
    if (!(tx instanceof SimpleTransaction))
    {
        throw new IllegalStateException("Transaction must be a SimpleTransaction to resume");
    }
    SimpleTransaction.resume((SimpleTransaction) tx);
}
项目:aries-jpa    文件:TransactionToken.java   
TransactionToken(Transaction activeTransaction, Transaction suspendedTransaction,
        TransactionAttribute transactionAttribute, boolean isCompletionAllowed)
{
    this.activeTransaction = activeTransaction;
    this.suspendedTransaction = suspendedTransaction;
    this.transactionAttribute = transactionAttribute;
    this.isCompletionAllowed = isCompletionAllowed;
}
项目:lams    文件:WebLogicJtaTransactionManager.java   
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);
    }
}
项目:lams    文件:JtaTransactionManager.java   
/**
 * 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(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);
}
项目:lams    文件:JtaTransactionManager.java   
/**
 * 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 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);
    }
}
项目:lams    文件:JtaTransactionManager.java   
@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);
}
项目:lams    文件:SimpleTransactionFactory.java   
@Override
public Transaction createTransaction(String name, int timeout) throws NotSupportedException, SystemException {
    if (timeout >= 0) {
        this.transactionManager.setTransactionTimeout(timeout);
    }
    this.transactionManager.begin();
    return new ManagedTransactionAdapter(this.transactionManager);
}
项目:lams    文件:JTANonClusteredSemaphore.java   
/**
 * 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"));
    }
}
项目:unitimes    文件:ReplicatedServer.java   
private boolean inTransaction() {
    try {
        Transaction tx = getTransactionManager().getTransaction();
        return tx != null && tx.getStatus() == Status.STATUS_ACTIVE;
    } catch (SystemException e) {
        return false;
    }
}
项目:asura    文件:JTANonClusteredSemaphore.java   
/**
 * 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"));
    }
}
项目:agroal    文件:NarayanaTransactionIntegration.java   
private boolean transactionRunning() throws SQLException {
    try {
        Transaction transaction = transactionManager.getTransaction();
        return transaction != null && ( transaction.getStatus() == STATUS_ACTIVE || transaction.getStatus() == STATUS_MARKED_ROLLBACK );
    } catch ( Exception e ) {
        throw new SQLException( "Exception in retrieving existing transaction", e );
    }
}