Java Code Examples for javax.transaction.UserTransaction#rollback()

The following examples show how to use javax.transaction.UserTransaction#rollback() . 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: PolicyComponentTransactionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void behaviourHierarchyNodeTestWork(QName createDocType, QName... disableTypes) throws Exception
{
    UserTransaction transaction = trxService.getUserTransaction();
    try
    {
        transaction.begin();
        NodeRef nodeRef = createDocOfType(createDocType);
        disableBehaviours(nodeRef, disableTypes);
        try
        {
            nodeService.addAspect(nodeRef, ASPECT, null);
        }
        finally
        {
            enableBehaviours(nodeRef, disableTypes);
        }
        transaction.commit();
    }
    catch(Exception e)
    {
        try { transaction.rollback(); } catch (IllegalStateException ee) {}
        throw e;
    }
}
 
Example 2
Source File: TransactionAwareSingletonTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testCommit() throws Throwable
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        singleton.put(INTEGER_ONE);
        check(INTEGER_ONE, true);
        check(null, false);

        // commit
        txn.commit();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
    check(INTEGER_ONE, true);
    check(INTEGER_ONE, false);
}
 
Example 3
Source File: TransactionAwareSingletonTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testRollback() throws Throwable
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        singleton.put(INTEGER_TWO);
        check(INTEGER_TWO, true);
        check(null, false);

        // rollback
        txn.rollback();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
    check(null, true);
    check(null, false);
}
 
Example 4
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Starts off with a <tt>null</tt> in the backing cache and adds a value to the
 * transactional cache.  There should be no problem with this.
 */
public void testNullValue() throws Throwable
{
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    txn.begin();
    
    TransactionalCache.putSharedCacheValue(backingCache, "A", null, null);
    transactionalCache.put("A", "AAA");
    
    try
    {
        txn.commit();
    }
    catch (Throwable e)
    {
        try {txn.rollback();} catch (Throwable ee) {}
        throw e;
    }
}
 
Example 5
Source File: SiteServiceTestHuge.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createUser(String userName) throws Exception
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        authenticationService.createAuthentication(userName, userName.toCharArray());

        PropertyMap ppOne = new PropertyMap(4);
        ppOne.put(ContentModel.PROP_USERNAME, userName);
        ppOne.put(ContentModel.PROP_FIRSTNAME, userName.substring(0, userName.length()-4));
        ppOne.put(ContentModel.PROP_LASTNAME, "user");
        ppOne.put(ContentModel.PROP_EMAIL, userName + "@email.com");
        ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");

        personService.createPerson(ppOne);

        txn.commit();
    }
    catch (Exception e)
    {
        txn.rollback();
        throw e;
    }
}
 
Example 6
Source File: SiteServiceTestHuge.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createGroup(String groupName) throws Exception
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        authorityService.createAuthority(AuthorityType.GROUP, groupName);

        txn.commit();
    }
    catch (Exception e)
    {
        txn.rollback();
        throw e;
    }
}
 
Example 7
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunWithTxnOfExecutingThread() throws SystemException, NotSupportedException {
    ThreadContext threadContext = ThreadContext.builder()
            .propagated()
            .unchanged(ThreadContext.TRANSACTION)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    UserTransaction ut = getUserTransaction("testRunWithTxnOfExecutingThread");

    if (threadContext == null || ut == null) {
        return; // the implementation does not support transaction propagation
    }

    Callable<Boolean> isInTransaction =
            threadContext.contextualCallable(() -> ut.getStatus() == Status.STATUS_ACTIVE);

    ut.begin();

    try {
        Assert.assertTrue(isInTransaction.call());
    }
    catch (Exception e) {
        Assert.fail("testRunWithTxnOfExecutingThread: a transaction should have been active");
    }
    finally {
        ut.rollback();
    }
}
 
Example 8
Source File: XAProducerBMTSB.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage() throws JMSException {

    System.out.println("Sending reply message");
    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;
    UserTransaction ux = sessionContext.getUserTransaction();

    try {
        ux.begin();
        conn = myCF.createConnection();
        session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);
        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
        ux.commit();
    } catch (Exception e) {
        e.printStackTrace();
        try {
           ux.rollback();
        } catch (Exception ex) {
           throw new EJBException(
            "rollback failed: " + ex.getMessage(), ex);
        }
    } finally {
        if (prod != null)
      prod.close();
        if (session != null)
      session.close();
        if (conn != null)
      conn.close();
    }
}
 
