package isip.java.bullyse.bullydb; import java.io.*; import java.util.*; import java.sql.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; // This file handles the buying and selling of stocks in the // Exchange public class buysell extends HttpServlet { // Create a new BullyDB object static BullyDB sessionbase = new BullyDB(); // System parameters are stored in the database, retrieve the values // through the BullyDB object. static String SystemURL = sessionbase.getURL(); static String ServletURL = sessionbase.getServletURL(); static String SystemEmail = sessionbase.getEmail(); static String SystemPath = sessionbase.getPath(); static String SystemName = sessionbase.getName(); static String SystemShortName = sessionbase.getShortName(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Initialize variables String AccountId = (String)null; String task = request.getParameter("task"); HttpSession session = request.getSession(); String SessionId = session.getId(); // Retrieve AccountId AccountId = sessionbase.getAccountId(SessionId); if (AccountId == null) { response.sendRedirect(ServletURL + ".nonMember?task=LI&Type=1"); } else { // Make sure user isn't locked if (sessionbase.checkAccount(SessionId)) { task = "Locked"; } if (task == null) { // Set up output stream response.setContentType("text/html"); PrintWriter out = response.getWriter(); String Symbol = (String)null; String Trans = (String)null; String NumS = (String)null; String Price = (String)null; Symbol = request.getParameter("Symbol"); Trans = request.getParameter("Trans"); NumS = request.getParameter("NumShares"); Price = request.getParameter("Price"); // Print top template for Buy and Sell sessionbase.printTop(out, 4); out.println("\"BSE
"); // Print link to view all current offers before Buy and Sell form out.println("View pending offers on all stock.

"); // Output form for user to make selections on out.println("
"); out.println(""); out.println(""); if (Trans != null) { if (Trans.equals("S")) { out.println(""); out.println(""); } else if (Trans.equals("B")) { out.println(""); out.println(""); } } else { out.println(""); out.println(""); } out.println(""); if (Symbol != null) { out.println(""); } else { out.println(""); } out.println(""); if (NumS != null) { out.println(""); } else { out.println(""); } out.println(""); if (Price != null) { out.println(""); } else { out.println(""); } out.println("
Please select:BuySellBuySellBuySellSymbol:
No. of shares:Asking price:$$
"); // Print user holdings sessionbase.showHoldings(out, 1, SessionId); sessionbase.printBot(out, SessionId, 1); out.close(); } else if (task.equals("Locked")) { response.sendRedirect(ServletURL + ".Portfolio?task=Locked"); } else if(task.equals("Status")) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String Trans = request.getParameter("Trans"); String Symbol = request.getParameter("Symbol"); // Give user the option of canceling their trade offer sessionbase.printTop(out, 4); out.println("\"BSE
"); if (Trans.equals("FB") || Trans.equals("FS")) { out.println("

This transaction has been frozen for evaluation by " + SystemName + " advisors. You can delete the transaction or send an email to " + SystemEmail + " for information why the task has been frozen.

"); } out.println("

Do you wish to delete the queued task?
"); out.println("Note: This will permanentely delete the offer from the"); out.println("queue.

"); out.println("

"); out.println(""); out.println(""); sessionbase.printBot(out, SessionId, 1); out.close(); } else if(task.equals("offerexists")) { // Set up output stream response.setContentType("text/html"); PrintWriter out = response.getWriter(); sessionbase.printTop(out, 5); out.println("\"BSE
"); out.println("

Error:

"); out.println("

You already have a transaction of this type. Users are only allowed one Buy or Sell transaction at a time for each Company owned. Please go back and try again.

