You are viewing a plain text version of this content. The canonical link for it is here.
Posted to scm@geronimo.apache.org by dw...@apache.org on 2010/01/20 07:23:40 UTC
svn commit: r901082 [1/2] - in /geronimo/daytrader/trunk: ./
assemblies/web/daytrader-web-jpa/
assemblies/web/daytrader-web-jpa/src/main/webapp/WEB-INF/
modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/
modules/ejb3/src/main...
Author: dwoods
Date: Wed Jan 20 06:23:35 2010
New Revision: 901082
URL: http://svn.apache.org/viewvc?rev=901082&view=rev
Log:
more updates, but daytrader-web-jpa still doesn't work
Added:
geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/tranTradeJPADirect.java (with props)
geronimo/daytrader/trunk/modules/entities/src/main/resources/META-INF/persistence.xml (with props)
geronimo/daytrader/trunk/modules/web/src/main/java/org/apache/geronimo/samples/daytrader/prim/
geronimo/daytrader/trunk/modules/web/src/main/java/org/apache/geronimo/samples/daytrader/prim/Servlet_Find.java (with props)
Removed:
geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/src/main/webapp/WEB-INF/persistence.xml
geronimo/daytrader/trunk/modules/ejb3/src/main/resources/META-INF/persistence.xml
Modified:
geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/pom.xml
geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/TradeJPADirect.java
geronimo/daytrader/trunk/modules/entities/src/main/java/org/apache/geronimo/samples/daytrader/beans/AccountDataBean.java
geronimo/daytrader/trunk/modules/entities/src/main/java/org/apache/geronimo/samples/daytrader/beans/AccountProfileDataBean.java
geronimo/daytrader/trunk/modules/entities/src/main/java/org/apache/geronimo/samples/daytrader/beans/HoldingDataBean.java
geronimo/daytrader/trunk/modules/entities/src/main/java/org/apache/geronimo/samples/daytrader/beans/OrderDataBean.java
geronimo/daytrader/trunk/modules/entities/src/main/java/org/apache/geronimo/samples/daytrader/beans/QuoteDataBean.java
geronimo/daytrader/trunk/modules/web/pom.xml
geronimo/daytrader/trunk/modules/web/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeServletAction.java
geronimo/daytrader/trunk/pom.xml
Modified: geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/pom.xml?rev=901082&r1=901081&r2=901082&view=diff
==============================================================================
--- geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/pom.xml (original)
+++ geronimo/daytrader/trunk/assemblies/web/daytrader-web-jpa/pom.xml Wed Jan 20 06:23:35 2010
@@ -53,41 +53,66 @@
<version>${version}</version>
</dependency>
<dependency>
+ <!-- we need to include this in the image for logging to work -->
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+
+ <!-- web container provided specs -->
+ <dependency>
<groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jta_1.1_spec</artifactId>
+ <artifactId>geronimo-servlet_2.5_spec</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jms_1.1_spec</artifactId>
+ <artifactId>geronimo-jsp_2.1_spec</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jta_1.1_spec</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_1.0_spec</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>jstl</artifactId>
+ <scope>provided</scope>
</dependency>
+ <!-- user or app server provided artifacts -->
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <!-- we need to include this in the image for logging to work -->
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ <scope>provided</scope>
</dependency>
-
- <!-- web container provided specs -->
<dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-servlet_2.5_spec</artifactId>
+ <groupId>commons-dbcp</groupId>
+ <artifactId>commons-dbcp</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jsp_2.1_spec</artifactId>
+ <groupId>commons-lang</groupId>
+ <artifactId>commons-lang</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
+ <groupId>commons-pool</groupId>
+ <artifactId>commons-pool</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>net.sourceforge.serp</groupId>
+ <artifactId>serp</artifactId>
<scope>provided</scope>
</dependency>
@@ -101,6 +126,10 @@
<!-- Not required for Bean version of TradeDirect
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jms_1.1_spec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-ejb_3.0_spec</artifactId>
<scope>provided</scope>
</dependency>
Modified: geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/TradeJPADirect.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/TradeJPADirect.java?rev=901082&r1=901081&r2=901082&view=diff
==============================================================================
--- geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/TradeJPADirect.java (original)
+++ geronimo/daytrader/trunk/modules/core/src/main/java/org/apache/geronimo/samples/daytrader/core/direct/TradeJPADirect.java Wed Jan 20 06:23:35 2010
@@ -16,54 +16,38 @@
*/
package org.apache.geronimo.samples.daytrader.core.direct;
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.PersistenceContext;
+import javax.persistence.PersistenceUnit;
+import javax.persistence.Query;
+
import org.apache.geronimo.samples.daytrader.beans.AccountDataBean;
import org.apache.geronimo.samples.daytrader.beans.AccountProfileDataBean;
import org.apache.geronimo.samples.daytrader.beans.HoldingDataBean;
import org.apache.geronimo.samples.daytrader.beans.OrderDataBean;
import org.apache.geronimo.samples.daytrader.beans.QuoteDataBean;
-import org.apache.geronimo.samples.daytrader.core.direct.TradeJDBCDirect;
import org.apache.geronimo.samples.daytrader.core.FinancialUtils;
import org.apache.geronimo.samples.daytrader.core.MarketSummaryDataBean;
import org.apache.geronimo.samples.daytrader.core.RunStatsDataBean;
-import org.apache.geronimo.samples.daytrader.core.TradeAction;
import org.apache.geronimo.samples.daytrader.core.TradeDBServices;
import org.apache.geronimo.samples.daytrader.core.TradeServices;
import org.apache.geronimo.samples.daytrader.util.Log;
-import org.apache.geronimo.samples.daytrader.util.MDBStats;
import org.apache.geronimo.samples.daytrader.util.TradeConfig;
-import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-//import javax.ejb.*;
-//import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.SystemException;
-
-
/**
- * TradeJPADirect uses JPA to implement the business methods of the
- * Trade online broker application. These business methods represent the
- * features and operations that can be performed by customers of the brokerage
- * such as login, logout, get a stock quote, buy or sell a stock, etc. and are
- * specified in the {@link org.apache.geronimo.samples.daytrader.TradeServices}
- * interface
+ * TradeJPADirect uses JPA to implement the business methods of the Trade online
+ * broker application. These business methods represent the features and
+ * operations that can be performed by customers of the brokerage such as login,
+ * logout, get a stock quote, buy or sell a stock, etc. and are specified in the
+ * {@link org.apache.geronimo.samples.daytrader.TradeServices} interface
*
* Note: In order for this class to be thread-safe, a new TradeJPA must be
* created for each call to a method from the TradeInterface interface.
@@ -72,11 +56,10 @@
* @see org.apache.geronimo.samples.daytrader.TradeServices
*
*/
-
public class TradeJPADirect implements TradeServices, TradeDBServices {
- @PersistenceContext
- private EntityManager entityManager;
+ @PersistenceUnit(name="daytrader")
+ private static EntityManagerFactory emf;
private static BigDecimal ZERO = new BigDecimal(0.0);
@@ -86,6 +69,16 @@
* Zero arg constructor for TradeJPADirect
*/
public TradeJPADirect() {
+
+
+ // TO-DO why
+ TradeConfig.setPublishQuotePriceChange(false);
+ if (emf == null) {
+ // creating entity manager factory. the persistence xml must be
+ // place under src/META-INF/
+ emf = Persistence.createEntityManagerFactory("daytrader");
+ }
+
if (initialized == false)
init();
}
@@ -96,6 +89,8 @@
if (Log.doTrace())
Log.trace("TradeJPADirect:init -- *** initializing");
+ // TO-DO-for some reason this is not setting it to false- added
+ // to the construct.
TradeConfig.setPublishQuotePriceChange(false);
if (Log.doTrace())
@@ -109,14 +104,21 @@
if (!initialized)
return;
Log.trace("TradeJPADirect:destroy");
- } catch (Exception e) {
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:destroy", e);
}
+
}
public MarketSummaryDataBean getMarketSummary() {
MarketSummaryDataBean marketSummaryData;
-
+
+ /*
+ * Creating entiManager
+ */
+ EntityManager entityManager = emf.createEntityManager();
+
try {
if (Log.doTrace())
Log.trace("TradeJPADirect:getMarketSummary -- getting market summary");
@@ -125,11 +127,13 @@
// ordered by their change in value
Collection<QuoteDataBean> quotes;
- Query query = entityManager.createNamedQuery("quoteejb.quotesByChange");
+ Query query = entityManager
+ .createNamedQuery("quoteejb.quotesByChange");
quotes = query.getResultList();
QuoteDataBean[] quoteArray = (QuoteDataBean[]) quotes.toArray(new QuoteDataBean[quotes.size()]);
- ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>(5);
+ ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>(
+ 5);
ArrayList<QuoteDataBean> topLosers = new ArrayList<QuoteDataBean>(5);
BigDecimal TSIA = FinancialUtils.ZERO;
BigDecimal openTSIA = FinancialUtils.ZERO;
@@ -149,80 +153,139 @@
openTSIA = openTSIA.add(open);
totalVolume += volume;
}
- TSIA = TSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND);
- openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND);
+ TSIA = TSIA.divide(new BigDecimal(quoteArray.length),
+ FinancialUtils.ROUND);
+ openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length),
+ FinancialUtils.ROUND);
}
- marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, totalVolume, topGainers, topLosers);
- } catch (Exception e) {
+ marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA,
+ totalVolume, topGainers, topLosers);
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:getMarketSummary", e);
throw new RuntimeException("TradeJPADirect:getMarketSummary -- error ", e);
}
+ /*
+ * closing entitymanager
+ */
+ entityManager.close();
+
return marketSummaryData;
}
- public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) {
+ public OrderDataBean buy(String userID, String symbol, double quantity,
+ int orderProcessingMode) {
OrderDataBean order = null;
BigDecimal total;
+ /*
+ * creating entitymanager
+ */
+ EntityManager entityManager = emf.createEntityManager();
+
try {
if (Log.doTrace())
Log.trace("TradeJPADirect:buy", userID, symbol, quantity, orderProcessingMode);
- AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
+ entityManager.getTransaction().begin();
+
+ AccountProfileDataBean profile = entityManager.find(
+ AccountProfileDataBean.class, userID);
AccountDataBean account = profile.getAccount();
- QuoteDataBean quote = entityManager.find(QuoteDataBean.class, symbol);
+
+ QuoteDataBean quote = entityManager.find(QuoteDataBean.class,
+ symbol);
+
HoldingDataBean holding = null; // The holding will be created by this buy order
- order = createOrder(account, quote, holding, "buy", quantity);
+ order = createOrder(account, quote, holding, "buy", quantity,
+ entityManager);
+ // order = createOrder(account, quote, holding, "buy", quantity);
// UPDATE - account should be credited during completeOrder
+
BigDecimal price = quote.getPrice();
BigDecimal orderFee = order.getOrderFee();
BigDecimal balance = account.getBalance();
total = (new BigDecimal(quantity).multiply(price)).add(orderFee);
account.setBalance(balance.subtract(total));
+ // commit the transaction before calling completeOrder
+ entityManager.getTransaction().commit();
+
if (orderProcessingMode == TradeConfig.SYNCH)
completeOrder(order.getOrderID(), false);
else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE)
queueOrder(order.getOrderID(), true);
- } catch (Exception e) {
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:buy(" + userID + "," + symbol + "," + quantity + ") --> failed", e);
/* On exception - cancel the order */
// TODO figure out how to do this with JPA
- if (order != null) order.cancel();
+ if (order != null)
+ order.cancel();
+
+ entityManager.getTransaction().rollback();
+
// throw new EJBException(e);
throw new RuntimeException(e);
}
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
+
+ // after the purchase or sell of a stock, update the stocks volume and
+ // price
+ updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity);
+
return order;
}
- public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) {
+ public OrderDataBean sell(String userID, Integer holdingID,
+ int orderProcessingMode) {
+ EntityManager entityManager = emf.createEntityManager();
+
OrderDataBean order = null;
BigDecimal total;
try {
+ entityManager.getTransaction().begin();
if (Log.doTrace())
Log.trace("TradeJPADirect:sell", userID, holdingID, orderProcessingMode);
- AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
+ AccountProfileDataBean profile = entityManager.find(
+ AccountProfileDataBean.class, userID);
+
AccountDataBean account = profile.getAccount();
- HoldingDataBean holding = entityManager.find(HoldingDataBean.class, holdingID);
-
+ HoldingDataBean holding = entityManager.find(HoldingDataBean.class,
+ holdingID);
+
if (holding == null) {
- Log.error("TradeJPADirect:sell User " + userID + " attempted to sell holding " + holdingID + " which has already been sold");
-
+ Log.error("TradeJPADirect:sell User " + userID
+ + " attempted to sell holding " + holdingID
+ + " which has already been sold");
+
OrderDataBean orderData = new OrderDataBean();
orderData.setOrderStatus("cancelled");
+
entityManager.persist(orderData);
-
+
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+
+ }
+ entityManager.getTransaction().commit();
return orderData;
- }
+ }
QuoteDataBean quote = holding.getQuote();
double quantity = holding.getQuantity();
- order = createOrder(account, quote, holding, "sell", quantity);
- // UPDATE the holding purchase data to signify this holding is "inflight" to be sold
+ order = createOrder(account, quote, holding, "sell", quantity,
+ entityManager);
+ // UPDATE the holding purchase data to signify this holding is
+ // "inflight" to be sold
// -- could add a new holdingStatus attribute to holdingEJB
holding.setPurchaseDate(new java.sql.Timestamp(0));
@@ -231,35 +294,57 @@
BigDecimal orderFee = order.getOrderFee();
BigDecimal balance = account.getBalance();
total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee);
+
account.setBalance(balance.add(total));
+ // commit the transaction before calling completeOrder
+ entityManager.getTransaction().commit();
+
if (orderProcessingMode == TradeConfig.SYNCH)
completeOrder(order.getOrderID(), false);
else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE)
queueOrder(order.getOrderID(), true);
- } catch (Exception e) {
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:sell(" + userID + "," + holdingID + ") --> failed", e);
// TODO figure out JPA cancel
- if (order != null) order.cancel();
- // UPDATE - handle all exceptions like:
- // throw new EJBException("TradeJPADirect:sell(" + userID + "," + holdingID + ")", e);
+ if (order != null)
+ order.cancel();
+
+ entityManager.getTransaction().rollback();
+
throw new RuntimeException("TradeJPADirect:sell(" + userID + "," + holdingID + ")", e);
}
+
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
+
+ if (!(order.getOrderStatus().equalsIgnoreCase("cancelled")))
+ //after the purchase or sell of a stock, update the stocks volume and price
+ updateQuotePriceVolume(order.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), order.getQuantity());
+
return order;
}
public void queueOrder(Integer orderID, boolean twoPhase) {
- Log.error("TradeJPADirect:queueOrder() not implemented for this runtime mode");
- throw new UnsupportedOperationException("TradeJPADirect:queueOrder() not implemented for this runtime mode");
+ Log
+ .error("TradeJPADirect:queueOrder() not implemented for this runtime mode");
+ throw new UnsupportedOperationException(
+ "TradeJPADirect:queueOrder() not implemented for this runtime mode");
}
public OrderDataBean completeOrder(Integer orderID, boolean twoPhase)
- throws Exception {
+ throws Exception {
+ EntityManager entityManager = emf.createEntityManager();
+ OrderDataBean order = null;
+
if (Log.doTrace())
Log.trace("TradeJPADirect:completeOrder", orderID + " twoPhase=" + twoPhase);
- OrderDataBean order = entityManager.find(OrderDataBean.class, orderID);
+ order = entityManager.find(OrderDataBean.class, orderID);
order.getQuote();
if (order == null) {
@@ -267,8 +352,9 @@
return null;
}
- if (order.isCompleted())
+ if (order.isCompleted()) {
throw new RuntimeException("Error: attempt to complete Order that is already completed\n" + order);
+ }
AccountDataBean account = order.getAccount();
QuoteDataBean quote = order.getQuote();
@@ -279,148 +365,235 @@
String userID = account.getProfile().getUserID();
if (Log.doTrace())
- Log.trace("TradeJPADirect:completeOrder--> Completing Order " + order.getOrderID()
- + "\n\t Order info: " + order
- + "\n\t Account info: " + account
- + "\n\t Quote info: " + quote
- + "\n\t Holding info: " + holding);
+ Log.trace("TradeJPADirect:completeOrder--> Completing Order "
+ + order.getOrderID() + "\n\t Order info: " + order
+ + "\n\t Account info: " + account + "\n\t Quote info: "
+ + quote + "\n\t Holding info: " + holding);
+ HoldingDataBean newHolding = null;
if (order.isBuy()) {
/*
- * Complete a Buy operation
- * - create a new Holding for the Account
- * - deduct the Order cost from the Account balance
+ * Complete a Buy operation - create a new Holding for the Account -
+ * deduct the Order cost from the Account balance
*/
- HoldingDataBean newHolding = createHolding(account, quote, quantity, price);
- order.setHolding(newHolding);
+ newHolding = createHolding(account, quote, quantity, price, entityManager);
}
- if (order.isSell()) {
- /*
- * Complete a Sell operation
- * - remove the Holding from the Account
- * - deposit the Order proceeds to the Account balance
- */
- if (holding == null) {
- Log.error("TradeJPADirect:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold");
- order.cancel();
- return order;
- } else {
- entityManager.remove(holding);
- order.setHolding(null);
+ try {
+ entityManager.getTransaction().begin();
+
+ if (newHolding != null) {
+ order.setHolding(newHolding);
}
- }
- order.setOrderStatus("closed");
- order.setCompletionDate(new java.sql.Timestamp(System.currentTimeMillis()));
+ if (order.isSell()) {
+ /*
+ * Complete a Sell operation - remove the Holding from the Account -
+ * deposit the Order proceeds to the Account balance
+ */
+ if (holding == null) {
+ Log.error("TradeJPADirect:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold");
+ order.cancel();
+ entityManager.getTransaction().commit();
+ return order;
+ }
+ else {
+ entityManager.remove(holding);
+ order.setHolding(null);
+ }
+ }
- if (Log.doTrace())
- Log.trace("TradeJPADirect:completeOrder--> Completed Order " + order.getOrderID()
- + "\n\t Order info: " + order
- + "\n\t Account info: " + account
- + "\n\t Quote info: " + quote
- + "\n\t Holding info: " + holding);
+ order.setOrderStatus("closed");
+
+ order.setCompletionDate(new java.sql.Timestamp(System.currentTimeMillis()));
+
+ if (Log.doTrace())
+ Log.trace("TradeJPADirect:completeOrder--> Completed Order "
+ + order.getOrderID() + "\n\t Order info: " + order
+ + "\n\t Account info: " + account + "\n\t Quote info: "
+ + quote + "\n\t Holding info: " + holding);
- //if (Log.doTrace())
- // Log.trace("Calling TradeAction:orderCompleted from Session EJB using Session Object");
- // FUTURE All getEJBObjects could be local -- need to add local I/F
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ entityManager.getTransaction().rollback();
+ }
- // commented out following call
- // - orderCompleted doesn't really do anything (think it was a hook for old Trade caching code)
-
- /*TradeAction tradeAction = new TradeAction();
- tradeAction.orderCompleted(userID, orderID);*/
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
return order;
}
public void cancelOrder(Integer orderID, boolean twoPhase) {
+ EntityManager entityManager = emf.createEntityManager();
+
if (Log.doTrace())
Log.trace("TradeJPADirect:cancelOrder", orderID + " twoPhase=" + twoPhase);
OrderDataBean order = entityManager.find(OrderDataBean.class, orderID);
- order.cancel();
+ /*
+ * managed transaction
+ */
+ try {
+ entityManager.getTransaction().begin();
+ order.cancel();
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
+ entityManager.close();
}
public void orderCompleted(String userID, Integer orderID) {
- throw new UnsupportedOperationException("TradeJPADirect:orderCompleted method not supported");
+ if (Log.doActionTrace())
+ Log.trace("TradeAction:orderCompleted", userID, orderID);
+ if (Log.doTrace())
+ Log.trace("OrderCompleted", userID, orderID);
}
public Collection<OrderDataBean> getOrders(String userID) {
if (Log.doTrace())
Log.trace("TradeJPADirect:getOrders", userID);
-
- AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
+ EntityManager entityManager = emf.createEntityManager();
+ AccountProfileDataBean profile = entityManager.find(
+ AccountProfileDataBean.class, userID);
AccountDataBean account = profile.getAccount();
+ entityManager.close();
return account.getOrders();
}
public Collection<OrderDataBean> getClosedOrders(String userID) {
+
if (Log.doTrace())
Log.trace("TradeJPADirect:getClosedOrders", userID);
+ EntityManager entityManager = emf.createEntityManager();
try {
// Get the primary keys for all the closed Orders for this
// account.
- Query query = entityManager.createNamedQuery("orderejb.closedOrders");
+ /*
+ * managed transaction
+ */
+ entityManager.getTransaction().begin();
+ Query query = entityManager
+ .createNamedQuery("orderejb.closedOrders");
query.setParameter("userID", userID);
+
+ entityManager.getTransaction().commit();
Collection results = query.getResultList();
Iterator itr = results.iterator();
-
+ // entityManager.joinTransaction();
// Spin through the orders to populate the lazy quote fields
- while (itr.hasNext()){
- OrderDataBean thisOrder = (OrderDataBean)itr.next();
+ while (itr.hasNext()) {
+ OrderDataBean thisOrder = (OrderDataBean) itr.next();
thisOrder.getQuote();
}
-
+
if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) {
- Query updateStatus = entityManager.createNamedQuery("orderejb.completeClosedOrders");
- updateStatus.setParameter("userID", userID);
- updateStatus.executeUpdate();
- } else if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) {
- /* Add logic to do update orders operation, because JBoss5' Hibernate 3.3.1GA DB2Dialect
- * and MySQL5Dialect do not work with annotated query "orderejb.completeClosedOrders"
- * defined in OrderDatabean
+ Query updateStatus = entityManager
+ .createNamedQuery("orderejb.completeClosedOrders");
+ /*
+ * managed transaction
*/
- Query findaccountid = entityManager.createNativeQuery("select "+
- "a.ACCOUNTID, "+
- "a.LOGINCOUNT, "+
- "a.LOGOUTCOUNT, "+
- "a.LASTLOGIN, "+
- "a.CREATIONDATE, "+
- "a.BALANCE, "+
- "a.OPENBALANCE, "+
- "a.PROFILE_USERID "+
- "from accountejb a where a.profile_userid = ?",
- org.apache.geronimo.samples.daytrader.beans.AccountDataBean.class);
+ try {
+ entityManager.getTransaction().begin();
+ updateStatus.setParameter("userID", userID);
+
+ updateStatus.executeUpdate();
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
+ }
+ else if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) {
+ /*
+ * Add logic to do update orders operation, because JBoss5'
+ * Hibernate 3.3.1GA DB2Dialect and MySQL5Dialect do not work
+ * with annotated query "orderejb.completeClosedOrders" defined
+ * in OrderDatabean
+ */
+ Query findaccountid = entityManager
+ .createNativeQuery(
+ "select "
+ + "a.ACCOUNTID, "
+ + "a.LOGINCOUNT, "
+ + "a.LOGOUTCOUNT, "
+ + "a.LASTLOGIN, "
+ + "a.CREATIONDATE, "
+ + "a.BALANCE, "
+ + "a.OPENBALANCE, "
+ + "a.PROFILE_USERID "
+ + "from accountejb a where a.profile_userid = ?",
+ org.apache.geronimo.samples.daytrader.beans.AccountDataBean.class);
findaccountid.setParameter(1, userID);
- AccountDataBean account = (AccountDataBean)findaccountid.getSingleResult();
+ AccountDataBean account = (AccountDataBean) findaccountid.getSingleResult();
Integer accountid = account.getAccountID();
- Query updateStatus = entityManager.createNativeQuery(
- "UPDATE orderejb o SET o.orderStatus = 'completed' WHERE " +
- "o.orderStatus = 'closed' AND o.ACCOUNT_ACCOUNTID = ?");
+ Query updateStatus = entityManager.createNativeQuery("UPDATE orderejb o SET o.orderStatus = 'completed' WHERE "
+ + "o.orderStatus = 'closed' AND o.ACCOUNT_ACCOUNTID = ?");
updateStatus.setParameter(1, accountid.intValue());
updateStatus.executeUpdate();
}
-
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
return results;
- } catch (Exception e) {
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect.getClosedOrders", e);
- throw new RuntimeException("TradeJPADirect.getClosedOrders - error", e);
+ entityManager.close();
+ entityManager = null;
+ throw new RuntimeException(
+ "TradeJPADirect.getClosedOrders - error", e);
+
}
+
}
- public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) {
+ public QuoteDataBean createQuote(String symbol, String companyName,
+ BigDecimal price) {
+ EntityManager entityManager = emf.createEntityManager();
try {
QuoteDataBean quote = new QuoteDataBean(symbol, companyName, 0, price, price, price, price, 0);
- entityManager.persist(quote);
+ /*
+ * managed transaction
+ */
+ try {
+ entityManager.getTransaction().begin();
+ entityManager.persist(quote);
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ }
+
if (Log.doTrace())
Log.trace("TradeJPADirect:createQuote-->" + quote);
+
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
return quote;
- } catch (Exception e) {
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:createQuote -- exception creating Quote", e);
+ System.out
+ .println("TradeJPADirect:createQuote -- exception creating Quote");
+ entityManager.close();
+ entityManager = null;
throw new RuntimeException(e);
}
}
@@ -428,39 +601,59 @@
public QuoteDataBean getQuote(String symbol) {
if (Log.doTrace())
Log.trace("TradeJPADirect:getQuote", symbol);
+ EntityManager entityManager = emf.createEntityManager();
+
+ QuoteDataBean qdb = entityManager.find(QuoteDataBean.class, symbol);
- return entityManager.find(QuoteDataBean.class, symbol);
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
+ return qdb;
}
public Collection<QuoteDataBean> getAllQuotes() {
if (Log.doTrace())
Log.trace("TradeJPADirect:getAllQuotes");
+ EntityManager entityManager = emf.createEntityManager();
Query query = entityManager.createNamedQuery("quoteejb.allQuotes");
+
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+
+ }
return query.getResultList();
}
- public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) {
+ public QuoteDataBean updateQuotePriceVolume(String symbol,
+ BigDecimal changeFactor, double sharesTraded) {
if (!TradeConfig.getUpdateQuotePrices())
return new QuoteDataBean();
if (Log.doTrace())
Log.trace("TradeJPADirect:updateQuote", symbol, changeFactor);
- /* Add logic to determine JPA layer, because JBoss5' Hibernate 3.3.1GA DB2Dialect
- * and MySQL5Dialect do not work with annotated query "quoteejb.quoteForUpdate"
- * defined in QuoteDatabean
- */
+ /*
+ * Add logic to determine JPA layer, because JBoss5' Hibernate 3.3.1GA
+ * DB2Dialect and MySQL5Dialect do not work with annotated query
+ * "quoteejb.quoteForUpdate" defined in QuoteDatabean
+ */
+ EntityManager entityManager = emf.createEntityManager();
QuoteDataBean quote = new QuoteDataBean();
if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) {
quote = entityManager.find(QuoteDataBean.class, symbol);
- }
-
+ }
+
if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) {
+
Query q = entityManager.createNamedQuery("quoteejb.quoteForUpdate");
q.setParameter(1, symbol);
+
quote = (QuoteDataBean) q.getSingleResult();
- }
+
+ }
BigDecimal oldPrice = quote.getPrice();
@@ -470,13 +663,29 @@
BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
- quote.setPrice(newPrice);
- quote.setVolume(quote.getVolume() + sharesTraded);
- entityManager.merge(quote);
-
- // TODO find out if requires new here is really intended -- it is backwards,
- // change can get published w/o it occurring.
- // ((Trade) context.getEJBObject()).publishQuotePriceChange(quote,oldPrice, changeFactor, sharesTraded);
+ /*
+ * managed transaction
+ */
+
+ try {
+
+ quote.setPrice(newPrice);
+ quote.setVolume(quote.getVolume() + sharesTraded);
+ quote.setChange((newPrice.subtract(quote.getOpen()).doubleValue()));
+
+ entityManager.getTransaction().begin();
+ entityManager.merge(quote);
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ }
+
+ if (entityManager != null) {
+ entityManager.close();
+ entityManager = null;
+ }
+
this.publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded);
return quote;
@@ -485,24 +694,34 @@
public Collection<HoldingDataBean> getHoldings(String userID) {
if (Log.doTrace())
Log.trace("TradeJPADirect:getHoldings", userID);
+ EntityManager entityManager = emf.createEntityManager();
+ /*
+ * managed transaction
+ */
+ entityManager.getTransaction().begin();
Query query = entityManager.createNamedQuery("holdingejb.holdingsByUserID");
query.setParameter("userID", userID);
+
+ entityManager.getTransaction().commit();
Collection<HoldingDataBean> holdings = query.getResultList();
/*
* Inflate the lazy data memebers
- */
+ */
Iterator itr = holdings.iterator();
while (itr.hasNext()) {
((HoldingDataBean) itr.next()).getQuote();
}
+ entityManager.close();
+ entityManager = null;
return holdings;
}
public HoldingDataBean getHolding(Integer holdingID) {
if (Log.doTrace())
Log.trace("TradeJPADirect:getHolding", holdingID);
+ EntityManager entityManager = emf.createEntityManager();
return entityManager.find(HoldingDataBean.class, holdingID);
}
@@ -510,30 +729,42 @@
if (Log.doTrace())
Log.trace("TradeJPADirect:getAccountData", userID);
+ EntityManager entityManager = emf.createEntityManager();
+
AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
/*
* Inflate the lazy data memebers
*/
AccountDataBean account = profile.getAccount();
account.getProfile();
-
+
// Added to populate transient field for account
account.setProfileID(profile.getUserID());
+ entityManager.close();
+ entityManager = null;
+
return account;
}
public AccountProfileDataBean getAccountProfileData(String userID) {
if (Log.doTrace())
Log.trace("TradeJPADirect:getProfileData", userID);
+ EntityManager entityManager = emf.createEntityManager();
- return entityManager.find(AccountProfileDataBean.class, userID);
+ AccountProfileDataBean apb = entityManager.find(AccountProfileDataBean.class, userID);
+ entityManager.close();
+ entityManager = null;
+ return apb;
}
public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) {
+
+ EntityManager entityManager = emf.createEntityManager();
+
if (Log.doTrace())
Log.trace("TradeJPADirect:updateAccountProfileData", profileData);
/*
- * // Retreive the pevious account profile in order to get account
+ * // Retrieve the previous account profile in order to get account
* data... hook it into new object AccountProfileDataBean temp =
* entityManager.find(AccountProfileDataBean.class,
* profileData.getUserID()); // In order for the object to merge
@@ -552,123 +783,214 @@
temp.setFullName(profileData.getFullName());
temp.setCreditCard(profileData.getCreditCard());
temp.setEmail(profileData.getEmail());
+ /*
+ * Managed Transaction
+ */
+ try {
- entityManager.merge(temp);
+ entityManager.getTransaction().begin();
+ entityManager.merge(temp);
+ entityManager.getTransaction().commit();
+ entityManager.close();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
return temp;
}
- public AccountDataBean login(String userID, String password) throws RollbackException {
+ public AccountDataBean login(String userID, String password)
+ throws Exception {
+
+ EntityManager entityManager = emf.createEntityManager();
+
AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
if (profile == null) {
throw new RuntimeException("No such user: " + userID);
}
+ /*
+ * Managed Transaction
+ */
+ entityManager.getTransaction().begin();
entityManager.merge(profile);
+
AccountDataBean account = profile.getAccount();
if (Log.doTrace())
Log.trace("TradeJPADirect:login", userID, password);
+
account.login(password);
+ entityManager.getTransaction().commit();
if (Log.doTrace())
Log.trace("TradeJPADirect:login(" + userID + "," + password + ") success" + account);
-
+ entityManager.close();
return account;
}
public void logout(String userID) {
if (Log.doTrace())
Log.trace("TradeJPADirect:logout", userID);
+ EntityManager entityManager = emf.createEntityManager();
AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID);
AccountDataBean account = profile.getAccount();
- account.logout();
-
+ /*
+ * Managed Transaction
+ */
+ try {
+ entityManager.getTransaction().begin();
+ account.logout();
+ entityManager.getTransaction().commit();
+ entityManager.close();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
+
if (Log.doTrace())
Log.trace("TradeJPADirect:logout(" + userID + ") success");
}
- public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) {
+ public AccountDataBean register(String userID, String password, String fullname,
+ String address, String email, String creditcard,
+ BigDecimal openBalance) {
AccountDataBean account = null;
AccountProfileDataBean profile = null;
-
+ EntityManager entityManager = emf.createEntityManager();
+
if (Log.doTrace())
Log.trace("TradeJPADirect:register", userID, password, fullname, address, email, creditcard, openBalance);
// Check to see if a profile with the desired userID already exists
+
profile = entityManager.find(AccountProfileDataBean.class, userID);
if (profile != null) {
Log.error("Failed to register new Account - AccountProfile with userID(" + userID + ") already exists");
return null;
- } else {
- profile = new AccountProfileDataBean(userID, password, fullname, address, email, creditcard);
+ }
+ else {
+ try {
+ entityManager.getTransaction().begin();
+ profile = new AccountProfileDataBean(userID, password, fullname,
+ address, email, creditcard);
account = new AccountDataBean(0, 0, null, new Timestamp(System.currentTimeMillis()), openBalance, openBalance, userID);
-
profile.setAccount(account);
account.setProfile(profile);
+ /*
+ * managed Transaction
+ */
+
+
+ entityManager.persist(profile);
+ entityManager.persist(account);
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
- entityManager.persist(profile);
- entityManager.persist(account);
}
-
+
return account;
}
- //@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
+ // @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception {
if (Log.doTrace())
Log.trace("TradeJPADirect:resetTrade", deleteAll);
- return (new TradeJDBCDirect(false)).resetTrade(deleteAll);
+ return(new TradeJDBCDirect(false)).resetTrade(deleteAll);
}
- private void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor,
- double sharesTraded) {
+ /*
+ * NO LONGER USE
+ */
+
+ private void publishQuotePriceChange(QuoteDataBean quote,
+ BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) {
if (!TradeConfig.getPublishQuotePriceChange())
return;
Log.error("TradeJPADirect:publishQuotePriceChange - is not implemented for this runtime mode");
throw new UnsupportedOperationException("TradeJPADirect:publishQuotePriceChange - is not implemented for this runtime mode");
}
- private OrderDataBean createOrder(AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding,
- String orderType, double quantity) {
+ /*
+ * new Method() that takes EntityManager as a parameter
+ */
+ private OrderDataBean createOrder(AccountDataBean account,
+ QuoteDataBean quote, HoldingDataBean holding, String orderType,
+ double quantity, EntityManager entityManager) {
OrderDataBean order;
if (Log.doTrace())
- Log.trace("TradeJPADirect:createOrder(orderID="
- + " account=" + ((account == null) ? null : account.getAccountID())
- + " quote=" + ((quote == null) ? null : quote.getSymbol())
- + " orderType=" + orderType
- + " quantity=" + quantity);
- try {
- order = new OrderDataBean(orderType, "open", new Timestamp(System.currentTimeMillis()), null,
- quantity, quote.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND),
- TradeConfig.getOrderFee(orderType), account, quote, holding);
- entityManager.persist(order);
- } catch (Exception e) {
+ Log.trace("TradeJPADirect:createOrder(orderID=" + " account="
+ + ((account == null) ? null : account.getAccountID())
+ + " quote=" + ((quote == null) ? null : quote.getSymbol())
+ + " orderType=" + orderType + " quantity=" + quantity);
+ try {
+ order = new OrderDataBean(orderType,
+ "open",
+ new Timestamp(System.currentTimeMillis()),
+ null,
+ quantity,
+ quote.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND),
+ TradeConfig.getOrderFee(orderType),
+ account,
+ quote,
+ holding);
+ entityManager.persist(order);
+ }
+ catch (Exception e) {
Log.error("TradeJPADirect:createOrder -- failed to create Order", e);
throw new RuntimeException("TradeJPADirect:createOrder -- failed to create Order", e);
}
return order;
}
- private HoldingDataBean createHolding(AccountDataBean account, QuoteDataBean quote, double quantity, BigDecimal purchasePrice) throws Exception {
- HoldingDataBean newHolding = new HoldingDataBean(quantity, purchasePrice, new Timestamp(System.currentTimeMillis()), account, quote);
- entityManager.persist(newHolding);
+ private HoldingDataBean createHolding(AccountDataBean account,
+ QuoteDataBean quote, double quantity, BigDecimal purchasePrice,
+ EntityManager entityManager) throws Exception {
+ HoldingDataBean newHolding = new HoldingDataBean(quantity,
+ purchasePrice, new Timestamp(System.currentTimeMillis()),
+ account, quote);
+ try {
+ /*
+ * manage transactions
+ */
+ entityManager.getTransaction().begin();
+ entityManager.persist(newHolding);
+ entityManager.getTransaction().commit();
+ }
+ catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ entityManager.close();
+ entityManager = null;
+ }
return newHolding;
}
-
- public double investmentReturn(double investment, double NetValue) throws Exception {
- if (Log.doTrace()) Log.trace("TradeJPADirect:investmentReturn");
-
+
+ public double investmentReturn(double investment, double NetValue)
+ throws Exception {
+ if (Log.doTrace())
+ Log.trace("TradeJPADirect:investmentReturn");
+
double diff = NetValue - investment;
double ir = diff / investment;
return ir;
}
-
+
public QuoteDataBean pingTwoPhase(String symbol) throws Exception {
- Log.error("TradeJPADirect:pingTwoPhase - is not implemented for this runtime mode");
+ Log
+ .error("TradeJPADirect:pingTwoPhase - is not implemented for this runtime mode");
throw new UnsupportedOperationException("TradeJPADirect:pingTwoPhase - is not implemented for this runtime mode");
}
@@ -680,28 +1002,32 @@
}
}
- @PostConstruct
- public void postConstruct() {
- Log.trace("POST CONSTRUCT");
- Log.trace("updateQuotePrices: " + TradeConfig.getUpdateQuotePrices());
- Log.trace("publishQuotePriceChange: " + TradeConfig.getPublishQuotePriceChange());
- }
-
/**
* TradeBuildDB needs this abstracted method
*/
public String checkDBProductName() throws Exception {
if (Log.doTrace())
Log.trace("TradeJPADirect:checkDBProductName");
- return (new TradeJDBCDirect(false)).checkDBProductName();
+ return(new TradeJDBCDirect(false)).checkDBProductName();
}
/**
* TradeBuildDB needs this abstracted method
*/
- public boolean recreateDBTables(Object[] sqlBuffer, java.io.PrintWriter out) throws Exception {
+ public boolean recreateDBTables(Object[] sqlBuffer, java.io.PrintWriter out)
+ throws Exception {
if (Log.doTrace())
- Log.trace("TradeJPADirect:recreateDBTables");
- return (new TradeJDBCDirect(false)).recreateDBTables(sqlBuffer, out);
+ Log.trace("TradeJPADirect:checkDBProductName");
+ return(new TradeJDBCDirect(false)).recreateDBTables(sqlBuffer, out);
+ }
+
+ /**
+ * Get mode - returns the persistence mode (TradeConfig.JPA)
+ *
+ * @return int mode
+ */
+ public int getMode() {
+ return TradeConfig.JPA;
}
+
}