Example 9
Source File: ReplicationServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check that the locking works.
 * Take a 10 second lock on the job, then execute.
 * Ensure that we really wait a little over 10 seconds.
 */
public void testReplicationExecutionLocking() throws Exception
{
   // We need the test transfer target for this test
   makeTransferTarget();

   // Create a task
   ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
   rd.setTargetName(TRANSFER_TARGET);
   rd.getPayload().add(folder1);
   rd.getPayload().add(folder2);
   
   // Get the lock, and run
   long start = System.currentTimeMillis();
   String token = jobLockService.getLock(
         rd.getReplicationQName(),
         10 * 1000,
         1,
         1
   );
   
   UserTransaction txn = transactionService.getUserTransaction();
   txn.begin();
   try {
       actionService.executeAction(rd, replicationRoot);
   } catch(ReplicationServiceException e) {
       // This shouldn't happen normally! Something is wrong!
       // Tidy up before we throw the exception
       txn.rollback();
       throw e;
   }
   txn.commit();
   long end = System.currentTimeMillis();
   
   assertTrue(
        "Should wait for the lock, but didn't (waited " + 
           ((end-start)/1000.0) + " seconds, not 10)",
        end-start > 10000
   );
}
 
Example 10
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Time how long it takes to create and complete a whole lot of transactions
 */
public void testInitializationPerformance() throws Exception
{
    TransactionService transactionService = serviceRegistry.getTransactionService();
    long start = System.nanoTime();
    int count = 10000;
    for (int i = 0; i < count; i++)
    {
        UserTransaction txn = transactionService.getUserTransaction();
        try
        {
            txn.begin();
            transactionalCache.contains("A");
        }
        finally
        {
            try { txn.rollback(); } catch (Throwable ee) {ee.printStackTrace();}
        }
    }
    long end = System.nanoTime();
    
    // report
    System.out.println(
            "Cache initialization performance test: \n" +
            "   count:       " + count + "\n" +
            "   transaction: " + (end-start)/((long)count) + " ns\\count"); 
}
 
Example 11
Source File: DbNodeServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void executeAndCheck(NodeRef nodeRef, RetryingTransactionCallback<Object> callback) throws Throwable
{
    UserTransaction txn = txnService.getUserTransaction();
    txn.begin();
    
    NodeRef.Status currentStatus = nodeService.getNodeStatus(nodeRef);
    assertNotNull(currentStatus);
    String currentTxnId = AlfrescoTransactionSupport.getTransactionId();
    assertNotNull(currentTxnId);
    assertNotSame(currentTxnId, currentStatus.getChangeTxnId());
    try
    {
        callback.execute();
        // get the status
        NodeRef.Status newStatus = nodeService.getNodeStatus(nodeRef);
        assertNotNull(newStatus);
        // check
        assertEquals("Change didn't update status", currentTxnId, newStatus.getChangeTxnId());
        
        // Make sure we can pre-load the node i.e. nodes in all state need to be pre-loadable
        // See CLOUD-1807
        Long nodeId = newStatus.getDbId();
        nodeDAO.getParentAssocs(nodeId, null, null, null, new DummyChildAssocRefQueryCallback());
        nodeDAO.cacheNodesById(Collections.singletonList(nodeId));
        
        txn.commit();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
}
 
Example 12
Source File: PolicyComponentTransactionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for MNT-13836 (new API)
 * @throws Exception
 */
public void testIsEnabled1() throws Exception
{
    UserTransaction transaction = trxService.getUserTransaction();
    try
    {
        transaction.begin();
        disableBehaviours(new ClassFilter(B_TYPE, true));
        try
        {
            assertEquals("Incorrect behaviour state: global: ", true, behaviourFilter.isEnabled());
            // A_TYPE
            assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(A_TYPE));
            assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, A_TYPE));
            assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome));
            // B_TYPE
            assertEquals("Incorrect behaviour state: class: ", false, behaviourFilter.isEnabled(B_TYPE));
            assertEquals("Incorrect behaviour state: classAndInstance", false, behaviourFilter.isEnabled(companyHome, B_TYPE));
            assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome));
            // C_TYPE
            assertEquals("Incorrect behaviour state: class: ", false, behaviourFilter.isEnabled(C_TYPE));
            assertEquals("Incorrect behaviour state: classAndInstance", false, behaviourFilter.isEnabled(companyHome, C_TYPE));
            assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome));
        }
        finally
        {
            behaviourFilter.enableBehaviour(B_TYPE);
        }
        transaction.commit();
    }
    catch(Exception e)
    {
        try { transaction.rollback(); } catch (IllegalStateException ee) {}
        throw e;
    }

}
 
