Java Code Examples for javax.transaction.UserTransaction#commit()
The following examples show how to use
javax.transaction.UserTransaction#commit() .
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: CacheTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 2
Source File: JPAResource.java From boost with Eclipse Public License 1.0 | 6 votes |
public void createThing(StringBuilder builder) throws NamingException, NotSupportedException, SystemException, IllegalStateException, SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException { Context ctx = new InitialContext(); // Before getting an EntityManager, start a global transaction UserTransaction tran = (UserTransaction) ctx.lookup("java:comp/UserTransaction"); tran.begin(); // Now get the EntityManager from JNDI EntityManager em = (EntityManager) ctx.lookup(JNDI_NAME); builder.append("Creating a brand new Thing with " + em.getDelegate().getClass()).append(newline); // Create a Thing object and persist it to the database Thing thing = new Thing(); em.persist(thing); // Commit the transaction tran.commit(); int id = thing.getId(); builder.append("Created Thing " + id + ": " + thing).append(newline); }
Example 3
Source File: SiteServiceTestHuge.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
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 4
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
private Product getProduct(String id) throws Exception { WorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JPAWorkItemHandler.P_ACTION, JPAWorkItemHandler.GET_ACTION); workItem.setParameter(JPAWorkItemHandler.P_TYPE, "org.jbpm.process.workitem.jpa.Product"); workItem.setParameter(JPAWorkItemHandler.P_ID, id); UserTransaction ut = getUserTransaction(); ut.begin(); handler.executeWorkItem(workItem, manager); ut.commit(); Map<String, Object> results = ((TestWorkItemManager) manager).getResults(workItem.getId()); Product product = (Product) results.get(JPAWorkItemHandler.P_RESULT); return product; }
Example 5
Source File: QueryAndJtaTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
public void testIndexOnCommitForDestroy() throws Exception { AttributesFactory af = new AttributesFactory(); af.setDataPolicy(DataPolicy.REPLICATE); Region region = cache.createRegion("sample", af.create()); qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample"); Context ctx = cache.getJNDIContext(); UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction"); Integer x = new Integer(0); utx.begin(); region.create(x, new Person("xyz", 45)); utx.commit(); Query q = qs.newQuery("select * from /sample where age < 50"); assertEquals(1, ((SelectResults)q.execute()).size()); Person dsample = (Person)CopyHelper.copy(region.get(x)); dsample.setAge(55); utx.begin(); region.destroy(x); utx.commit(); System.out.println((region.get(x))); assertEquals(0, ((SelectResults) q.execute()).size()); }
Example 6
Source File: TransactionAwareSingletonTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
@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 7
Source File: ReplicationRestApiTest.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 6 votes |
@Override protected void tearDown() throws Exception { super.tearDown(); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); personManager.clearPeople(); // Zap any replication definitions we created AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); for(ReplicationDefinition rd : replicationService.loadReplicationDefinitions()) { replicationService.deleteReplicationDefinition(rd); } AuthenticationUtil.clearCurrentSecurityContext(); txn.commit(); }
Example 8
Source File: PersistenceContextStatefulBean.java From tomee with Apache License 2.0 | 5 votes |
public void testExtendedPersistenceContext() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/ExtendedTestContext"); Assert.assertNotNull("The EntityManager is null", em); // call a do nothing method to assure entity manager actually exists em.getFlushMode(); if (extendedEntityManager != null) { Assert.assertSame("Extended entity manager should be the same instance that was found last time", extendedEntityManager, em); Assert.assertSame("Extended entity manager delegate should be the same instance that was found last time", extendedEntityManager.getDelegate(), em.getDelegate()); } extendedEntityManager = em; final UserTransaction userTransaction = ejbContext.getUserTransaction(); userTransaction.begin(); try { em.getFlushMode(); } finally { userTransaction.commit(); } } catch (final Exception e) { e.printStackTrace(); Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 9
Source File: CacheTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** Execute the callback and ensure that the backing cache is left with the expected value */ private void executeAndCheck( RetryingTransactionCallback<Object> callback, boolean readOnly, String key, Object expectedValue, boolean mustContainKey) throws Throwable { if (expectedValue != null && !mustContainKey) { throw new IllegalArgumentException("Why have a value when the key should not be there?"); } TransactionService transactionService = serviceRegistry.getTransactionService(); UserTransaction txn = transactionService.getUserTransaction(readOnly); try { txn.begin(); callback.execute(); txn.commit(); } finally { try { txn.rollback(); } catch (Throwable ee) {} } Object actualValue = TransactionalCache.getSharedCacheValue(backingCache, key, null); assertEquals("Backing cache value was not correct", expectedValue, actualValue); assertEquals("Backing cache contains(key): ", mustContainKey, backingCache.contains(key)); // Clear the backing cache to ensure that subsequent tests don't run into existing data backingCache.clear(); }
Example 10
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Test(expected = WorkItemHandlerRuntimeException.class) public void queryWithParameterActionTestInvalidParams() throws Exception { WorkItemManager manager = new TestWorkItemManager(); String DESC = "Cheese"; Product p1 = new Product("Bread", 2f); Product p2 = new Product("Milk", 3f); Product p3 = new Product(DESC, 5f); create(p1); create(p2); create(p3); WorkItemImpl workItem = new WorkItemImpl(); Map<String, Object> params = new HashMap<>(); UserTransaction ut = getUserTransaction(); ut.begin(); handler.executeWorkItem(workItem, manager); ut.commit(); assertNotNull(((TestWorkItemManager) manager).getResults()); assertEquals(0, ((TestWorkItemManager) manager).getResults().size()); }
Example 11
Source File: ActionTrackingServiceImplTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
public void awaitExecution(UserTransaction tx, Thread toWake, String type) throws Exception { this.wantedType = type; synchronized (waitForExecutionLock) { // Have things begin working if (tx != null) { tx.commit(); } if (toWake != null) { toWake.interrupt(); } // Now wait for them to finish try { long now = System.currentTimeMillis(); waitForExecutionLock.wait(waitTime); if (System.currentTimeMillis() - now >= waitTime) { System.err.println("Warning - trigger wasn't received"); } } catch (InterruptedException e) { } } }
Example 12
Source File: ConcurrentNodeServiceSearchTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
protected void setUp() throws Exception { ctx = ApplicationContextHelper.getApplicationContext(); DictionaryDAO dictionaryDao = (DictionaryDAO) ctx.getBean("dictionaryDAO"); // load the system model ClassLoader cl = BaseNodeServiceTest.class.getClassLoader(); InputStream modelStream = cl.getResourceAsStream("alfresco/model/systemModel.xml"); assertNotNull(modelStream); M2Model model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); // load the test model modelStream = cl.getResourceAsStream("org/alfresco/repo/node/BaseNodeServiceTest_model.xml"); assertNotNull(modelStream); model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); nodeService = (NodeService) ctx.getBean("dbNodeService"); transactionService = (TransactionService) ctx.getBean("transactionComponent"); this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); this.authenticationComponent.setSystemUserAsCurrentUser(); // create a first store directly UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis()); rootNodeRef = nodeService.getRootNode(storeRef); tx.commit(); }
Example 13
Source File: SiteServiceTestHuge.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
private void creatSite(String siteName, String doAsUser) throws Exception { String currentUser = authenticationComponent.getCurrentUserName(); UserTransaction txn = transactionService.getUserTransaction(); try { if (doAsUser != null) authenticationComponent.setCurrentUser(doAsUser); txn.begin(); if (siteService.getSite(siteName) == null) { String sitePreset = "site-dashboard"; siteService.createSite(sitePreset, siteName, "Title for " + siteName, "Description for " + siteName, SiteVisibility.PUBLIC); // TODO Should do the following rather than the createContainers - not sure how // Map<String, String> tokens = new HashMap<String, String>(); // tokens.put("siteid", siteName); // presetsManager.constructPreset(tokens, tokens); siteService.createContainer(siteName, "documentLibrary", ContentModel.TYPE_FOLDER, null); siteService.createContainer(siteName, "links", ContentModel.TYPE_FOLDER, null); } txn.commit(); } catch (Exception e) { try { txn.rollback(); } catch (Exception e2) { } throw e; } finally { authenticationComponent.setCurrentUser(currentUser); } }
Example 14
Source File: PersistenceContextStatefulBean.java From tomee with Apache License 2.0 | 4 votes |
public void testPropagatedPersistenceContext() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/ExtendedTestContext"); Assert.assertNotNull("The EntityManager is null", em); // call a do nothing method to assure entity manager actually exists em.getFlushMode(); // get the raw entity manager so we can test it below inheritedDelegate = (EntityManager) em.getDelegate(); // The extended entity manager is not propigated to a non-extended entity manager unless there is a transaction final EntityManager nonExtendedEm = (EntityManager) ctx.lookup("java:comp/env/persistence/TestContext"); nonExtendedEm.getFlushMode(); final EntityManager nonExtendedDelegate = ((EntityManager) nonExtendedEm.getDelegate()); Assert.assertTrue("non-extended entity manager should be open", nonExtendedDelegate.isOpen()); Assert.assertNotSame("Extended non-extended entity manager shound not be the same instance as extendend entity manager when accessed out side of a transactions", inheritedDelegate, nonExtendedDelegate); // When the non-extended entity manager is accessed within a transaction is should see the stateful extended context. // // Note: this code also tests EBJ 3.0 Persistence spec 5.9.1 "UserTransaction is begun within the method, the // container associates the persistence context with the JTA transaction and calls EntityManager.joinTransaction." // If our the extended entity manager were not associted with the transaction, the non-extended entity manager would // not see it. final UserTransaction userTransaction = ejbContext.getUserTransaction(); userTransaction.begin(); try { Assert.assertSame("Extended non-extended entity manager to be same instance as extendend entity manager", inheritedDelegate, nonExtendedEm.getDelegate()); } finally { userTransaction.commit(); } // When a stateful bean with an extended entity manager creates another stateful bean, the new bean will // inherit the extended entity manager (assuming it contains an extended entity manager for the same persistence // unit). final PersistenceContextStatefulHome home = (PersistenceContextStatefulHome) ejbContext.getEJBHome(); final PersistenceContextStatefulObject object = home.create(); // test the new stateful bean recieved the context object.testPropgation(); // remove the bean object.remove(); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 15
Source File: RunningActionRestApiTest.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 4 votes |
@SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); ApplicationContext appContext = getServer().getApplicationContext(); nodeService = (NodeService)appContext.getBean("NodeService"); replicationService = (ReplicationService)appContext.getBean("ReplicationService"); actionTrackingService = (ActionTrackingService)appContext.getBean("actionTrackingService"); repositoryHelper = (Repository)appContext.getBean("repositoryHelper"); transactionService = (TransactionService)appContext.getBean("transactionService"); executingActionsCache = (SimpleCache<String, ExecutionDetails>)appContext.getBean("executingActionsCache"); MutableAuthenticationService authenticationService = (MutableAuthenticationService)appContext.getBean("AuthenticationService"); PersonService personService = (PersonService)appContext.getBean("PersonService"); personManager = new TestPersonManager(authenticationService, personService, nodeService); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); personManager.createPerson(USER_NORMAL); // Ensure we start with no replication definitions // (eg another test left them behind) AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); for(ReplicationDefinition rd : replicationService.loadReplicationDefinitions()) { replicationService.deleteReplicationDefinition(rd); } txn.commit(); // Grab a reference to the data dictionary dataDictionary = nodeService.getChildByName( repositoryHelper.getCompanyHome(), ContentModel.ASSOC_CONTAINS, "Data Dictionary" ); AuthenticationUtil.clearCurrentSecurityContext(); }
Example 16
Source File: ActionTrackingServiceImplTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
@Override @SuppressWarnings("unchecked") protected void setUp() throws Exception { // Detect any dangling transactions as there is a lot of direct UserTransaction manipulation if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE) { throw new IllegalStateException( "There should not be any transactions when starting test: " + AlfrescoTransactionSupport.getTransactionId() + " started at " + new Date(AlfrescoTransactionSupport.getTransactionStartTime())); } // Grab our beans this.nodeService = (NodeService)ctx.getBean("nodeService"); this.scriptService = (ScriptService)ctx.getBean("scriptService"); this.actionService = (ActionService)ctx.getBean("actionService"); this.runtimeActionService = (RuntimeActionService)ctx.getBean("actionService"); this.actionTrackingService = (ActionTrackingService)ctx.getBean("actionTrackingService"); this.transactionService = (TransactionService)ctx.getBean("transactionService"); this.executingActionsCache = (SimpleCache<String, ExecutionDetails>)ctx.getBean("executingActionsCache"); AuthenticationUtil.setRunAsUserSystem(); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); // Where to put things this.storeRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis()); this.rootNodeRef = this.nodeService.getRootNode(this.storeRef); // Create the node used for tests this.nodeRef = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}testnode"), ContentModel.TYPE_CONTENT).getChildRef(); this.nodeService.setProperty( this.nodeRef, ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null)); this.folder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}testFolder"), ContentModel.TYPE_FOLDER).getChildRef(); txn.commit(); // Cache should start empty each time executingActionsCache.clear(); // Reset the execution instance IDs, so we // can predict what they'll be ((ActionTrackingServiceImpl)actionTrackingService).resetNextExecutionId(); // Register the test executor, if needed SleepActionExecuter.registerIfNeeded(ctx); // We want to know when async actions occur asyncOccurs = new AsyncOccurs(); ((PolicyComponent)ctx.getBean("policyComponent")).bindClassBehaviour( AsynchronousActionExecutionQueuePolicies.OnAsyncActionExecute.QNAME, ActionModel.TYPE_ACTION, new JavaBehaviour(asyncOccurs, "onAsyncActionExecute", NotificationFrequency.EVERY_EVENT) ); }
Example 17
Source File: CacheTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
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; } }
Example 18
Source File: XATransactionTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
public void testJTA_localTransaction() throws Exception { Properties props = new Properties(); String jndiBindingsXmlFile = TestUtil.getResourcesDir() + "/lib/gfxdCacheJta.xml"; props.put("cache-xml-file", jndiBindingsXmlFile); Connection c = TestUtil.getConnection(props); Statement stmnt = c.createStatement(); stmnt.execute("create table XATT2 (i int primary key, text char(10))"); String tableName = "testtable"; Context ctx = Misc.getGemFireCache().getJNDIContext(); String sql = "create table " + tableName + " (id integer NOT NULL primary key, name varchar(50))"; DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); Connection cxn = ds.getConnection(); Statement sm = cxn.createStatement(); try { sm.execute("drop table " + tableName); } catch (Exception e) { // ignore. we just want that table is not present } sm.execute(sql); sm.close(); UserTransaction ta = (UserTransaction)ctx.lookup("java:/UserTransaction"); ta.begin(); Connection sm_conn = null; // get the SimpleDataSource before the transaction begins DataSource sds = (DataSource)ctx.lookup("java:/SimpleDataSource"); // Begin the user transaction DataSource gemfirexdXADataSource = (DataSource)ctx.lookup("java:/GemfirexdXADataSource"); Connection conn = gemfirexdXADataSource.getConnection(); Statement stm = conn.createStatement(); stm.execute("insert into XATT2 values (1234, 'Test_Entry')"); stm.close(); sm_conn = sds.getConnection(); Statement sm_stmt = sm_conn.createStatement(); sm_stmt.execute("insert into " + tableName + " values (1, 'first')"); sm_stmt.close(); // close the connections //xa_conn.close(); sm_conn.close(); // commit the transaction Connection connBeforeCommit = TestUtil.getConnection(); stmnt = connBeforeCommit.createStatement(); stmnt.execute("select * from XATT2"); assertFalse(stmnt.getResultSet().next()); stmnt.execute("select * from XATT2 where i = 1234"); assertFalse(stmnt.getResultSet().next()); ta.commit(); stmnt.execute("select * from XATT2"); assertTrue(stmnt.getResultSet().next()); }
Example 19
Source File: TradeJEEDirect.java From jboss-daytrader with Apache License 2.0 | 4 votes |
/** * @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 20
Source File: TradeDirect.java From sample.daytrader7 with Apache License 2.0 | 4 votes |
/** * @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; }