"); sessionbase.printBot(out, SessionId, 1); out.close(); } else if(task.equals("confirmDel")) { String Trans = request.getParameter("Trans"); String Symbol = request.getParameter("Symbol"); Symbol = Symbol.toLowerCase(); ResultSet result = null; int numShares = 0; int oldShares = 0; double buyAt = 0.0; String query = (String)null; DecimalFormat numFormat = new DecimalFormat("################0.00"); DecimalFormat intFormat = new DecimalFormat("################0"); String Username = sessionbase.getUsername(SessionId); // Set up output stream response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Grab the transaction lock String Locked = "9999"; boolean isLocked = true; int error = 0; while (isLocked) { Locked = sessionbase.LockTrading(SessionId); if (!Locked.equals("9999") && Locked.equals(SessionId)) { isLocked = false; } else if (!Locked.equals("9999") && !Locked.equals(SessionId)) { isLocked = false; error = 1; } } // Make sure the transaction still exists query = "select NumShares from " + Username + " where Trans = '" + Trans + "' and Symbol = '" + Symbol + "'"; result = sessionbase.doQuery(query); try { while (result.next()) { numShares = result.getInt("NumShares"); } } catch (Exception e) { e.printStackTrace(); } if (!(numShares > 0)) { // Transaction must be gone - send an error. sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("Error:
"); out.println("The transaction you are trying to delete no longer exists. Most likely someone responded to the offer before the deletion was processed.
"); sessionbase.printBot(out, SessionId, 1); out.close(); } else if (error != 0) { // Transaction must be gone - send an error. sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("Error:
"); out.println("A problem occured trying to grab the transaction lock. Go back and try again. If the problem persists, send an email to " + SystemEmail + " detailing what happened."); sessionbase.printBot(out, SessionId, 1); out.close(); } else { // Remove the transaction from the queue and user table if (Trans.equals("FB") || Trans.equals("B")) { // Simply remove it from the queue and user if (Trans.equals("B")) { query = "delete from " + Username + " where Trans = '" + Trans + "' and Symbol = '" + Symbol + "'"; sessionbase.doUpdate(query); query = "delete from qt" + Symbol.toLowerCase() + " where Trans = '" + Trans + "' and AccountId = " + sessionbase.getAccountId(SessionId); sessionbase.doUpdate(query); } else if (Trans.equals("FB")) { query = "delete from " + Username + " where Trans = '" + Trans + "' and Symbol = '" + Symbol + "'"; sessionbase.doUpdate(query); query = "delete from Frozen where Trans = 'B' and AccountId = " + sessionbase.getAccountId(SessionId); sessionbase.doUpdate(query); } } else if (Trans.equals("FS") || Trans.equals("S")) { // The shares will have to be added back into the // users Fixed holdings if (Trans.equals("S")) { // We are adding numShares back in, use modHoldings for this. sessionbase.modHoldings(Username, Symbol, numShares); // Delete from user and queue query = "delete from " + Username + " where Trans = '" + Trans + "' and Symbol = '" + Symbol + "'"; sessionbase.doUpdate(query); query = "delete from qt" + Symbol.toLowerCase() + " where Trans = '" + Trans + "' and AccountId = " + sessionbase.getAccountId(SessionId); sessionbase.doUpdate(query); } else if (Trans.equals("FS")) { // We are adding numShares back in, use modShares for this. sessionbase.modHoldings(Username, Symbol, numShares); // Delete from user and queue query = "delete from " + Username + " where Trans = '" + Trans + "' and Symbol = '" + Symbol + "'"; sessionbase.doUpdate(query); query = "delete from Frozen where Trans = '" + Trans + "' and AccountId = " + sessionbase.getAccountId(SessionId); sessionbase.doUpdate(query); } } // Transaction deleted, output success sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("Success:
"); out.println("Your transaction offer has been removed from the " + SystemName); sessionbase.printBot(out, SessionId, 1); out.close(); } // Unlock transaction while (!isLocked) { isLocked = sessionbase.UnLockTrading(SessionId); } } else if(task.equals("confirmBuy")) { // Initialize variables String Symbol = request.getParameter("Symbol"); String nums = request.getParameter("numShares"); String buyVal = request.getParameter("askPrice"); Timestamp now = null; Double buyTemp = Double.valueOf(buyVal); double buyAt = buyTemp.doubleValue(); Integer NumS = Integer.valueOf(nums); int offerShares = NumS.intValue(); Offers currentOffer = new Offers(Symbol, "B", buyAt, offerShares, now, sessionbase.getAccountId(SessionId)); sessionbase.doTrans(currentOffer, SessionId, false, response); response.sendRedirect(ServletURL + ".buysell"); } else if(task.equals("confirmSell")) { // Initialize variables String Symbol = request.getParameter("Symbol"); String nums = request.getParameter("numShares"); String buyVal = request.getParameter("askPrice"); Timestamp now = null; Double buyTemp = Double.valueOf(buyVal); double buyAt = buyTemp.doubleValue(); Integer NumS = Integer.valueOf(nums); int offerShares = NumS.intValue(); Offers currentOffer = new Offers(Symbol, "S", buyAt, offerShares, now, sessionbase.getAccountId(SessionId)); sessionbase.doTrans(currentOffer, SessionId, false, response); response.sendRedirect(ServletURL + ".buysell"); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, NumberFormatException { // Initialize variables String task = request.getParameter("task"); String AccountId = (String)null; String query = (String)null; // Initialize output stream response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); String SessionId = session.getId(); // Retrieve AccountId AccountId = sessionbase.getAccountId(SessionId); DecimalFormat numFormat = new DecimalFormat("################0.00"); DecimalFormat intFormat = new DecimalFormat("################0"); if (AccountId == null) { response.sendRedirect(ServletURL + ".nonMember?task=LI&Type=1"); } else { // Make sure user isn't locked if (sessionbase.checkAccount(SessionId)) { task = "Locked"; } if (task == null) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