Example 13
Source File: VersionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void behaviourVersionTestWork(boolean revert, boolean disableBehaviour, boolean disableBehaviourNode)
        throws Exception
{
    UserTransaction transaction = transactionService.getUserTransaction();
    try
    {
        transaction.begin();
        NodeRef nodeRef = createNode(false, TEST_TYPE_QNAME);
        if (revert)
        {
            createVersion(nodeRef);
        }
        if (disableBehaviour)
        {
            if (disableBehaviourNode)
            {
                policyBehaviourFilter.disableBehaviour(nodeRef, TEST_TYPE_QNAME);
            }
            else
            {
                policyBehaviourFilter.disableBehaviour(TEST_TYPE_QNAME);
            }
        }
        try
        {
            if (revert)
            {
                versionService.revert(nodeRef);
            }
            else
            {
                createVersion(nodeRef);
            }
        }
        finally
        {
            if (disableBehaviour)
            {
                if (disableBehaviourNode)
                {
                    policyBehaviourFilter.enableBehaviour(nodeRef, TEST_TYPE_QNAME);
                }
                else
                {
                    policyBehaviourFilter.enableBehaviour(TEST_TYPE_QNAME);
                }
            }
        }
        transaction.commit();
    }
    catch (Exception e)
    {
        try
        {
            transaction.rollback();
        }
        catch (IllegalStateException ee)
        {
        }
        throw e;
    }
}
 
Example 14
Source File: BMXATestBean.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@RemoteMethod
  public void testXACommitRollbackWithJMS(boolean toCommit, int dstype) throws GemFireXDXATestException {
JMSQueueHelper jms = null;
      Connection gfxdConn = null;

      try {
          Context ictx = new InitialContext();
          Context env = (Context) ictx.lookup("java:comp/env");

          String queueConnFactoryName = (String) env.lookup("queueConnFactoryName");
          String queueName = (String) env.lookup("queueName");
	jms = new JMSQueueHelper(ictx, queueConnFactoryName, queueName);
	jms.init();

          String gfxdXADSName = (String) env.lookup(getGemFireXDDSName(dstype));
          DataSource gfxdxads = (DataSource) ictx.lookup(gfxdXADSName);
          gfxdConn = gfxdxads.getConnection();

          String tableName = (String) env.lookup("tableName");

          UserTransaction utx = getSessionContext().getUserTransaction();
          utx.begin();
          log("BM TRANSACTION BEGUN");
          String msgText = jms.receive();
	if (msgText == null) {
		log("***WARN!! Message is null**** ");
		return;
	} else {
		updateDatabase(gfxdConn, tableName, msgText);
	}
	if (toCommit) {
		utx.commit();
		log("BM TRANSACTION COMMIT");
	} else {
		utx.rollback();
		log("BM TRANSACTION ROLLBACK");
	}

      } catch (NamingException nex) {
          log("Naming exception: " + nex);
          throw new GemFireXDXATestException("Failed in test setting: ", nex);
      } catch (JMSException jex) {
          log("JMS exception: " + jex);
          throw new GemFireXDXATestException("Failed in test setting: ", jex);
      } catch (SQLException sqle) {
          log("SQL exception: " + sqle);
          throw new GemFireXDXATestException("Failed in test setting: ", sqle);
      } catch (Exception e) {
          log("EXCEPTION: " + e);
      } finally {
	jms.closeReceiver();
          if (gfxdConn != null) {
              try {
                  gfxdConn.close();
              } catch (SQLException ex) {
              }
	}
      }
  }
 
