geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jb...@apache.org
Subject svn commit: r775187 [4/10] - in /geronimo/daytrader/trunk: ./ daytrader-webonly/ daytrader-webonly/src/ daytrader-webonly/src/main/ daytrader-webonly/src/main/java/ daytrader-webonly/src/main/java/org/ daytrader-webonly/src/main/java/org/apache/ daytra...
Date Fri, 15 May 2009 15:17:45 GMT
Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java Fri May 15 15:17:36 2009
@@ -0,0 +1,193 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.util;
+
+import java.util.Collection;
+import java.util.Iterator;
+import org.apache.commons.logging.*;
+import org.apache.geronimo.samples.daytrader.*;
+
+public class Log {
+    private final static org.apache.commons.logging.Log log = LogFactory.getLog(Log.class);
+//A general purpose, high performance logging, tracing, statistic service
+
+    public static void log(String message) {
+        log.debug("DayTrader Log:" + new java.util.Date() + "------\n\t ");
+        log.debug(message); 
+    }
+
+    public static void log(String msg1, String msg2) {
+        log(msg1+msg2);
+    }
+
+    public static void log(String msg1, String msg2, String msg3) {
+        log(msg1+msg2+msg3);
+    }
+
+    public static void error(String message) {
+        message = "Error: " + message;
+        log.error(message);
+    }
+
+    public static void error(String message, Throwable e) {
+        error(message+"\n\t"+e.toString());
+        e.printStackTrace(System.out);
+    }
+
+    public static void error(String msg1, String msg2, Throwable e) {
+        error(msg1+"\n"+msg2+"\n\t", e);
+    }
+
+    public static void error(String msg1, String msg2, String msg3, Throwable e) {
+        error(msg1+"\n"+msg2+"\n"+msg3+"\n\t", e);
+    }
+
+    public static void error(Throwable e, String message) {
+        error(message+"\n\t",e);
+        e.printStackTrace(System.out);
+    }
+
+    public static void error(Throwable e, String msg1, String msg2) {
+        error(msg1+"\n"+msg2+"\n\t",e);
+    }
+
+    public static void error(Throwable e, String msg1, String msg2, String msg3) {
+        error(msg1+"\n"+msg2+"\n"+msg3+"\n\t", e);
+    }
+
+    public static void trace(String message) {
+        log.trace(message + " threadID="+ Thread.currentThread());
+    }
+
+    public static void trace(String message, Object parm1) {
+        trace(message+"("+parm1+")");
+    }
+
+    public static void trace(String message, Object parm1, Object parm2) {
+        trace(message+"("+parm1+", "+parm2+")");
+    }
+
+    public static void trace(String message, Object parm1, Object parm2, Object parm3) {
+        trace(message+"("+parm1+", "+parm2+", "+parm3+")");
+    }
+
+    public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4) {
+        trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4);
+    }
+
+    public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5) {
+        trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5);
+    }
+
+    public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, 
+                             Object parm5, Object parm6) {
+        trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5+", "+parm6);
+    }
+
+    public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, 
+                             Object parm5, Object parm6, Object parm7) {
+        trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5+", "+parm6+", "+parm7);
+    }
+
+    public static void traceEnter(String message) {
+        log.trace("Method enter --" + message);
+    }
+
+    public static void traceExit(String message) {
+        log.trace("Method exit  --" + message);
+    }
+
+    public static void stat(String message) {
+        log(message);
+    }
+
+    public static void debug(String message) {
+        log.debug(message);
+    }
+
+    public static void print(String message) {
+        log(message);
+    }
+
+    public static void printObject(Object o) {
+        log("\t"+o.toString());
+    }
+
+    public static void printCollection(Collection c) {
+        log("\t---Log.printCollection -- collection size=" + c.size());
+        Iterator it = c.iterator();
+        while ( it.hasNext() ) {
+            log("\t\t"+it.next().toString());
+        }
+        log("\t---Log.printCollection -- complete");        
+    }
+
+    public static void printCollection(String message, Collection c) {
+        log(message);
+        printCollection(c);
+    }
+
+    public static boolean doActionTrace() {
+        return getTrace() || getActionTrace();
+    }
+
+    public static boolean doTrace() {
+        return getTrace();
+    }
+
+    public static boolean doDebug() {
+        return true;
+    }
+
+    public static boolean doStat() {
+        return true;
+    }       
+
+    /**
+     * Gets the trace
+     * @return Returns a boolean
+     */
+    public static boolean getTrace() {
+        return TradeConfig.getTrace();
+    }
+
+    /**
+     * Gets the trace value for Trade actions only
+     * @return Returns a boolean
+     */
+    public static boolean getActionTrace() {
+        return TradeConfig.getActionTrace();
+    }
+
+    /**
+     * Sets the trace
+     * @param trace The trace to set
+     */
+    public static void setTrace(boolean traceValue) {
+        TradeConfig.setTrace(traceValue);
+    }
+
+    /**
+     * Sets the trace value for Trade actions only
+     * @param trace The trace to set
+     */
+    public static void setActionTrace(boolean traceValue) {
+        TradeConfig.setActionTrace(traceValue);
+    }
+
+}
+

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/Log.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java Fri May 15 15:17:36 2009
@@ -0,0 +1,63 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.util;
+
+
+/**
+ *
+ * To change this generated comment edit the template variable "typecomment":
+ * Window>Preferences>Java>Templates.
+ * To enable and disable the creation of type comments go to
+ * Window>Preferences>Java>Code Generation.
+ */
+public class MDBStats extends java.util.HashMap {
+
+
+    //Singleton class
+    private static MDBStats mdbStats = null;
+    private MDBStats() {
+    }
+
+    public static synchronized MDBStats getInstance() {
+        if (mdbStats == null)
+            mdbStats = new MDBStats();
+        return mdbStats;
+    }
+
+    public TimerStat addTiming(String type, long sendTime, long recvTime) {
+        TimerStat stats = null;
+        synchronized (type) {
+
+            stats = (TimerStat) get(type);
+            if (stats == null) stats = new TimerStat();
+
+            long time =  recvTime - sendTime;                               
+            if ( time > stats.getMax() ) stats.setMax(time);
+            if ( time < stats.getMin() ) stats.setMin(time);
+            stats.setCount(stats.getCount()+1);
+            stats.setTotalTime(stats.getTotalTime() + time);
+
+            put(type, stats);
+        }
+        return stats;
+    }
+
+    public synchronized void reset() {
+        clear();
+    }   
+
+}

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/MDBStats.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java Fri May 15 15:17:36 2009
@@ -0,0 +1,121 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.util;
+
+/**
+ *
+ * To change this generated comment edit the template variable "typecomment":
+ * Window>Preferences>Java>Templates.
+ * To enable and disable the creation of type comments go to
+ * Window>Preferences>Java>Code Generation.
+ */
+public class TimerStat {
+
+    private double min=1000000000.0, max=0.0, totalTime=0.0;
+    private int count;
+    /**
+     * Returns the count.
+     * @return int
+     */
+    public int getCount() {
+        return count;
+    }
+
+    /**
+     * Returns the max.
+     * @return double
+     */
+    public double getMax() {
+        return max;
+    }
+
+    /**
+     * Returns the min.
+     * @return double
+     */
+    public double getMin() {
+        return min;
+    }
+
+    /**
+     * Sets the count.
+     * @param count The count to set
+     */
+    public void setCount(int count) {
+        this.count = count;
+    }
+
+    /**
+     * Sets the max.
+     * @param max The max to set
+     */
+    public void setMax(double max) {
+        this.max = max;
+    }
+
+    /**
+     * Sets the min.
+     * @param min The min to set
+     */
+    public void setMin(double min) {
+        this.min = min;
+    }
+
+    /**
+     * Returns the totalTime.
+     * @return double
+     */
+    public double getTotalTime() {
+        return totalTime;
+    }
+
+    /**
+     * Sets the totalTime.
+     * @param totalTime The totalTime to set
+     */
+    public void setTotalTime(double totalTime) {
+        this.totalTime = totalTime;
+    }
+
+    /**
+     * Returns the max in Secs
+     * @return double
+     */
+    public double getMaxSecs() {
+        return max/1000.0;
+    }
+
+    /**
+     * Returns the min in Secs
+     * @return double
+     */
+    public double getMinSecs() {
+        return min/1000.0;
+    }
+
+    /**
+     * Returns the average time in Secs
+     * @return double
+     */
+    public double getAvgSecs() {
+
+        double avg =  (double)getTotalTime() / (double)getCount();
+        return avg / 1000.0;
+    }       
+
+
+}

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/util/TimerStat.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java Fri May 15 15:17:36 2009
@@ -0,0 +1,101 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import java.io.IOException;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import org.apache.geronimo.samples.daytrader.*;
+
+public class OrdersAlertFilter implements Filter {
+
+	/**
+	 * Constructor for CompletedOrdersAlertFilter
+	 */
+	public OrdersAlertFilter() {
+		super();
+	}
+
+	/**
+	 * @see Filter#init(FilterConfig)
+	 */
+	private FilterConfig filterConfig = null;
+	public void init(FilterConfig filterConfig) throws ServletException {
+	      this.filterConfig = filterConfig;
+	}
+
+	/**
+	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
+	 */
+	public void doFilter(
+		ServletRequest req,
+		ServletResponse resp,
+		FilterChain chain)
+		throws IOException, ServletException {
+		if (filterConfig == null)
+			return;
+		
+		try
+		{
+			String action = req.getParameter("action");
+			if ( action != null ) 
+			{
+				action = action.trim();
+				if ( (action.length() > 0) && (!action.equals("logout")) )
+				{
+					String userID;
+					if ( action.equals("login") )
+						userID = req.getParameter("uid");
+					else
+						userID = (String) ((HttpServletRequest) req).getSession().getAttribute("uidBean");
+					if ( (userID != null) && (userID.trim().length()>0) )
+					{	
+						TradeServices tAction=null;
+						if(TradeConfig.getAccessMode() == TradeConfig.STANDARD)
+						    tAction = new TradeAction();
+																
+						java.util.Collection closedOrders = tAction.getClosedOrders(userID);
+						if ( (closedOrders!=null) && (closedOrders.size() > 0) )
+							req.setAttribute("closedOrders", closedOrders);
+						if (Log.doTrace()) Log.printCollection("OrderAlertFilter: userID="+userID+" closedOrders=", closedOrders);
+					}
+				}	
+			}
+		}
+		catch (Exception e)
+		{
+			Log.error(e, "OrdersAlertFilter - Error checking for closedOrders");
+		}
+
+        ServletContext sc = filterConfig.getServletContext();
+        //String xyz = (String) sc.getAttribute("hitCounter");
+		chain.doFilter(req, resp/*wrapper*/);        
+
+	}
+
+	/**
+	 * @see Filter#destroy()
+	 */
+	public void destroy() {
+		this.filterConfig = null;	
+	}
+
+}
+

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/OrdersAlertFilter.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java Fri May 15 15:17:36 2009
@@ -0,0 +1,106 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import org.apache.geronimo.samples.daytrader.*;
+
+public class TestServlet extends HttpServlet {
+
+
+	public void init(ServletConfig config) throws ServletException
+	{
+		super.init(config);
+	}
+	
+	
+   /**
+	* Process incoming HTTP GET requests
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/
+	public void doGet(HttpServletRequest request, HttpServletResponse response)
+		throws ServletException, IOException
+	{
+		performTask(request,response);
+	}
+
+   /**
+	* Process incoming HTTP POST requests
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/
+	public void doPost(HttpServletRequest request, HttpServletResponse response)
+		throws ServletException, IOException
+	{
+		performTask(request,response);
+	}	
+
+   /**
+	* Main service method for TradeAppServlet
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/    	
+	public void performTask(HttpServletRequest req, HttpServletResponse resp)
+		throws ServletException, IOException 
+	{
+		try {
+			Log.debug("Enter TestServlet doGet");
+			TradeConfig.runTimeMode = TradeConfig.DIRECT;
+			for (int i=0; i<10; i++) 
+			{
+				new TradeAction().createQuote("s:"+i, "Company " + i, new BigDecimal(i*1.1));
+			}
+			/*
+			
+			AccountDataBean accountData = new TradeAction().register("user1", "password", "fullname", "address", 
+											"email", "creditCard", new BigDecimal(123.45), false);
+
+			OrderDataBean orderData = new TradeAction().buy("user1", "s:1", 100.0);
+			orderData = new TradeAction().buy("user1", "s:2", 200.0);
+			Thread.sleep(5000);
+			accountData = new TradeAction().getAccountData("user1");
+			Collection holdingDataBeans = new TradeAction().getHoldings("user1");
+			PrintWriter out = resp.getWriter();
+			resp.setContentType("text/html");
+			out.write("<HEAD></HEAD><BODY><BR><BR>");
+			out.write(accountData.toString());
+			Log.printCollection("user1 Holdings", holdingDataBeans);
+			ServletContext sc  = getServletContext();
+			req.setAttribute("results", "Success");
+			req.setAttribute("accountData", accountData);
+			req.setAttribute("holdingDataBeans", holdingDataBeans);
+			getServletContext().getRequestDispatcher("/tradehome.jsp").include(req, resp);
+			out.write("<BR><BR>done.</BODY>");
+			*/
+		}
+		catch (Exception e)
+		{
+			Log.error("TestServletException", e);
+		}
+	}
+}
+

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TestServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java Fri May 15 15:17:36 2009
@@ -0,0 +1,202 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.apache.geronimo.samples.daytrader.direct.*;
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import java.io.IOException;
+import org.apache.geronimo.samples.daytrader.*;
+
+/**
+ * 
+ * TradeAppServlet provides the standard web interface to Trade and can be
+ * accessed with the Go Trade! link. Driving benchmark load using this interface
+ * requires a sophisticated web load generator that is capable of filling HTML
+ * forms and posting dynamic data.
+ */
+
+public class TradeAppServlet extends HttpServlet {
+
+    /**
+     * Servlet initialization method.
+     */
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+        java.util.Enumeration en = config.getInitParameterNames();
+        while (en.hasMoreElements()) {
+            String parm = (String) en.nextElement();
+            String value = config.getInitParameter(parm);
+            TradeConfig.setConfigParam(parm, value);
+        }
+        try {
+            TradeDirect.init();
+        } catch (Exception e) {
+            Log.error(e,
+                    "TradeAppServlet:init -- Error initializing TradeDirect");
+        }
+    }
+
+    /**
+     * Returns a string that contains information about TradeScenarioServlet
+     * 
+     * @return The servlet information
+     */
+    public java.lang.String getServletInfo() {
+        return "TradeAppServlet provides the standard web interface to Trade";
+    }
+
+    /**
+     * Process incoming HTTP GET requests
+     * 
+     * @param request
+     *            Object that encapsulates the request to the servlet
+     * @param response
+     *            Object that encapsulates the response from the servlet
+     */
+    public void doGet(javax.servlet.http.HttpServletRequest request,
+            javax.servlet.http.HttpServletResponse response)
+            throws ServletException, IOException {
+        performTask(request, response);
+    }
+
+    /**
+     * Process incoming HTTP POST requests
+     * 
+     * @param request
+     *            Object that encapsulates the request to the servlet
+     * @param response
+     *            Object that encapsulates the response from the servlet
+     */
+    public void doPost(javax.servlet.http.HttpServletRequest request,
+            javax.servlet.http.HttpServletResponse response)
+            throws ServletException, IOException {
+        performTask(request, response);
+    }
+
+    /**
+     * Main service method for TradeAppServlet
+     * 
+     * @param request
+     *            Object that encapsulates the request to the servlet
+     * @param response
+     *            Object that encapsulates the response from the servlet
+     */
+    public void performTask(HttpServletRequest req, HttpServletResponse resp)
+            throws ServletException, IOException {
+
+        String action = null;
+        String userID = null;
+        // String to create full dispatch path to TradeAppServlet w/ request
+        // Parameters
+        String dispPath = null; // Dispatch Path to TradeAppServlet
+
+        resp.setContentType("text/html");
+        TradeServletAction tsAction = new TradeServletAction();
+
+        // Dyna - need status string - prepended to output
+        action = req.getParameter("action");
+
+        ServletContext ctx = getServletConfig().getServletContext();
+
+        if (action == null) {
+            tsAction.doWelcome(ctx, req, resp, "");
+            return;
+        } else if (action.equals("login")) {
+            userID = req.getParameter("uid");
+            String passwd = req.getParameter("passwd");
+            String inScenario = req.getParameter("inScenario");
+            tsAction.doLogin(ctx, req, resp, userID, passwd);
+            return;
+        } else if (action.equals("register")) {
+            userID = req.getParameter("user id");
+            String passwd = req.getParameter("passwd");
+            String cpasswd = req.getParameter("confirm passwd");
+            String fullname = req.getParameter("Full Name");
+            String ccn = req.getParameter("Credit Card Number");
+            String money = req.getParameter("money");
+            String email = req.getParameter("email");
+            String smail = req.getParameter("snail mail");
+            tsAction.doRegister(ctx, req, resp, userID, passwd, cpasswd,
+                    fullname, ccn, money, email, smail);
+            return;
+        }
+
+        // The rest of the operations require the user to be logged in -
+        // Get the Session and validate the user.
+        HttpSession session = req.getSession();
+        userID = (String) session.getAttribute("uidBean");
+
+        if (userID == null) {
+            System.out
+                    .println("TradeAppServlet service error: User Not Logged in");
+            tsAction.doWelcome(ctx, req, resp, "User Not Logged in");
+            return;
+        }
+        if (action.equals("quotes")) {
+            String symbols = req.getParameter("symbols");
+            tsAction.doQuotes(ctx, req, resp, userID, symbols);
+        } else if (action.equals("buy")) {
+            String symbol = req.getParameter("symbol");
+            String quantity = req.getParameter("quantity");
+            tsAction.doBuy(ctx, req, resp, userID, symbol, quantity);
+        } else if (action.equals("sell")) {
+            int holdingID = Integer.parseInt(req.getParameter("holdingID"));
+            tsAction.doSell(ctx, req, resp, userID, new Integer(holdingID));
+        } else if (action.equals("portfolio")
+                || action.equals("portfolioNoEdge")) {
+            tsAction.doPortfolio(ctx, req, resp, userID, "Portfolio as of "
+                    + new java.util.Date());
+        } else if (action.equals("logout")) {
+            tsAction.doLogout(ctx, req, resp, userID);
+        } else if (action.equals("home")) {
+            tsAction.doHome(ctx, req, resp, userID, "Ready to Trade");
+        } else if (action.equals("account")) {
+            tsAction.doAccount(ctx, req, resp, userID, "");
+        } else if (action.equals("update_profile")) {
+            String password = req.getParameter("password");
+            String cpassword = req.getParameter("cpassword");
+            String fullName = req.getParameter("fullname");
+            String address = req.getParameter("address");
+            String creditcard = req.getParameter("creditcard");
+            String email = req.getParameter("email");
+            tsAction.doAccountUpdate(ctx, req, resp, userID,
+                    password == null ? "" : password.trim(),
+                    cpassword == null ? "" : cpassword.trim(),
+                    fullName == null ? "" : fullName.trim(),
+                    address == null ? "" : address.trim(),
+                    creditcard == null ? "" : creditcard.trim(),
+                    email == null ? "" : email.trim());
+        } else {
+            System.out.println("TradeAppServlet: Invalid Action=" + action);
+            tsAction.doWelcome(ctx, req, resp,
+                    "TradeAppServlet: Invalid Action" + action);
+        }
+    }
+
+    private void sendRedirect(HttpServletResponse resp, String page)
+            throws ServletException, IOException {
+        resp.sendRedirect(resp.encodeRedirectURL(page));
+    }
+
+    // URL Path Prefix for dispatching to TradeAppServlet
+    private final static String tasPathPrefix = "/app?action=";
+
+}
\ No newline at end of file

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeAppServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java Fri May 15 15:17:36 2009
@@ -0,0 +1,310 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+
+import org.apache.geronimo.samples.daytrader.direct.TradeDirect;
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import org.apache.geronimo.samples.daytrader.*;
+
+/**
+ * TradeBuildDB uses operations provided by the TradeApplication to (a) create the Database tables
+ * (b)populate a DayTrader database without creating the tables. Specifically, a 
+ * new DayTrader User population is created using UserIDs of the form "uid:xxx" 
+ * where xxx is a sequential number (e.g. uid:0, uid:1, etc.). New stocks are also created of the 
+ * form "s:xxx", again where xxx represents sequential numbers (e.g. s:1, s:2, etc.)
+ */
+public class TradeBuildDB {
+
+	private boolean verbose = true;
+	private TradeConfig t = new TradeConfig();
+
+	/**
+	  * Populate a Trade DB using standard out as a log
+	  */
+	public TradeBuildDB() throws Exception {
+		this(new java.io.PrintWriter(System.out), null);
+	}
+
+	/**
+		* Re-create the DayTrader db tables and populate them OR just populate a DayTrader DB, logging to the provided output stream
+		*/
+	public TradeBuildDB(java.io.PrintWriter out, String warPath) throws Exception {
+		String symbol, companyName;
+		int errorCount = 0; // Give up gracefully after 10 errors
+		TradeAction tradeAction = new TradeAction();
+
+		//  TradeStatistics.statisticsEnabled=false;  // disable statistics
+		out.println(
+			"<HEAD><BR><EM> TradeBuildDB: Building DayTrader Database...</EM><BR> This operation will take several minutes. Please wait...</HEAD>");
+		out.println("<BODY>");
+		
+		if (warPath != null)
+		{	
+			//out.println("<BR>TradeBuildDB: **** warPath= "+warPath+" ****</BR></BODY>");
+			
+			TradeDirect tradeDirect = new TradeDirect();
+			boolean success = false;
+			String dbProductName = null;
+			File ddlFile = null;
+			Object[] sqlBuffer = null;
+			
+			//Find out the Database being used
+			try
+			{
+				dbProductName = tradeDirect.checkDBProductName();
+			}
+			catch (Exception e)
+			{
+				Log.error(e, "TradeBuildDB: Unable to check DB Product name");
+			}
+			if (dbProductName == null)
+			{
+				out.println("<BR>TradeBuildDB: **** Unable to check DB Product name, please check Database/AppServer configuration and retry ****</BR></BODY>");
+				return;
+			}
+			
+			//Locate DDL file for the specified database
+			try
+			{
+				out.println("<BR>TradeBuildDB: **** Database Product detected: "+dbProductName+" ****</BR>");
+				if (dbProductName.startsWith("DB2/")) // if db is DB2
+				{
+					ddlFile = new File(warPath+File.separatorChar+"dbscripts"+File.separatorChar+"db2"+File.separatorChar+"Table.ddl");
+				}
+				else if (dbProductName.startsWith("Apache Derby")) //if db is Derby
+				{
+					ddlFile = new File(warPath+File.separatorChar+"dbscripts"+File.separatorChar+"derby"+File.separatorChar+"Table.ddl");
+				}
+				else if (dbProductName.startsWith("Oracle")) // if the Db is Oracle
+				{
+					ddlFile = new File(warPath+File.separatorChar+"dbscripts"+File.separatorChar+"oracle"+File.separatorChar+"Table.ddl");
+				}
+				else // Unsupported "Other" Database
+				{
+					ddlFile = new File(warPath+File.separatorChar+"dbscripts"+File.separatorChar+"other"+File.separatorChar+"Table.ddl");
+					out.println("<BR>TradeBuildDB: **** This Database is unsupported/untested use at your own risk ****</BR>");
+				}
+				
+				if (!ddlFile.exists())
+				{
+					Log.error("TradeBuildDB: DDL file doesnt exist at path "+ ddlFile.getCanonicalPath()+" , please provide the file and retry");
+					out.println("<BR>TradeBuildDB: DDL file doesnt exist at path <I>"+ ddlFile.getCanonicalPath()+"</I> , please provide the file and retry ****</BR></BODY>");
+					return;
+				}
+				out.println("<BR>TradeBuildDB: **** The DDL file at path <I>"+ ddlFile.getCanonicalPath()+"</I> will be used ****</BR>");
+				out.flush();
+			}
+			catch (Exception e)
+			{
+				Log.error(e, "TradeBuildDB: Unable to locate DDL file for the specified database");
+				out.println("<BR>TradeBuildDB: **** Unable to locate DDL file for the specified database ****</BR></BODY>");
+				return;
+			}
+			
+			//parse the DDL file and fill the SQL commands into a buffer
+			try
+			{
+				sqlBuffer = parseDDLToBuffer(ddlFile);
+			}
+			catch (Exception e)
+			{
+				Log.error(e, "TradeBuildDB: Unable to parse DDL file");
+				out.println("<BR>TradeBuildDB: **** Unable to parse DDL file for the specified database ****</BR></BODY>");
+				return;
+			}
+			if ((sqlBuffer == null)||(sqlBuffer.length == 0))
+			{
+				out.println("<BR>TradeBuildDB: **** Parsing DDL file returned empty buffer, please check that a valid DB specific DDL file is available and retry ****</BR></BODY>");
+				return;
+			}
+			
+			// send the sql commands buffer to drop and recreate the Daytrader tables
+			out.println("<BR>TradeBuildDB: **** Dropping and Recreating the DayTrader tables... ****</BR>");
+			try
+			{
+				success = tradeDirect.recreateDBTables(sqlBuffer, out);
+			}
+			catch (Exception e)
+			{
+				Log.error(e, "TradeBuildDB: Unable to drop and recreate DayTrader Db Tables, please check for database consistency before continuing");
+			}
+			if (!success)
+			{
+				out.println("<BR>TradeBuildDB: **** Unable to drop and recreate DayTrader Db Tables, please check for database consistency before continuing ****</BR></BODY>");
+				return;
+			}
+			out.println("<BR>TradeBuildDB: **** DayTrader tables successfully created! ****</BR><BR><b> Please Stop and Re-start your Daytrader application (or your application server) and then use the \"Repopulate Daytrader Database\" link to populate your database.</b></BR><BR><BR></BODY>");
+			return;
+		} // end of createDBTables
+		
+		out.println("<BR>TradeBuildDB: **** Creating " + TradeConfig.getMAX_QUOTES() + " Quotes ****</BR>");
+		//Attempt to delete all of the Trade users and Trade Quotes first
+		try
+		{
+			tradeAction.resetTrade(true);
+		}
+		catch (Exception e)
+		{
+			Log.error(e, "TradeBuildDB: Unable to delete Trade users (uid:0, uid:1, ...) and Trade Quotes (s:0, s:1, ...)");
+		}
+		for (int i = 0; i < TradeConfig.getMAX_QUOTES(); i++) {
+			symbol = "s:" + i;
+			companyName = "S" + i + " Incorporated";
+			try {
+				QuoteDataBean quoteData =
+					tradeAction.createQuote(
+						symbol,
+						companyName,
+						new java.math.BigDecimal(TradeConfig.rndPrice()));
+				if (i % 10 == 0) {
+					out.print("....." + symbol);
+					if (i % 100 == 0) {
+						out.println(" -<BR>");
+						out.flush();
+					}
+				}
+			} catch (Exception e) {
+				if (errorCount++ >= 10) {
+					String error = "Populate Trade DB aborting after 10 create quote errors. Check the EJB datasource configuration. Check the log for details <BR><BR> Exception is: <BR> " + e.toString();						
+					Log.error(e, error);
+					throw e;
+				}	
+			}
+		}
+		out.println("<BR>");
+		out.println("<BR>**** Registering " + TradeConfig.getMAX_USERS() + " Users **** ");
+		errorCount = 0; //reset for user registrations
+
+		// Registration is a formal operation in Trade 2. 
+		for (int i = 0; i < TradeConfig.getMAX_USERS(); i++) {
+			String userID = "uid:" + i;
+			String fullname = TradeConfig.rndFullName();
+			String email = TradeConfig.rndEmail(userID);
+			String address = TradeConfig.rndAddress();
+			String creditcard = TradeConfig.rndCreditCard();
+			double initialBalance = (double) (TradeConfig.rndInt(100000)) + 200000;
+			if (i == 0) {
+				initialBalance = 1000000; // uid:0 starts with a cool million.
+			}
+			try {
+				AccountDataBean accountData =
+					tradeAction.register(
+						userID,
+						"xxx",
+						fullname,
+						address,
+						email,
+						creditcard,
+						new BigDecimal(initialBalance));
+				String results;
+				if (accountData != null) {
+					if (i % 50 == 0) {
+						out.print("<BR>Account# " +accountData.getAccountID() + " userID=" + userID);
+					} // end-if
+
+					int holdings = TradeConfig.rndInt(TradeConfig.getMAX_HOLDINGS()+1); // 0-MAX_HOLDING (inclusive), avg holdings per user = (MAX-0)/2
+					double quantity = 0;
+					OrderDataBean orderData;
+					for (int j = 0; j < holdings; j++) {
+						symbol = TradeConfig.rndSymbol();
+						quantity = TradeConfig.rndQuantity();
+						orderData = tradeAction.buy(userID, symbol, quantity, TradeConfig.orderProcessingMode);
+					} // end-for
+					if (i % 50 == 0) {
+						out.println(" has " + holdings + " holdings.");
+						out.flush();
+					} // end-if
+				} else {
+					out.println("<BR>UID " + userID + " already registered.</BR>");
+					out.flush();
+				} // end-if
+
+			} catch (Exception e) {
+				if (errorCount++ >= 10) {
+					AccountProfileDataBean accountProfileData = null;
+
+					String error = "Populate Trade DB aborting after 10 user registration errors. Check the log for details. <BR><BR> Exception is: <BR>"	+ e.toString();
+					Log.error(e, error);
+					throw e;					
+				}
+			}
+		} // end-for
+		out.println("</BODY>");
+	}
+	
+	public Object[] parseDDLToBuffer(File ddlFile) throws Exception 
+	{
+        BufferedReader br = null;
+        ArrayList sqlBuffer = new ArrayList(30); //initial capacity 30 assuming we have 30 ddl-sql statements to read
+
+        try 
+        {
+        	if (Log.doTrace()) Log.traceEnter("TradeBuildDB:parseDDLToBuffer - " + ddlFile);
+        	
+			br = new BufferedReader(new FileReader(ddlFile));
+            String s;
+			String sql = new String();
+            while ((s = br.readLine()) != null) 
+            {
+				s = s.trim();
+				if ((s.length() != 0) && (s.charAt(0) != '#'))  // Empty lines or lines starting with "#" are ignored
+				{
+					sql = sql +" "+ s;
+					if (s.endsWith(";")) // reached end of sql statement
+					{
+						sql = sql.replace(';', ' '); //remove the semicolon
+						//System.out.println (sql);
+						sqlBuffer.add(sql);
+						sql = "";
+					}
+				}
+            }
+        } 
+        catch (IOException ex)
+        {
+        	Log.error("TradeBuildDB:parseDDLToBuffer Exeception during open/read of File: " + ddlFile, ex);
+        	throw ex;
+        }
+        finally 
+        {
+            if (br != null) 
+            {
+                try 
+                {
+                    br.close();
+                } catch(IOException ex) 
+                {
+                	Log.error("TradeBuildDB:parseDDLToBuffer Failed to close BufferedReader", ex);
+                }
+            }
+        }
+        return sqlBuffer.toArray();
+	}
+	
+	public static void main(String args[]) throws Exception {
+		new TradeBuildDB();
+
+	}
+}

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeBuildDB.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java Fri May 15 15:17:36 2009
@@ -0,0 +1,436 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import java.io.IOException;
+import org.apache.geronimo.samples.daytrader.*;
+
+/**
+ * TradeConfigServlet provides a servlet interface to adjust DayTrader runtime parameters.
+ * TradeConfigServlet updates values in the {@link org.apache.geronimo.samples.daytrader.web.TradeConfig} JavaBean holding 
+ * all configuration and runtime parameters for the Trade application
+ *
+ */
+public class TradeConfigServlet extends HttpServlet {
+	
+   /**
+	* Servlet initialization method.
+	*/
+	public void init(ServletConfig config) throws ServletException
+	{
+		super.init(config);
+	}
+	/**
+	 * Create the TradeConfig bean and pass it the config.jsp page 
+	 * to display the current Trade runtime configuration
+	 * Creation date: (2/8/2000 3:43:59 PM)
+	 */
+	void doConfigDisplay(
+		HttpServletRequest req, 
+		HttpServletResponse resp, 
+		String results)
+		throws Exception {
+
+		TradeConfig currentConfig = new TradeConfig();
+
+		req.setAttribute("tradeConfig", currentConfig);
+		req.setAttribute("status", results);
+		getServletConfig()
+			.getServletContext()
+			.getRequestDispatcher(TradeConfig.getPage(TradeConfig.CONFIG_PAGE))
+			.include(req, resp); 
+	}
+	
+	void doResetTrade(
+		HttpServletRequest req, 
+		HttpServletResponse resp, 
+		String results)
+		throws Exception
+	{
+		RunStatsDataBean runStatsData = new RunStatsDataBean();
+		TradeConfig currentConfig = new TradeConfig();		
+		try
+		{
+			runStatsData = new TradeAction().resetTrade(false);
+			
+			req.setAttribute("runStatsData", runStatsData);
+			req.setAttribute("tradeConfig", currentConfig);
+			results += "Trade Reset completed successfully";						
+			req.setAttribute("status", results);
+
+		}
+		catch (Exception e)
+		{
+			results += "Trade Reset Error  - see log for details";
+			Log.error(e, 	results);
+			throw e;
+		}
+		getServletConfig()
+				.getServletContext()
+				.getRequestDispatcher(TradeConfig.getPage(TradeConfig.STATS_PAGE))
+				.include(req, resp); 			
+		
+	}
+	
+	
+	/**
+	 * Update Trade runtime configuration paramaters
+	 * Creation date: (2/8/2000 3:44:24 PM)
+	 */
+	void doConfigUpdate(HttpServletRequest req, HttpServletResponse resp)
+		throws Exception {
+
+		TradeConfig currentConfig = new TradeConfig();
+
+		String currentConfigStr = "\n\n########## Trade configuration update. Current config:\n\n";
+		String runTimeModeStr = req.getParameter("RunTimeMode");
+		if (runTimeModeStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(runTimeModeStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.runTimeModeNames.length)) //Input validation
+					TradeConfig.runTimeMode = i;
+			}
+			catch (Exception e)
+			{
+				//>>rjm
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set runtimemode to " + runTimeModeStr, 
+					"reverting to current value");
+
+			} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tRunTimeMode:\t\t" + TradeConfig.runTimeModeNames[TradeConfig.runTimeMode] + "\n";
+		
+		/* Add JPA layer choice to avoid some ugly Hibernate bugs */
+		String jpaLayerStr = req.getParameter("JPALayer");
+		if (jpaLayerStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(jpaLayerStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.jpaLayerNames.length)) //Input validation
+					TradeConfig.jpaLayer = i;
+			}
+			catch (Exception e)
+			{				
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set JPALayer to " + jpaLayerStr, 
+					"reverting to current value");
+
+			} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tJPALayer:\t\t" + TradeConfig.jpaLayerNames[TradeConfig.jpaLayer] + "\n";
+		
+
+		String orderProcessingModeStr = req.getParameter("OrderProcessingMode");
+		if (orderProcessingModeStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(orderProcessingModeStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.orderProcessingModeNames.length)) //Input validation
+					TradeConfig.orderProcessingMode = i;
+			}
+			catch (Exception e)
+			{
+				//>>rjm
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set orderProcessing to " + orderProcessingModeStr, 
+					"reverting to current value");
+
+			} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tOrderProcessingMode:\t" + TradeConfig.orderProcessingModeNames[TradeConfig.orderProcessingMode]  + "\n";		
+		
+		String accessModeStr = req.getParameter("AcessMode");
+		if (accessModeStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(accessModeStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.accessModeNames.length) && (i != TradeConfig.getAccessMode())) //Input validation
+					TradeConfig.setAccessMode(i);
+			}
+			catch (Exception e)
+			{
+				//>>rjm
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set orderProcessing to " + orderProcessingModeStr, 
+					"reverting to current value");
+
+			} // If the value is bad, simply revert to current
+		}		
+		currentConfigStr += "\t\tAcessMode:\t\t" + TradeConfig.accessModeNames[TradeConfig.getAccessMode()]  + "\n";		
+		
+			
+		String workloadMixStr = req.getParameter("WorkloadMix");
+		if (workloadMixStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(workloadMixStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.workloadMixNames.length)) //Input validation
+					TradeConfig.workloadMix = i;
+			}
+			catch (Exception e)
+			{
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set workloadMix to " + workloadMixStr, 
+					"reverting to current value");
+			} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tWorkload Mix:\t\t" + TradeConfig.workloadMixNames[TradeConfig.workloadMix]  + "\n";		
+		
+		
+		
+		String webInterfaceStr = req.getParameter("WebInterface");
+		if (webInterfaceStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(webInterfaceStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.webInterfaceNames.length)) //Input validation
+					TradeConfig.webInterface = i;
+			}
+			catch (Exception e)
+			{
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set WebInterface to " + webInterfaceStr, 
+					"reverting to current value");
+
+
+			} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tWeb Interface:\t\t" + TradeConfig.webInterfaceNames[TradeConfig.webInterface]  + "\n";		
+		
+		String cachingTypeStr = req.getParameter("CachingType");
+		if (cachingTypeStr != null)
+		{
+			try
+			{
+				int i = Integer.parseInt(cachingTypeStr);
+				if ((i >= 0)
+					&& (i < TradeConfig.cachingTypeNames.length)) //Input validation
+					TradeConfig.cachingType = i;
+			}
+			catch (Exception e)
+			{
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"trying to set CachingType to " + cachingTypeStr, 
+					"reverting to current value");
+				} // If the value is bad, simply revert to current
+		}
+		currentConfigStr += "\t\tCachingType:\t\t" + TradeConfig.cachingTypeNames[TradeConfig.cachingType]  + "\n";		
+
+		String parm = req.getParameter("SOAP_URL");
+		if ((parm != null) && (parm.length() > 0))
+		{
+			if (!TradeConfig.getSoapURL().equals(parm)) {
+				TradeConfig.setSoapURL(parm);
+			}
+		}
+		else
+		{
+			TradeConfig.setSoapURL(null);
+		}
+
+		parm = req.getParameter("MaxUsers");
+		if ((parm != null) && (parm.length() > 0))
+		{
+			try
+			{
+				TradeConfig.setMAX_USERS(Integer.parseInt(parm));
+			}
+			catch (Exception e)
+			{
+				Log.error(
+					e, 
+					"TradeConfigServlet.doConfigUpdate(..): minor exception caught", 
+					"Setting maxusers, probably error parsing string to int:" + parm, 
+					"revertying to current value: " + TradeConfig.getMAX_USERS());
+
+			} //On error, revert to saved
+		}
+		parm = req.getParameter("MaxQuotes");
+		if ((parm != null) && (parm.length() > 0))
+		{
+			try
+			{
+				TradeConfig.setMAX_QUOTES(Integer.parseInt(parm));
+			}
+			catch (Exception e)
+			{
+				//>>rjm
+				Log.error(
+					e, 
+					"TradeConfigServlet: minor exception caught", 
+					"trying to set max_quotes, error on parsing int " + parm, 
+					"reverting to current value " + TradeConfig.getMAX_QUOTES());
+				//<<rjm
+
+			} //On error, revert to saved
+		}
+		currentConfigStr += "\t\t#Trade  Users:\t\t" + TradeConfig.getMAX_USERS()  + "\n";		
+		currentConfigStr += "\t\t#Trade Quotes:\t\t" + TradeConfig.getMAX_QUOTES()  + "\n";		
+		
+                parm = req.getParameter("marketSummaryInterval");
+                if ((parm != null) && (parm.length() > 0)) {
+                        try {
+                                TradeConfig.setMarketSummaryInterval(Integer.parseInt(parm));
+                        }
+                        catch (Exception e) {
+                                Log.error(
+                                        e, 
+                                        "TradeConfigServlet: minor exception caught", 
+                                        "trying to set marketSummaryInterval, error on parsing int " + parm, 
+                                        "reverting to current value " + TradeConfig.getMarketSummaryInterval());
+
+                        }
+                }
+                currentConfigStr += "\t\tMarket Summary Interval:\t\t" + TradeConfig.getMarketSummaryInterval()  + "\n";
+		
+		parm = req.getParameter("primIterations");
+		if ((parm != null) && (parm.length() > 0)) {
+			try {
+				TradeConfig.setPrimIterations(Integer.parseInt(parm));
+			}
+			catch (Exception e) {
+				Log.error(
+					e, 
+					"TradeConfigServlet: minor exception caught", 
+					"trying to set primIterations, error on parsing int " + parm, 
+					"reverting to current value " + TradeConfig.getPrimIterations());
+
+			}
+		}
+		currentConfigStr += "\t\tPrimitive Iterations:\t\t" + TradeConfig.getPrimIterations()  + "\n";
+                
+		String enablePublishQuotePriceChange = req.getParameter("EnablePublishQuotePriceChange");
+		
+		if (enablePublishQuotePriceChange != null)
+			TradeConfig.setPublishQuotePriceChange(true);
+		else 
+			TradeConfig.setPublishQuotePriceChange(false);
+		currentConfigStr += "\t\tTradeStreamer MDB Enabled:\t" + TradeConfig.getPublishQuotePriceChange() + "\n";
+		
+		String enableTrace = req.getParameter("EnableTrace");
+		if (enableTrace != null)
+			Log.setTrace(true);
+		else 
+			Log.setTrace(false);			
+		String enableActionTrace = req.getParameter("EnableActionTrace");
+		if (enableActionTrace != null)
+			Log.setActionTrace(true);
+		else 
+			Log.setActionTrace(false);						
+
+        String enableLongRun = req.getParameter("EnableLongRun");
+        
+        if (enableLongRun != null)
+            TradeConfig.setLongRun(true);
+        else 
+            TradeConfig.setLongRun(false);
+        currentConfigStr += "\t\tLong Run Enabled:\t\t" + TradeConfig.getLongRun()  + "\n";
+		
+		
+		System.out.println(currentConfigStr);
+
+	}
+
+	public void service(HttpServletRequest req, HttpServletResponse resp)
+		throws ServletException, IOException {
+
+		String action = null;
+		String result = "";
+		
+		resp.setContentType("text/html");
+		try
+		{
+			action = req.getParameter("action");
+			if (action == null)
+			{
+				doConfigDisplay(req, resp, result + "<b><br>Current DayTrader Configuration:</br></b>");
+				return;
+			}
+			else if (action.equals("updateConfig"))
+			{
+				doConfigUpdate(req, resp);
+				result = "<B><BR>DayTrader Configuration Updated</BR></B>";
+			}
+			else if (action.equals("resetTrade"))
+			{
+				doResetTrade(req, resp, "");
+				return;
+			}
+			else if (action.equals("buildDB"))
+			{
+				resp.setContentType("text/html");
+                                new TradeBuildDB(resp.getWriter(), null);
+				result = "DayTrader Database Built - " + TradeConfig.getMAX_USERS() + "users created";
+			}
+                        else if (action.equals("buildDBTables"))
+                        {
+ 
+                                resp.setContentType("text/html");
+                                new TradeBuildDB(resp.getWriter(), getServletConfig().getServletContext().getRealPath("/"));
+                        }
+			doConfigDisplay(req, resp, result + "Current DayTrader Configuration:");
+		}
+		catch (Exception e)
+		{
+			Log.error(
+				e, 
+				"TradeConfigServlet.service(...)", 
+				"Exception trying to perform action=" + action);
+
+			resp.sendError(
+				500, 
+				"TradeConfigServlet.service(...)"
+					+ "Exception trying to perform action="
+					+ action
+                                        + "\nException details: " + e.toString()); 
+			
+		}
+	}
+}

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeConfigServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java
URL: http://svn.apache.org/viewvc/geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java?rev=775187&view=auto
==============================================================================
--- geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java (added)
+++ geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java Fri May 15 15:17:36 2009
@@ -0,0 +1,297 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.samples.daytrader.web;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.apache.geronimo.samples.daytrader.util.*;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.io.IOException;
+import java.io.PrintWriter;
+import org.apache.geronimo.samples.daytrader.*;
+
+/**
+ * TradeScenarioServlet emulates a population of web users by generating a specific Trade operation 
+ * for a randomly chosen user on each access to the URL. Test this servlet by clicking Trade Scenario 
+ * and hit "Reload" on your browser to step through a Trade Scenario. To benchmark using this URL aim 
+ * your favorite web load generator (such as AKStress) at the Trade Scenario URL and fire away.
+ */
+public class TradeScenarioServlet extends HttpServlet {
+
+   /**
+	* Servlet initialization method.
+	*/
+	public void init(ServletConfig config) throws ServletException
+	{
+		super.init(config);
+		java.util.Enumeration en = config.getInitParameterNames();
+		while ( en.hasMoreElements() )
+		{
+			String parm = (String) en.nextElement();
+			String value = config.getInitParameter(parm);
+			TradeConfig.setConfigParam(parm, value);
+		}
+	}
+	
+   /**
+	* Returns a string that contains information about TradeScenarioServlet
+	*
+	* @return The servlet information
+	*/
+	public java.lang.String getServletInfo()
+	{
+		return "TradeScenarioServlet emulates a population of web users";
+	}	
+
+
+
+   /**
+	* Process incoming HTTP GET requests
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/
+	public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
+		throws ServletException, IOException
+	{
+		performTask(request,response);
+	}
+
+   /**
+	* Process incoming HTTP POST requests
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/
+	public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
+		throws ServletException, IOException
+	{
+		performTask(request,response);
+	}	
+
+   /** 
+	* Main service method for TradeScenarioServlet
+	*
+	* @param request Object that encapsulates the request to the servlet
+	* @param response Object that encapsulates the response from the servlet
+	*/    
+	public void performTask(HttpServletRequest req, HttpServletResponse resp)
+		throws ServletException, IOException {
+
+		// Scenario generator for Trade2
+		char action = ' ';
+		String userID = null;
+
+		// String to create full dispatch path to TradeAppServlet w/ request Parameters
+		String dispPath = null; // Dispatch Path to TradeAppServlet
+
+		String scenarioAction = (String) req.getParameter("action");
+		if ((scenarioAction != null) && (scenarioAction.length() >= 1))
+		{
+			action = scenarioAction.charAt(0);
+			if (action == 'n')
+			{ //null;
+				try
+				{
+					resp.setContentType("text/html");
+					PrintWriter out = new PrintWriter(resp.getOutputStream());
+					out.println("<HTML><HEAD>TradeScenarioServlet</HEAD><BODY>Hello</BODY></HTML>"); 
+					out.close();
+					return;
+	
+				}
+				catch (Exception e)
+				{
+					Log.error(
+						"trade_client.TradeScenarioServlet.service(...)" + 
+						"error creating printwriter from responce.getOutputStream", e);
+						
+					resp.sendError(
+							500, 
+						"trade_client.TradeScenarioServlet.service(...): erorr creating and writing to PrintStream created from response.getOutputStream()"); 
+				} //end of catch
+	
+			} //end of action=='n'
+		}
+
+
+		ServletContext ctx = null;
+		HttpSession session = null;
+		try
+		{
+			ctx = getServletConfig().getServletContext();
+			// These operations require the user to be logged in. Verify the user and if not logged in
+			// change the operation to a login
+			session = req.getSession(true);
+			userID = (String) session.getAttribute("uidBean");
+		}
+		catch (Exception e)
+		{
+			Log.error(
+				"trade_client.TradeScenarioServlet.service(...): performing " + scenarioAction +
+				"error getting ServletContext,HttpSession, or UserID from session" +
+				"will make scenarioAction a login and try to recover from there", e);
+			userID = null;
+			action = 'l';
+		}
+
+		if (userID == null)
+		{
+			action = 'l'; // change to login
+			TradeConfig.incrementScenarioCount();
+		}
+		else if (action == ' ') {
+			//action is not specified perform a random operation according to current mix
+			// Tell getScenarioAction if we are an original user or a registered user 
+			// -- sellDeficits should only be compensated for with original users.
+			action = TradeConfig.getScenarioAction(
+				userID.startsWith(TradeConfig.newUserPrefix));
+		}	
+		switch (action)
+			{
+
+				case 'q' : //quote 
+					dispPath = tasPathPrefix + "quotes&symbols=" + TradeConfig.rndSymbols();
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'a' : //account
+					dispPath = tasPathPrefix + "account";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'u' : //update account profile
+					dispPath = tasPathPrefix + "account";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+
+					String fullName = "rnd" + System.currentTimeMillis();
+					String address = "rndAddress";
+					String   password = "xxx";
+					String email = "rndEmail";
+					String creditcard = "rndCC";
+					dispPath = tasPathPrefix + "update_profile&fullname=" + fullName + 
+						"&password=" + password + "&cpassword=" + password + 					
+						"&address=" + address +	"&email=" + email + 
+						"&creditcard=" +  creditcard;
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'h' : //home
+					dispPath = tasPathPrefix + "home";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'l' : //login
+					userID = TradeConfig.getUserID();
+					String password2 = "xxx";
+					dispPath = tasPathPrefix + "login&inScenario=true&uid=" + userID + "&passwd=" + password2;
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+						
+					// login is successful if the userID is written to the HTTP session
+					if (session.getAttribute("uidBean") == null) {
+						System.out.println("TradeScenario login failed. Reset DB between runs");
+					} 
+					break;
+				case 'o' : //logout
+					dispPath = tasPathPrefix + "logout";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'p' : //portfolio
+					dispPath = tasPathPrefix + "portfolio";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 'r' : //register
+					//Logout the current user to become a new user
+					// see note in TradeServletAction
+					req.setAttribute("TSS-RecreateSessionInLogout", Boolean.TRUE);
+					dispPath = tasPathPrefix + "logout";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+
+					userID = TradeConfig.rndNewUserID();
+					String passwd = "yyy";
+					fullName = TradeConfig.rndFullName();
+					creditcard = TradeConfig.rndCreditCard();
+					String money = TradeConfig.rndBalance();
+					email = TradeConfig.rndEmail(userID);
+					String smail = TradeConfig.rndAddress();
+					dispPath = tasPathPrefix + "register&Full Name=" + fullName + "&snail mail=" + smail +
+						"&email=" + email + "&user id=" + userID + "&passwd=" + passwd + 
+						"&confirm passwd=" + passwd + "&money=" + money + 
+						"&Credit Card Number=" + creditcard;
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+				case 's' : //sell
+					dispPath = tasPathPrefix + "portfolioNoEdge";
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+
+					Collection holdings = (Collection) req.getAttribute("holdingDataBeans");
+					int numHoldings = holdings.size();
+					if (numHoldings > 0)
+					{
+						//sell first available security out of holding 
+						
+						Iterator it = holdings.iterator();
+						boolean foundHoldingToSell = false;
+						while (it.hasNext()) 
+						{
+							HoldingDataBean holdingData = (HoldingDataBean) it.next();
+							if ( !(holdingData.getPurchaseDate().equals(new java.util.Date(0)))  )
+							{
+								Integer holdingID = holdingData.getHoldingID();
+
+								dispPath = tasPathPrefix + "sell&holdingID="+holdingID;
+								ctx.getRequestDispatcher(dispPath).include(req, resp);
+								foundHoldingToSell = true;
+								break;	
+							}
+						}
+						if (foundHoldingToSell) break;
+						if (Log.doTrace())
+							Log.trace("TradeScenario: No holding to sell -switch to buy -- userID = " + userID + "  Collection count = " + numHoldings);		
+
+					}
+					// At this point: A TradeScenario Sell was requested with No Stocks in Portfolio
+					// This can happen when a new registered user happens to request a sell before a buy
+					// In this case, fall through and perform a buy instead
+
+					/* Trade 2.037: Added sell_deficit counter to maintain correct buy/sell mix.
+					 * When a users portfolio is reduced to 0 holdings, a buy is requested instead of a sell.
+					 * This throws off the buy/sell mix by 1. This results in unwanted holding table growth
+					 * To fix this we increment a sell deficit counter to maintain the correct ratio in getScenarioAction
+					 * The 'z' action from getScenario denotes that this is a sell action that was switched from a buy
+					 * to reduce a sellDeficit
+					 */
+					if (userID.startsWith(TradeConfig.newUserPrefix) == false)
+					{
+						TradeConfig.incrementSellDeficit();
+					}
+				case 'b' : //buy
+					String symbol = TradeConfig.rndSymbol();
+					String amount = TradeConfig.rndQuantity() + "";
+
+					dispPath = tasPathPrefix + "quotes&symbols=" + symbol;
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+
+					dispPath = tasPathPrefix + "buy&quantity=" + amount + "&symbol=" + symbol;
+					ctx.getRequestDispatcher(dispPath).include(req, resp);
+					break;
+			} //end of switch statement 
+	}
+
+	// URL Path Prefix for dispatching to TradeAppServlet
+	private final static String tasPathPrefix = "/app?action=";
+
+}

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/daytrader/trunk/daytrader-webonly/src/main/java/org/apache/geronimo/samples/daytrader/web/TradeScenarioServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message