You must select whether to \"buy\" or \"sell\"."); out.println("Please go back and correct the problem.

"); sessionbase.printBot(out, SessionId, 1); out.close(); } else if (task.equals("Locked")) { response.sendRedirect(ServletURL + ".Portfolio?task=Locked"); } else if (task.equals("buy")) { // Initialize variables String Symbol = request.getParameter("symbol"); String nums = request.getParameter("numShares"); String askP = request.getParameter("askPrice"); Integer convInt; int numShares = 0; // Cost per share container double shareCost = 0.00; // Current balance container double Balance = 0.00; // Total cost of purchase container double tCost = 0.00; // End balance container double endBalance = 0.00; // Available shares container int availShares = 0; // Remaining shares available int endShares = 0; ResultSet result = null; int error = 0; Double contP; double askPrice = 0.00; String numCheck = ""; char Checkit; int lenCheck = 0; String Locked = ""; DecimalFormat curFormat = new DecimalFormat("$##,###,###,###,###,##0.00"); // Is trading currently frozen? sessionbase.loadParams(); if (sessionbase.checkFreeze()) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println(""); out.println("

Notice:

"); out.println("Trading is currently frozen on " + SystemName + ".
"); out.println("Please try your transaction again later.
"); out.println(""); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } if (error == 0) { // Everything is type String, convert everything to its proper type. askP = askP.trim(); lenCheck = askP.length(); // Filter out $ and , from the Cost for (int i = 0 ; i < lenCheck ; i++) { Checkit = askP.charAt(i); if (Checkit != '$' && Checkit != ',') { numCheck += Checkit; } } askP = numCheck; try { convInt = new Integer(nums); numShares = convInt.intValue(); contP = new Double(askP); askPrice = contP.doubleValue(); } catch(NumberFormatException e) { // User must have entered something else wrong sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

Invalid characters entered."); out.println("Please go back and correct the problem.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } } // Make sure this isn't a Company account trying to buy something // other than itself query = "select Type from Account where AccountId = " + AccountId; result = sessionbase.doQuery(query, SessionId); String Type = (String)null; try { while (result.next()) { Type = result.getString("Type"); } } catch (Exception e) { e.printStackTrace(); } if (Type.equals("C") && error == 0) { String Sym1 = Symbol.toLowerCase(); String Sym2 = sessionbase.getUsername(SessionId); Sym2 = Sym2.toLowerCase(); if (!Sym1.equals(Sym2)) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("Company accounts are only permitted to buy and sell their own stock."); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } } // Make sure user isn't trying to sell 0 shares or < $0.01 if ((numShares < 1 || askPrice < 0.01) && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

0 and negative values not allowed for Shares or Amount."); out.println("Go back and enter a different number.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } // Make sure they entered a valid company and that it isn't locked query = "Select Last, Locked from Companies where Symbol = '" + Symbol + "'"; result = sessionbase.doQuery(query, SessionId); try { while(result.next()) { shareCost = result.getDouble("Last"); Locked = result.getString("Locked"); } } catch(Exception e) { e.printStackTrace(); } if(shareCost == 0.00 && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

You have entered an invalid symbol."); out.println("Please go back and enter a different one.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } if (Locked.equals("Y") && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("The stock you are trying to buy is currently frozen, no buy or sell transactions can take place until this is lifted."); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } // Get user balance and make sure they have enough money query = "select Balance from Portfolio where AccountId = " + AccountId; result = sessionbase.doQuery(query, SessionId); try { while(result.next()) { Balance = result.getDouble("Balance"); } } catch(Exception e) { e.printStackTrace(); } if (Type.equals("C")) { tCost = askPrice * numShares; } else { tCost = sessionbase.getCommission(SessionId) + (askPrice * numShares); } endBalance = Balance - tCost; if(endBalance < 0 && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