Example 15
Source File: AbstractLockStoreTxTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testCanChangeLockIfLatestValueIsHeldEvenIfAlreadyChangedByAnotherTx() throws NotSupportedException, SystemException
{
    final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
    UserTransaction txA = txService.getUserTransaction();
    final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
    final Date now = new Date();
    Date expired = new Date(now.getTime() - 180000);
    final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
                "jbloggs", expired, Lifetime.EPHEMERAL, null);
    
    final LockState lockState2 = LockState.createWithOwner(lockState1, "another");
    
    Thread txB = new Thread("TxB")
    {
        @Override
        public void run()
        {
            Object main = AbstractLockStoreTxTest.this;
            UserTransaction tx = txService.getUserTransaction();
            try
            {
                tx.begin();
                try
                {
                    AuthenticationUtil.setFullyAuthenticatedUser("new-user");
                    
                    // txB read lock state
                    LockState readLockState = lockStore.get(nodeRef);
                    assertEquals(lockState2, readLockState);
                    
                    // Set new value, even though txA has already set new values
                    // (but not since this tx's initial read)
                    Date expiresFuture = new Date(now.getTime() + 180000);
                    final LockState newUserLockState = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
                                "new-user", expiresFuture, Lifetime.EPHEMERAL, null);
                    lockStore.set(nodeRef, newUserLockState);
                    
                    // Read
                    assertEquals(newUserLockState, lockStore.get(nodeRef));
                }
                finally
                {
                    tx.rollback();
                }
            }
            catch (Throwable e)
            {
                throw new RuntimeException("Error in transaction B", e);
            }
            finally
            {
                // Stop 'main' from waiting
                synchronized(main)
                {
                    main.notifyAll();
                }
            }
        }  
    };
    
    txA.begin();
    try
    {
        AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner needed to change lock.
        
        // txA set lock state 1
        lockStore.set(nodeRef, lockState1);
        assertEquals(lockState1, lockStore.get(nodeRef));
        
        // txA set different lock state
        lockStore.set(nodeRef, lockState2);
        assertEquals(lockState2, lockStore.get(nodeRef));
        
        // Wait while txB modifies the lock info
        txB.setDaemon(true);
        txB.start();
        passControl(this, txB);
        
        // This tx should still see the same state, though it has been changed by txB.
        assertEquals(lockState2, lockStore.get(nodeRef));
    }
    finally
    {
        txA.rollback();
    }
}
 
Example 16
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testTransactionalCacheStatsOnCommit() throws Throwable
{
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);
    
    
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    
    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);
    
    try
    {
        // begin a transaction
        txn.begin();
        
        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");
        
        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));
        
        // commit the transaction
        txn.commit();

        // TODO: remove is called twice for each remove (in beforeCommit and afterCommit) - check this is correct.
        assertEquals(removesAtStart+16, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(hitsAtStart+3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart+4, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart+5, cacheStats.count("transactionalCache", OpType.PUT));
        // Performing a clear would affect the other stats, so a separate test is required.
        assertEquals(clearsAtStart+0, cacheStats.count("transactionalCache", OpType.CLEAR));
    }
    catch (Throwable e)
    {
        if (txn.getStatus() == Status.STATUS_ACTIVE)
        {
            txn.rollback();
        }
        throw e;
    }
}
 
Example 17
Source File: TradeDirect.java    From sample.daytrader7 with Apache License 2.0 4 votes vote down vote up
/**
 * @see TradeServices#buy(String, String, double)
 */
@Override
public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception {

    final Connection conn = getConn();
    OrderDataBean orderData = null;
    UserTransaction txn = null;
     
    BigDecimal total;

    try {
        if (Log.doTrace()) {
            Log.trace("TradeDirect:buy - inSession(" + this.inSession + ")", userID, symbol, new Double(quantity));
        }

        if (!inSession && orderProcessingMode == TradeConfig.ASYNCH_2PHASE) {
            if (Log.doTrace()) {
                Log.trace("TradeDirect:buy create/begin global transaction");
            }
            // FUTURE the UserTransaction be looked up once
            txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction");
            txn.begin();
            setInGlobalTxn(true);
        }

       //conn = getConn();

        AccountDataBean accountData = getAccountData(conn, userID);
        QuoteDataBean quoteData = getQuoteData(conn, symbol);
        HoldingDataBean holdingData = null; // the buy operation will create
        // the holding

        orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity);

        // Update -- account should be credited during completeOrder
        BigDecimal price = quoteData.getPrice();
        BigDecimal orderFee = orderData.getOrderFee();
        total = (new BigDecimal(quantity).multiply(price)).add(orderFee);
        // subtract total from account balance
        creditAccountBalance(conn, accountData, total.negate());
        final Integer orderID = orderData.getOrderID();
        
        try {
            
            if (orderProcessingMode == TradeConfig.SYNCH) {
                completeOrder(conn,orderID);
            } else  {
                commit(conn);
                queueOrder(orderID, true); // 2-phase
            }
        } catch (JMSException je) {
            Log.error("TradeBean:buy(" + userID + "," + symbol + "," + quantity + ") --> failed to queueOrder", je);
            /* On exception - cancel the order */

            cancelOrder(conn, orderData.getOrderID());
        }

        orderData = getOrderData(conn, orderData.getOrderID().intValue());

        if (txn != null) {
            if (Log.doTrace()) {
                Log.trace("TradeDirect:buy committing global transaction");
            }
            txn.commit();
            setInGlobalTxn(false);
        } else {
            commit(conn);
        }
    } catch (Exception e) {
        Log.error("TradeDirect:buy error - rolling back", e);
        if (getInGlobalTxn()) {
            txn.rollback();
        } else {
            rollBack(conn, e);
        }
    } finally {
        releaseConn(conn);
    }

    return orderData;
}
 
Example 18
Source File: TradeJEEDirect.java    From jboss-daytrader with Apache License 2.0 4 votes vote down vote up
/**
 * @see TradeServices#sell(String, Integer)
 */
public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception {
    Connection conn = null;
    OrderDataBean orderData = null;
    UserTransaction txn = null;

    /*
     * total = (quantity * purchasePrice) + orderFee
     */
    BigDecimal total;

    try {
        if (Log.doTrace())
            Log.trace("TradeDirect:sell - inSession(" + this.inSession + ")", userID, holdingID);

        if (!inSession && orderProcessingMode == TradeConfig.ASYNCH_2PHASE) {
            if (Log.doTrace())
                Log.trace("TradeDirect:sell create/begin global transaction");
            // FUTURE the UserTransaction be looked up once

            txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction");
            txn.begin();
            setInGlobalTxn(true);
        }

        conn = getConn();

        AccountDataBean accountData = getAccountData(conn, userID);
        HoldingDataBean holdingData = getHoldingData(conn, holdingID.intValue());
        QuoteDataBean quoteData = null;
        if (holdingData != null)
            quoteData = getQuoteData(conn, holdingData.getQuoteID());

        if ((accountData == null) || (holdingData == null) || (quoteData == null)) {
            String error =
                "TradeDirect:sell -- error selling stock -- unable to find:  \n\taccount=" + accountData
                    + "\n\tholding=" + holdingData + "\n\tquote=" + quoteData + "\nfor user: " + userID
                    + " and holdingID: " + holdingID;
            Log.error(error);
            if (getInGlobalTxn())
                txn.rollback();
            else
                rollBack(conn, new Exception(error));
            return orderData;
        }

        double quantity = holdingData.getQuantity();

        orderData = createOrder(conn, accountData, quoteData, holdingData, "sell", quantity);

        // Set the holdingSymbol purchaseDate to selling to signify the sell
        // is "inflight"
        updateHoldingStatus(conn, holdingData.getHoldingID(), holdingData.getQuoteID());

        // UPDATE -- account should be credited during completeOrder
        BigDecimal price = quoteData.getPrice();
        BigDecimal orderFee = orderData.getOrderFee();
        total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee);
        creditAccountBalance(conn, accountData, total);

        try {
            if (orderProcessingMode == TradeConfig.SYNCH)
                completeOrder(conn, orderData.getOrderID());
            else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE)
                queueOrder(orderData.getOrderID(), true); // 2-phase
            // commit
        } catch (JMSException je) {
            Log.error("TradeBean:sell(" + userID + "," + holdingID + ") --> failed to queueOrder", je);
            /* On exception - cancel the order */

            cancelOrder(conn, orderData.getOrderID());
        }

        orderData = getOrderData(conn, orderData.getOrderID().intValue());

        if (txn != null) {
            if (Log.doTrace())
                Log.trace("TradeDirect:sell committing global transaction");
            txn.commit();
            setInGlobalTxn(false);
        } else
            commit(conn);
    } catch (Exception e) {
        Log.error("TradeDirect:sell error", e);
        if (getInGlobalTxn())
            txn.rollback();
        else
            rollBack(conn, e);
    } finally {
        releaseConn(conn);
    }

    return orderData;
}
 