You cannot afford the number of stocks requested. "); if (!Type.equals("C")) { out.println("Keep in mind there is a $" + sessionbase.getCommission(SessionId) + " commission on each transaction."); } out.println("
Please go back and try again.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } // Check to see if user already has an offer out for this symbol query = "select Symbol from " + sessionbase.getUsername(SessionId) + " where Symbol = '" + Symbol + "' and Trans = 'B'"; result = sessionbase.doQuery(query, SessionId); String Sym = (String)null; try { while(result.next()) { Sym = result.getString("Symbol"); } } catch(Exception e) { e.printStackTrace(); } if (Sym != null) { response.sendRedirect(ServletURL + ".buysell?task=offerexists"); } if (error == 0) { // Everything must be ok. Prompt user to ensure they // really want to do the trade. sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("Confirm
"); out.println("Please confirm your purchase bid:
"); // Make sure the transaction doesn't go outside the boundaries // of whatever filters are in place. // All the real checking for this, for buy or sell transactions, // is done by a class in BullyDB. Any changes to the actual rules // for the filters will need to be done there. Variables for the // rules are currently stored in the Database and can be modified // from the Parameters section of the Administrative pages. if (!sessionbase.checkRules(Symbol, numShares, askPrice, "B", 1, SessionId)) { out.println("
Notice:
"); out.println("As listed, your transaction will be frozen for review by an Exchange Administrator. Checks are put into place to prevent transactions done simply to manipulate the market value. You can either cancel the transaction and modify it or send it through and let an Administrator decide on its approval. Email " + SystemEmail + " with any questions.

"); } out.println("" + numShares + " shares of " + Symbol.toUpperCase() + " at " + curFormat.format(askPrice) + " per share.
"); out.println("Transaction Cost: " + curFormat.format(tCost) + "
"); if (!Type.equals("C")) { out.println("Commission Cost: $" + sessionbase.getCommission(SessionId) + "

"); } out.println("Note: The listed cost is what will be deducted from your account if a Sell offer is made at the amount you specify, but the actual amount may be less if a cheaper Sell offer is made. The money is not deducted from your account until a Sell offer has been made so you will need to make sure you keep enough money in your account to cover this purchase. However, the commission charge will be deducted now.
"); out.println(" "); sessionbase.printBot(out, SessionId, 1); out.close(); } } else if(task.equals("sell")) { // Initialize variables String Symbol = ""; Symbol += request.getParameter("symbol"); String nums = ""; nums += request.getParameter("numShares"); String askP = ""; askP += request.getParameter("askPrice"); int userShares = 0; double Balance = 0.00; double shareCost = 0.00; double endBalance = 0.00; double Profit = 0.00; int error = 0; Integer convInt; int numShares = 0; String numCheck = ""; int lenCheck = 0; char Checkit; Double contP; double askPrice = 0.00; String Locked = ""; // Is trading currently frozen? sessionbase.loadParams(); if (sessionbase.checkFreeze()) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println(""); out.println("

Notice:

"); out.println("Trading is currently frozen on " + SystemName + ".
"); out.println("Please try your transaction again later.
"); out.println(""); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } if (error == 0) { askP = askP.trim(); lenCheck = askP.length(); for (int i = 0 ; i < lenCheck ; i++) { Checkit = askP.charAt(i); if (Checkit != '$' && Checkit != ',') { numCheck += Checkit; } } askP = numCheck; try { convInt = new Integer(nums); numShares = convInt.intValue(); contP = new Double(askP); askPrice = contP.doubleValue(); } catch(NumberFormatException e) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

Invalid characters entered."); out.println("Please go back and correct the problem.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } } ResultSet result = null; DecimalFormat curFormat = new DecimalFormat("$##,###,###,###,###,###,##0.00"); // Make sure they entered a valid company query = "select Last, Locked from Companies where Symbol = '" + Symbol + "'"; result = sessionbase.doQuery(query, SessionId); try { while(result.next()) { shareCost = result.getDouble("Last"); Locked = result.getString("Locked"); } } catch(Exception e) { e.printStackTrace(); } if (shareCost == 0.00 && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

The Symbol you have entered doesn't exist."); out.println("Go back and enter a valid symbol.

"); sessionbase.printBot(out, SessionId, 1); error++; out.close(); } // Make sure user isn't trying to sell 0 shares or < $0.01 if ((numShares < 1 || askPrice < 0.01) && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

0 and negative values not allowed for Shares or Amount."); out.println("Go back and enter a different number.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } // Make sure user has the number of shares they try to sell query = "Select NumShares from " + sessionbase.getUsername(SessionId) + " where Symbol = '" + Symbol + "' and Trans = 'C'"; result = sessionbase.doQuery(query, SessionId); try { while(result.next()) { userShares = result.getInt("NumShares"); } } catch(Exception e) { e.printStackTrace(); } if ((userShares - numShares) < 0 && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("

You don't have that many shares to sell."); out.println("Go back and enter a different number.

"); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } if (Locked.equals("Y") && error == 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("The stock you are trying to buy is currently frozen, no buy or sell transactions can take place until this is lifted."); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } // Check to see if user already has an offer out for this symbol query = "select Symbol from " + sessionbase.getUsername(SessionId) + " where Symbol = '" + Symbol + "' and Trans = 'S'"; result = sessionbase.doQuery(query, SessionId); String Sym = (String)null; try { while(result.next()) { Sym = result.getString("Symbol"); } } catch(Exception e) { e.printStackTrace(); } if (Sym != null && error == 0) { response.sendRedirect(ServletURL + ".buysell?task=offerexists"); error++; } // Make sure user can afford the commission cost // Get user's balance query = "select Balance from Portfolio where AccountId = " + AccountId; result = sessionbase.doQuery(query, SessionId); try { while(result.next()) { Balance = result.getDouble("Balance"); } } catch(Exception e) { e.printStackTrace(); } // Get user Type. If this is a company we won't charge a // commission. query = "select Type from Account where AccountId = " + AccountId; result = sessionbase.doQuery(query, SessionId); String Type = (String)null; try { while (result.next()) { Type = result.getString("Type"); } } catch (Exception e) { e.printStackTrace(); } if (!Type.equals("C")) { double checkBal = Balance - sessionbase.getCommission(SessionId); if (checkBal < 0) { sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("

Error:

"); out.println("You cannot afford the commission charge to sell this stock."); sessionbase.printBot(out, SessionId, 1); out.close(); error++; } } if (error == 0) { // Everything seems ok, confirm the sale if (Type.equals("C")) { Profit = numShares * askPrice; } else { Profit = (numShares * askPrice) - sessionbase.getCommission(SessionId); } endBalance = Balance + Profit; sessionbase.printTop(out, 4); out.println("\"BSE
"); out.println("Confirm
"); out.println("Please confirm your sale bid:
"); // Make sure the transaction doesn't go outside the boundaries // of whatever filters are in place. // All the real checking for this, for buy or sell transactions, // is done by a class in BullyDB. Any changes to the actual rules // for the filters will need to be done there. Variables for the // rules are currently stored in the Database and can be modified // from the Parameters section of the Administrative pages. if (!sessionbase.checkRules(Symbol, numShares, askPrice, "S", 1, SessionId)) { out.println("
Notice:
"); out.println("As listed, your transaction will be frozen for review by an Exchange Administrator. Checks are put into place to prevent transactions done simply to manipulate the market value. You can either cancel the transaction and modify it or send it through and let an Administrator decide on its approval. Email " + SystemEmail + " with any questions.

"); } out.println("" + numShares + " shares of " + Symbol.toUpperCase() + " at " + curFormat.format(askPrice) + " per share.
"); out.println("Sale Value: " + curFormat.format(Profit + sessionbase.getCommission(SessionId)) + "
"); if (!Type.equals("C")) { out.println("Commission Cost: $" + sessionbase.getCommission(SessionId) + "
"); } out.println("Ending Balance: " + curFormat.format(endBalance) + "
"); out.println(" "); sessionbase.printBot(out, SessionId, 1); out.close(); } } } } static public void reload() { SystemURL = sessionbase.getURL(); ServletURL = sessionbase.getServletURL(); SystemEmail = sessionbase.getEmail(); SystemPath = sessionbase.getPath(); SystemName = sessionbase.getName(); SystemShortName = sessionbase.getShortName(); } }