Example 19
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** Lock values and ensure they don't get modified */
public void testValueLockingInTxn() throws Exception
{
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, DEFINITIVE_TWO, "initial_two", null);
    TransactionalCache.putSharedCacheValue(backingCache, DEFINITIVE_THREE, "initial_three", null);
    
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        // begin a transaction
        txn.begin();
        
        // Add
        {
            assertEquals(null, transactionalCache.get(DEFINITIVE_ONE));
            // Add it
            transactionalCache.put(DEFINITIVE_ONE, DEFINITIVE_ONE);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_ONE));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_ONE);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_ONE));
            // Attempt update
            transactionalCache.put(DEFINITIVE_ONE, "update_one");
            assertEquals("Update values should be locked.", DEFINITIVE_ONE, transactionalCache.get(DEFINITIVE_ONE));
        }
        
        // Update
        {
            assertEquals("initial_two", transactionalCache.get(DEFINITIVE_TWO));
            // Update it
            transactionalCache.put(DEFINITIVE_TWO, DEFINITIVE_TWO);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_TWO));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_TWO);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_TWO));
            // Attempt update
            transactionalCache.put(DEFINITIVE_TWO, "update_two");
            assertEquals("Update values should be locked.", DEFINITIVE_TWO, transactionalCache.get(DEFINITIVE_TWO));
            // Attempt removal
            transactionalCache.remove(DEFINITIVE_TWO);
            assertEquals("Update values should be locked.", DEFINITIVE_TWO, transactionalCache.get(DEFINITIVE_TWO));
        }
        
        // Remove
        {
            assertEquals("initial_three", transactionalCache.get(DEFINITIVE_THREE));
            // Remove it
            transactionalCache.remove(DEFINITIVE_THREE);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_THREE));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_THREE);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_THREE));
            // Attempt update
            transactionalCache.put(DEFINITIVE_THREE, "add_three");
            assertEquals("Removal should be locked.", null, transactionalCache.get(DEFINITIVE_THREE));
        }
        
        txn.commit();

        // Check post-commit values
        assertEquals("Definitive change not written through.", DEFINITIVE_ONE, TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_ONE, null));
        assertEquals("Definitive change not written through.", DEFINITIVE_TWO, TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_TWO, null));
        assertEquals("Definitive change not written through.", null, TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_THREE, null));
    }
    finally
    {
        try { txn.rollback(); } catch (Throwable ee) {}
    }
}
 
Example 20
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testTransactionalCacheStatsForClears() throws Throwable
{
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);
    
    
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    
    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);
    
    try
    {
        // begin a transaction
        txn.begin();
        
        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");
        
        // Perform some clears
        transactionalCache.clear();
        transactionalCache.clear();
        
        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));
        
        // commit the transaction
        txn.commit();

        assertEquals(clearsAtStart+2, cacheStats.count("transactionalCache", OpType.CLEAR));
        // There are no removes or puts propagated to the shared cache, as a result of the clears.
        assertEquals(removesAtStart+0, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(putsAtStart+0, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(hitsAtStart+3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart+4, cacheStats.count("transactionalCache", OpType.GET_MISS));
    }
    catch (Throwable e)
    {
        if (txn.getStatus() == Status.STATUS_ACTIVE)
        {
            txn.rollback();
        }
        throw e;
    }
}