package isip.java.bullyse.bullydb; // file: BullyDB.java // import java.io.*; import java.util.*; import java.sql.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; // Method for email has changed. // import javax.mail.*; // import javax.mail.internet.*; // import javax.activation.*; //************************************* // // ISIP_BullySE_BullyDB // //************************************* public class BullyDB { //************************************ // // private data // //************************************ // These are needed to initialize the jdbc connection // Change MySQL to the address of your MySQL server private String MySQL = "isip003.isip.msstate.edu:3306"; // Change this to the name you gave your Exchange database private String dBase = "bullyse"; private String _URL = "jdbc:mysql://" + MySQL + "/" + dBase; private String _user = "bullyse"; private String _pWord = "BullySe"; // Database objects private Connection conn; private ResultSet result; // Initialize the Parameters object private Parameters ExchangeParam = new Parameters(); // Used to lock transactions to a single user at a time static boolean isLocked = false; static String hasLock = "9999"; // The Users Hashtable is used to store User objects. Each user has // their own User object created when they log in and it is stored, // by SessionID, in the Hashtable. static Hashtable Users = new Hashtable(); // Parameter data String SystemURL = getURL(); String ServletURL = getServletURL(); String SystemEmail = getEmail(); String SystemPath = getPath(); String SystemName = getName(); String SystemShortName = getShortName(); // Parsing variables static boolean doParse = false; java.util.Date dailyParse = getDaily(); java.util.Date calcValue = new java.util.Date(0, 0, 0, 0, 0, 0); //************************************ // // constructor methods // //************************************ // default constructor // public BullyDB() {} public void putUser() { // Create a generic User for nonMember User nonMember = new User(); String nonMId = "nonMember"; if (Users.containsKey(nonMId)) { Users.remove(nonMId); Users.put(nonMId, nonMember); } else { Users.put(nonMId, nonMember); } } public Statement connect() { Statement stmt = null; // Lets start a database connection try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch(Exception e){ e.printStackTrace(); } // Statement shouldn't exist. If it does, close it. if (stmt != null) { try { stmt.close(); } catch(SQLException e) { e.printStackTrace(); } } // Connection shouldn't exist. If it does, close it. if (conn != null) { try { conn.close(); } catch(SQLException e) { e.printStackTrace(); } } // Open a connection to the database try { conn = DriverManager.getConnection(_URL, _user, _pWord); } catch(SQLException e) { e.printStackTrace(); } while (conn == null) { // Error. This isn't good. } // Set up the statement object try { // initialize the statment object stmt = conn.createStatement(); } catch(SQLException e){ e.printStackTrace(); } return stmt; } public boolean doLogon(String username, String password, String sessionId) throws ServletException, IOException { String AccountId = (String)null; String Username = (String)null; String Fname = (String)null; // format query that verifies account information String query = "select * from Account where Username = '" + username + "' and Password = password('" + password + "')"; result = doQuery(query); // pull the accountId out of the ResultSet if it existed try { while(result.next()) { AccountId = result.getString("AccountId"); Username = result.getString("Username"); Fname = result.getString("Fname"); } } catch(SQLException e) { e.printStackTrace(); } if (AccountId == null) { // User login failed, return an error return false; } else { // User logged in successfully. Create a new user object // and insert it into the Hashtable. User Trader = new User(AccountId, Username, Fname); // First, make sure no duplicate SessionId's exist in the Hashtable if (Users.containsKey(sessionId)) { Users.remove(sessionId); Users.put(sessionId, Trader); } else { Users.put(sessionId, Trader); } return true; } } // Query method for users logged in to the system. SessionId // is given so that we can use the MySQL stream stored in the // user object. On Query's it's not too big an issue but it's // not a bad habit to get into. public ResultSet doQuery(String query, String SessionId) throws IOException { ResultSet toReturn = null; // Find users object and call the Query method within it if (Users.containsKey(SessionId)) { User thisUser = (User)Users.get(SessionId); toReturn = thisUser.doQuery(query); return toReturn; } else { return null; } } // Update method for users logged in to the system. SessionId // is given so that we can use the MySQL stream stored in the // user object. Individual streams have to be used here in order // to allow for table locking. public void doUpdate(String query, String SessionId) throws IOException { // Find users object and call the Update method within it if (Users.containsKey(SessionId)) { User thisUser = (User)Users.get(SessionId); thisUser.doUpdate(query); } } public boolean checkAccount(String SessionId) throws IOException { String LockedStat = (String)null; String query = "select Locked from Account where AccountId = " + getAccountId(SessionId); ResultSet result = doQuery(query, SessionId); try { while (result.next()) { LockedStat = result.getString("Locked"); } } catch (Exception e) { e.printStackTrace(); } if (LockedStat.equals("Y")) { return true; } else { return false; } } // Query method for users not logged in. This might be people // currently logging in or just looking through the system. public ResultSet doQuery(String query) throws IOException { Statement stmt = null; result = null; stmt = connect(); try { result = stmt.executeQuery(query); stmt.close(); } catch(Exception e) { e.printStackTrace(); } if(result != null) { return result; } else { return null; } } // Update method for users not logged in. This would be used // for people trying to create an account. public void doUpdate(String query) throws IOException { Statement stmt = null; stmt = connect(); try { stmt.executeUpdate(query); } catch(Exception e) { e.printStackTrace(); } } // The User object holds on to all the data about the current // user. public class User { // Initialize individual database connection Connection conn = null; Statement stmt = null; ResultSet result = null; // Holds user information private String AccountId; private String Username; private String Fname; public User () { Username = "Guest"; Fname = "Guest"; connect(); } public User (String AccountId, String Username, String Fname) { this.AccountId = AccountId; this.Username = Username; this.Fname = Fname; connect(); } private void connect() { // Lets start a database connection try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch(Exception e){ e.printStackTrace(); } // Statement shouldn't exist. If it does, close it. if (stmt != null) { try { stmt.close(); } catch(SQLException e) { e.printStackTrace(); } } // Connection shouldn't exist. If it does, close it. if (conn != null) { try { conn.close(); } catch(SQLException e) { e.printStackTrace(); } } // Open a connection to the database try { conn = DriverManager.getConnection(_URL, _user, _pWord); } catch(SQLException e) { e.printStackTrace(); } while (conn == null) { // Error. This isn't good. } // Set up the statement object try { // initialize the statment object stmt = conn.createStatement(); } catch(SQLException e){ e.printStackTrace(); } } // Query method for a logged in user public ResultSet doQuery(String query) throws IOException { ResultSet thisResult = null; try { thisResult = stmt.executeQuery(query); } catch(Exception e) { e.printStackTrace(); } if(thisResult != null) { return thisResult; } else { return null; } } // Update method for a logged in user public void doUpdate(String query) throws IOException { try { stmt.executeUpdate(query); } catch(Exception e) { e.printStackTrace(); } } // Return user details if requested public String getAccountId() { return AccountId; } public String getUsername() { return Username; } public String getFname() { return Fname; } // This object holds details on the users Holdings. Used // by the showHoldings method. public class Holdings { private String Symbol; private String Trans; private double boughtAt; private int numShares; private double Last; public Holdings (String Symbol, double boughtAt, String Trans, int numShares, double Last) { this.Symbol = Symbol; this.boughtAt = boughtAt; this.Trans = Trans; this.numShares = numShares; this.Last = Last; } // Return details on the users holdings when requested. public String getSymbol() { return Symbol.toUpperCase(); } public double getboughtAt() { return boughtAt; } public int getnumShares() { return numShares; } public double getLast() { return Last; } public String getTrans() { return Trans; } public String getTransL() { // Check Trans type, return a String based on this. if (Trans.equals("B")) { return "Pending Purchase"; } else if (Trans.equals("S")) { return "Pending Sale"; } else if (Trans.equals("FB")) { return "Frozen Purchase"; } else if (Trans.equals("FS")) { return "Frozen Sale"; } else if (Trans.equals("C")) { return " "; } else { return "Unknown"; } } } // Remove the user object from the Hashtable when they log out public void doLogout(String SessionId) { Users.remove(SessionId); } // Show all holdings of the user public void showHoldings(PrintWriter out, int vTag) throws IOException, ServletException { String query = (String)null; ResultSet rslt = null; ResultSet result = null; double Balance = 0.00; String Symbol = (String)null; double boughtAt = 0.00; String Trans = (String)null; double Last = 0.00; double Profit = 0.00; int numShares = 0; int count = 0; double Total = 0.00; String Type = (String)null; Vector dumpPlace = new Vector(); String fcolor = "000000"; String userName = (String)null; String Status = (String)null; String userTrans = (String)null; int userCount = 0; double userAvgValue = 0; int userTotalShares = 0; int userShares = 0; double userValue = 0.00; int totalShares = 0; double totalValue = 0; int totalHoldings = 0; double marketCap = 0; double projectedCap = 0; double userTradeValue = 0; double Value = 0; int compOwn = 0; // Set up decimal formatting for digits. This will force at least 0.00. DecimalFormat curFormat = new DecimalFormat("$##,###,###,###,###,##0.00"); DecimalFormat numFormat = new DecimalFormat("################0.00"); DecimalFormat intFormat = new DecimalFormat("################0"); BullyDB Dbase = new BullyDB(); // Holdings display are different for Company and Regular users, // so first get the user type. query = "select Type from Account where AccountId = '" + AccountId + "'"; rslt = Dbase.doQuery(query); try { while (rslt.next()) { Type = rslt.getString("Type"); } } catch (Exception e) { e.printStackTrace(); } // Extract users Balance from database query = "select Balance from Portfolio where AccountId = '" + AccountId + "'"; rslt = Dbase.doQuery(query); try { while(rslt.next()) { Balance = rslt.getDouble("Balance"); } } catch(Exception e) { e.printStackTrace(); } // Extract users Holdings from database query = "select t1.Symbol, t1.NumShares, t1.Trans, t1.tradeAt, t2.Last from " + Username + " as t1, Companies as t2 where t1.Symbol = t2.Symbol"; rslt = Dbase.doQuery(query); try { while (rslt.next()) { count++; Symbol = rslt.getString("Symbol"); numShares = rslt.getInt("NumShares"); Trans = rslt.getString("Trans"); boughtAt = rslt.getDouble("tradeAt"); Last = rslt.getDouble("Last"); // Place users Holdings into a Holdings object. Each new // object is stored in a temporary Vector. dumpPlace.addElement(new Holdings(Symbol, boughtAt, Trans, numShares, Last)); } } catch(Exception e) { e.printStackTrace(); } // Display user holdings if(count == 0) { if(vTag == 1) { out.println(""); out.println(""); out.println(""); out.println(""); out.println("
No holdings found for your account.
Please email " + SystemEmail + " if this is in error.
"); out.println("
"); out.println("Current Balance: " + curFormat.format(Balance) + "
"); } else { out.println("Current Balance: " + curFormat.format(Balance) + "
"); } } else { out.println("Listed below are your current holdings and their value.
"); out.println("

"); out.println(""); out.println("
"); out.println(""); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); // Loop to go through each of the stocks in the storage // vector. for(int i=0; i"); Holdings hold = (Holdings) dumpPlace.elementAt(i); Trans = hold.getTrans(); if (Trans.equals("C")) { Profit = hold.getLast() * hold.getnumShares(); Total += Profit; if (AccountId.equals("1")) { out.println(""); } else { out.println(""); } } else { Profit = hold.getboughtAt() * hold.getnumShares(); if (AccountId.equals("1")) { out.println(""); } else { out.println(""); } } } Total += Balance; out.println(""); out.println(""); } else { out.println("
Balance
"); } out.println(""); if (vTag == 1 && !Type.equals("C")) { out.println(""); out.println(""); out.println(""); } out.println(""); out.println("
StatusSymbolNumber of SharesCurrent BidNet Worth
Fixed" + hold.getSymbol() + "" + hold.getnumShares() + "" + curFormat.format(hold.getLast()) + "" + curFormat.format(Profit) + "
Fixed" + hold.getSymbol() + "" + hold.getnumShares() + "" + curFormat.format(hold.getLast()) + "" + curFormat.format(Profit) + "
" + hold.getTransL() + "" + hold.getSymbol() + "" + hold.getnumShares() + "" + curFormat.format(hold.getboughtAt()) + "" + curFormat.format(Profit) + "
" + hold.getTransL() + "" + hold.getSymbol() + "" + hold.getnumShares() + "" + curFormat.format(hold.getboughtAt()) + "" + curFormat.format(Profit) + "
"); if (Type.equals("C")) { out.println("
Cash Reserves
"); out.println("
" + curFormat.format(Balance) + "
"); out.println("
Total Net Worth
"); out.println("
" + curFormat.format(Total) + "
"); out.println("
"); } } } // Calls the users Object to retrieve the AccountId public String getAccountId(String sessionId) { if (Users.containsKey(sessionId)) { User thisUser = (User)Users.get(sessionId); return thisUser.getAccountId(); } else { return (String)null; } } // Queries the database for the username. The flag is just to distinguish // this from getAccountId(String SessionId) public String getAccountId(String User, int flag) throws IOException { String FoundAc = (String)null; ResultSet result = null; String query = "select AccountId from Account where Username = '" + User + "'"; result = doQuery(query); try { while (result.next()) { FoundAc = result.getString("AccountId"); } } catch (Exception e) { e.printStackTrace(); } return FoundAc; } // Calls the users Object to retrieve the Username public String getUsername(String sessionId) { User thisUser = (User)Users.get(sessionId); return thisUser.getUsername(); } // Calls the users Object to retrieve the first name public String getFname(String sessionId) { User thisUser = (User)Users.get(sessionId); return thisUser.getFname(); } // Retrieves the users Username from the database. Similar to // getUsername except the AccountId is used rather than the // SessionId. public String getUser(String userId) throws IOException { String uName = (String)null; result = doQuery("select Username from Account where AccountId = " + userId); try { while(result.next()) { uName = result.getString("Username"); } } catch(Exception e) { e.printStackTrace(); } return uName; } // Call the user object showHoldings public void showHoldings(PrintWriter out, int vTag, String SessionId) throws IOException, ServletException { User thisUser = (User)Users.get(SessionId); thisUser.showHoldings(out, vTag); } public void showCompany(PrintWriter out, String SessionId) throws IOException, ServletException { String query = (String)null; ResultSet result = null; ResultSet result2 = null; String Symbol = getUsername(SessionId); double cashReserves = 0; String userName = (String)null; double userValue = 0; double userAmount = 0; int userShares = 0; double userTradeValue = 0; String userTrans = (String)null; String userEmail = (String)null; double marketCap = 0; double projectedCap = 0; int userCount = 0; int totalShares = 0; int numHolds = 0; double IPO = 0; double diff = 0; DecimalFormat curFormat = new DecimalFormat("$##,######,###,###,##0.00"); // Get company balance and IPO query = "select Balance from Portfolio where AccountId = " + getAccountId(SessionId); result = doQuery(query); try { while (result.next()) { cashReserves = result.getDouble("Balance"); } } catch (Exception e) { e.printStackTrace(); } query = "select IPO from Companies where Symbol = '" + Symbol + "'"; result = doQuery(query); try { while (result.next()) { IPO = result.getDouble("IPO"); } } catch (Exception e) { e.printStackTrace(); } out.println("Listed below are all holders of the company stock.
"); out.println(""); out.println(""); out.println("
"); out.println(""); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); query = "select Username from Account where Username != 'root' order by Username"; result2 = doQuery(query); try { while (result2.next()) { userName = result2.getString("Username"); query = "select * from " + userName + " where Symbol = '" + Symbol + "' and Trans != 'B' and Trans != 'FB'"; result = doQuery(query); while (result.next()) { userCount++; userValue = result.getDouble("boughtAt"); userTradeValue = result.getDouble("tradeAt"); userTrans = result.getString("Trans"); userShares += result.getInt("NumShares"); if (userTrans.equals("S") || userTrans.equals("FS")) { projectedCap += (userTradeValue * userShares); } else { projectedCap += (userValue * userShares); } } if (userCount > 0) { // Get user email query = "select Email from Account where Username = '" + userName + "'"; result = doQuery(query); try { while (result.next()) { userEmail = result.getString("Email"); } } catch (Exception e) { e.printStackTrace(); } totalShares += userShares; marketCap += (userValue * userShares); userAmount = userValue * userShares; out.println(""); userShares = 0; userCount = 0; } } } catch (Exception e) { e.printStackTrace(); } out.println(""); out.println(""); IPO = totalShares * IPO; out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("
OwnerNo. SharesPriceAmount
" + userName + "" + userShares + "" + curFormat.format(userValue) + "" + curFormat.format(userAmount) + "
Sub-Total:" + totalShares + "Filler
Market Capitalization:
" + curFormat.format(marketCap) + "
Original Capitalization:
" + curFormat.format(IPO) + "
Market Growth:
" + curFormat.format((marketCap - IPO)) + "
Projected Capitalization:
" + curFormat.format(projectedCap) + "
Cash Reserves:
" + curFormat.format(cashReserves) + "
"); out.println("
"); } // Call the user object Logout public void doLogout(String SessionId) { User thisUser = (User)Users.get(SessionId); thisUser.doLogout(SessionId); } public void runScript(String Exec, String Path) { // get the current runtime environment // Runtime environ = Runtime.getRuntime(); // make sure we got a valid runtime environment // if (environ == null) { System.out.println("Exchange Mailer didn't get Script Runtime!"); return; } // launch the script with the start option // Process start_proc = (Process)null; try { start_proc = environ.exec(Exec); } catch (java.io.IOException e) { e.printStackTrace(System.out); return; } // make sure we got a valid process // if (start_proc == null) { return; } try{ start_proc.waitFor(); } catch(java.lang.InterruptedException e){ return; } // We need to remove the file generated by the mailer Exec = "rm " + Path; // launch the script with the start option // start_proc = (Process)null; try { start_proc = environ.exec(Exec); } catch (java.io.IOException e) { e.printStackTrace(System.out); return; } // make sure we got a valid process // if (start_proc == null) { return; } try{ start_proc.waitFor(); } catch(java.lang.InterruptedException e){ return; } } // Handles sending email to a user. public void sendEmail(String subject, String to, String from, String body, String SessionId) throws IOException { // Even using SessionId for the filename there is a possibility of // a SessionId trying to generate multiple messages ("nonMember") so // tack on a random number at the end of the name. int rnum; Random rand = new Random(); rnum = rand.nextInt(99999); String FilePath = SystemPath + "/data/Mail/" + SessionId + "." + rnum + "mail"; File outEmail = new File(FilePath); FileWriter out = new FileWriter(outEmail); out.write(body); out.close(); String mailPath = SystemPath + "/data/scripts/send_email"; String Exec = mailPath + " -address " + to + " -subject " + subject + " -reply_to " + from + " -file " + FilePath; runScript(Exec, FilePath); } public void sendEmail(String subject, String Message, String sendTo, String SessionId) throws IOException { String emailTo = (String)null; String query = (String)null; ResultSet result = null; // Retrieve the email address query = "select Email from Account where AccountId = '" + sendTo + "'"; result = doQuery(query, SessionId); try { while (result.next()) { emailTo = result.getString("Email"); } } catch (Exception e) { e.printStackTrace(); } // Even using SessionId for the filename there is a possibility of // a SessionId trying to generate multiple messages ("nonMember") so // tack on a random number at the end of the name. int rnum; Random rand = new Random(); rnum = rand.nextInt(99999); String FilePath = SystemPath + "/data/Mail/" + SessionId + "." + rnum + "mail"; File outEmail = new File(FilePath); FileWriter out = new FileWriter(outEmail); out.write(Message); out.close(); String mailPath = SystemPath + "/data/scripts/send_email"; String Exec = mailPath + " -address " + emailTo + " -subject " + subject + " -reply_to " + SystemEmail + " -file " + FilePath; runScript(Exec, FilePath); } // Email sending for nonMember public void sendEmail(String subject, String Message, String sendTo) throws IOException { String emailTo = (String)null; String query = (String)null; ResultSet result = null; // Retrieve the email address query = "select Email from Account where AccountId = '" + sendTo + "'"; result = doQuery(query); try { while (result.next()) { emailTo = result.getString("Email"); } } catch (Exception e) { e.printStackTrace(); } // User is a nonMember so have a nice big random number. int rnum1; int rnum2; Random rand = new Random(); rnum1 = rand.nextInt(999999); rnum2 = rand.nextInt(999999); String FilePath = SystemPath + "/data/Mail/" + rnum1 + "." + rnum2 + "mail"; File outEmail = new File(FilePath); FileWriter out = new FileWriter(outEmail); out.write(Message); out.close(); String mailPath = SystemPath + "/data/scripts/send_email"; String Exec = mailPath + " -address " + emailTo + " -subject " + subject + " -reply_to " + SystemEmail + " -file " + FilePath; runScript(Exec, FilePath); } // This method displays the Quote Flash box on several BSE pages. // It simply picks the 5 highest valued stocks. public void QuoteFlash(PrintWriter out, int Type) throws IOException, ServletException { String query = (String)null; // Storage variables to hold the 5 values for display String Sym = (String)null; String Sym1 = (String)null; String Sym2 = (String)null; String Sym3 = (String)null; String Sym4 = (String)null; String Sym5 = (String)null; double Val = 0.00; double Val1 = 0.00; double Val2 = 0.00; double Val3 = 0.00; double Val4 = 0.00; double Val5 = 0.00; // Number format to force at least 0.00 DecimalFormat numFormat = new DecimalFormat("################0.00"); String LinkTo = (String)null; if (Type == 1) { LinkTo = ".Quotes?"; } else if (Type == 2) { LinkTo = ".nonMember?task=viewQuote&"; } else if (Type == 3) { LinkTo = ".Admin?task=quote&Type=1&"; } // Read in the Symbols and Last values query = "select Symbol, Last from Companies where Symbol != 'SYS'"; result = doQuery(query); try { while (result.next()) { Sym = result.getString("Symbol"); Val = result.getDouble("Last"); // Compare values and swap out the greater ones to // get the top 5. If a greater value is found, all // lesser values have to be moved down one. if (Val > Val1) { Val5 = Val4; Sym5 = Sym4; Val4 = Val3; Sym4 = Sym3; Val3 = Val2; Sym3 = Sym2; Val2 = Val1; Sym2 = Sym1; Val1 = Val; Sym1 = Sym; } else if (Val > Val2) { Val5 = Val4; Sym5 = Sym4; Val4 = Val3; Sym4 = Sym3; Val3 = Val2; Sym3 = Sym2; Val2 = Val; Sym2 = Sym; } else if (Val > Val3) { Val5 = Val4; Sym5 = Sym4; Val4 = Val3; Sym4 = Sym3; Val3 = Val; Sym3 = Sym; } else if (Val > Val4) { Val5 = Val4; Sym5 = Sym4; Val4 = Val; Sym4 = Sym; } else if (Val > Val5) { Val5 = Val; Sym5 = Sym; } } } catch (Exception e) { e.printStackTrace(); } if (Sym1 != null) { // Output Quote Flash table out.println(""); out.println("
"); out.println(""); out.println(""); out.println(""); out.println(""); } out.println("
"); out.println("Quote Flash
top stocks

"); if (Sym1 != null) { out.println("° " + Sym1.toUpperCase() + "
"); } if (Sym2 != null) { out.println("° " + Sym2.toUpperCase() + "
"); } if (Sym3 != null) { out.println("° " + Sym3.toUpperCase() + "
"); } if (Sym4 != null) { out.println("° " + Sym4.toUpperCase() + "
"); } if (Sym5 != null) { out.println("° " + Sym5.toUpperCase() + "

"); } out.println("

"); if (Sym1 != null) { out.println(numFormat.format(Val1) + "
"); } if (Sym2 != null) { out.println(numFormat.format(Val2) + "
"); } if (Sym3 != null) { out.println(numFormat.format(Val3) + "
"); } if (Sym4 != null) { out.println(numFormat.format(Val4) + "
"); } if (Sym5 != null) { out.println(numFormat.format(Val5) + "

"); if (Type == 1) { out.println(""); } else if (Type == 2) { out.println(""); } else if (Type == 3) { out.println(""); } out.println("MoreAll Quotes"); out.println("
"); } } // Reload any system parameters if changes are made public void loadParams() { ExchangeParam.reload(); } // This object holds all of the Parameters used in the Exchange. public class Parameters { private String URL; private String ServletURL; private String Path; private String Email; private String Name; private String ShortName; private String Frozen; private String Locked; private java.util.Date dayParse; public Parameters () { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } } public void reload() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } // Load the individual objects Admin Admn = new Admin(); profile Prfl = new profile(); buysell BySl = new buysell(); Quotes Qts = new Quotes(); Portfolio Prtf = new Portfolio(); News Nws = new News(); nonMember Lgn = new nonMember(); // Reload each individual class Admn.reload(); Prfl.reload(); BySl.reload(); Qts.reload(); Prtf.reload(); Nws.reload(); Lgn.reload(); // Free the memory back up Admn = null; Prfl = null; BySl = null; Qts = null; Prtf = null; Nws = null; Lgn = null; } private void getParameters() throws IOException { String query = "select * from Parameters"; ResultSet result = null; result = doQuery(query); try { while (result.next()) { URL = result.getString("URL"); ServletURL = result.getString("ServletURL"); Path = result.getString("Path"); Email = result.getString("Email"); Name = result.getString("Name"); ShortName = result.getString("ShortName"); Frozen = result.getString("Frozen"); Locked = result.getString("Locked"); dayParse = result.getDate("DailyParse"); } } catch (Exception e) { e.printStackTrace(); } } public String getURL() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return URL; } public String getServletURL() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return ServletURL; } public String getPath() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return Path; } public String getEmail() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return Email; } public String getName() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return Name; } public String getShortName() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return ShortName; } public String getFreezeStatus() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return Frozen; } public String getLockStatus() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return Locked; } public java.util.Date getDaily() { try { getParameters(); } catch (Exception e) { e.printStackTrace(); } return dayParse; } } public String getURL() { return ExchangeParam.getURL(); } public String getServletURL() { return ExchangeParam.getServletURL(); } public String getPath() { return ExchangeParam.getPath(); } public String getEmail() { return ExchangeParam.getEmail(); } public String getName() { return ExchangeParam.getName(); } public String getShortName() { return ExchangeParam.getShortName(); } public String getFreezeStatus() { return ExchangeParam.getFreezeStatus(); } public String getLockStatus() { return ExchangeParam.getLockStatus(); } public java.util.Date getDaily() { return ExchangeParam.getDaily(); } // This method checks if any of the data parsing needs to be done. public void checkParse() throws IOException { if (!doParse) { doParse = true; // Check if 20 minute parse needs to be done java.util.Date compVal = new java.util.Date(); compVal.setMinutes(-20); if (compVal.after(calcValue)) { parseValue(); } // Check if daily parse needs to be done java.util.Date compParse = new java.util.Date(); if(compParse.getDay() != dailyParse.getDay()) { parseDaily(); } doParse = false; } } public boolean checkRoot(String userName) throws IOException { String rootName = (String)null; // Retrieve the root user's name String query = "select Username from Account where AccountId = 1"; ResultSet result = doQuery(query); try { while (result.next()) { rootName = result.getString("Username"); } } catch (Exception e) { e.printStackTrace(); } rootName = rootName.toLowerCase(); userName = userName.toLowerCase(); if (rootName.equals(userName)) { return true; } else { return false; } } // These methods handle printing the top and bottom sections of BSE public void printTop(PrintWriter out, int On) throws IOException { int Type = 1; if (On < 10) { Type = 1; } else if ((On > 10) && (On < 20)) { Type = 2; } else if (On > 20) { Type = 3; } String linksHead = (String)null; String linksMid = (String)null; String linksFoot = (String)null; String imgHead = (String)null; String imgMid = (String)null; String imgFoot = (String)null; String LinksLine = (String)null; String firstLine = (String)null; String secondLine = (String)null; String thirdLine = (String)null; String fourthLine = (String)null; String fifthLine = (String)null; String sixthLine = (String)null; String firstImage = (String)null; String secondImage = (String)null; String thirdImage = (String)null; String fourthImage = (String)null; String fifthImage = (String)null; String sixthImage = (String)null; String firstEnd = (String)null; String secondEnd = (String)null; String thirdEnd = (String)null; String fourthEnd = (String)null; String fifthEnd = (String)null; String sixthEnd = (String)null; String firstAlt = (String)null; String secondAlt = (String)null; String thirdAlt = (String)null; String fourthAlt = (String)null; String fifthAlt = (String)null; String sixthAlt = (String)null; if (Type == 1) { firstLine = ".Portfolio?task=Members"; firstImage = "home"; firstAlt = "Home"; secondLine = ".Portfolio"; secondImage = "portfolio"; secondAlt = "My Portfolio"; thirdLine = ".profile?task=Account"; thirdImage = "account"; thirdAlt = "My Account"; fourthLine = ".buysell"; fourthImage = "buysell"; fourthAlt = "Buy/Sell"; fifthLine = ".Quotes?Task=showAll"; fifthImage = "quotes"; fifthAlt = "Quotes"; sixthLine = ".News"; sixthImage = "news"; sixthAlt = "News"; } else if (Type == 2) { firstLine = ".nonMember"; firstImage = "home"; firstAlt = "Home"; secondLine = ".nonMember?task=LI&Type=1"; secondImage = "portfolio"; secondAlt = "My Portfolio"; thirdLine = ".nonMember?task=LI&Type=2"; thirdImage = "account"; thirdAlt = "My Account"; fourthLine = ".nonMember?task=LI&Type=3"; fourthImage = "buysell"; fourthAlt = "Buy/Sell"; fifthLine = ".nonMember?task=Quotes"; fifthImage = "quotes"; fifthAlt = "Quotes"; sixthLine = ".nonMember?task=news"; sixthImage = "news"; sixthAlt = "News"; } else if (Type == 3) { firstLine = ".Admin"; firstImage = "admin_home"; firstAlt = "Home"; secondLine = ".Admin?task=account"; secondImage = "admin_users"; secondAlt = "Users"; thirdLine = ".Admin?task=trans"; thirdImage = "admin_trans"; thirdAlt = "Transactions"; fourthLine = ".Admin?task=companies"; fourthImage = "admin_companies"; fourthAlt = "Companies"; fifthLine = ".Admin?task=showAll"; fifthImage = "quotes"; fifthAlt = "Quotes"; sixthLine = ".Admin?task=news"; sixthImage = "admin_news"; sixthAlt = "News"; } firstEnd = "_off.gif"; secondEnd = "_off.gif"; thirdEnd = "_off.gif"; fourthEnd = "_off.gif"; fifthEnd = "_off.gif"; sixthEnd = "_off.gif"; if (On == 1 || On == 11 || On == 21) { firstEnd = "_on.gif"; } else if (On == 2 || On == 12 || On == 22) { secondEnd = "_on.gif"; } else if (On == 3 || On == 13 || On == 23) { thirdEnd = "_on.gif"; } else if (On == 4 || On == 14 || On == 24) { fourthEnd = "_on.gif"; } else if (On == 5 || On == 15 || On == 25) { fifthEnd = "_on.gif"; } else if (On == 6 || On == 16 || On == 26) { sixthEnd = "_on.gif"; } linksHead = ""; linksFoot = ""; imgHead = "\"";"; LinksLine = linksHead + firstLine + linksMid + imgHead + firstImage + firstEnd + imgMid + firstAlt + imgFoot + linksFoot + linksHead + secondLine + linksMid + imgHead + secondImage + secondEnd + imgMid + secondAlt + imgFoot + linksFoot + linksHead + thirdLine + linksMid + imgHead + thirdImage + thirdEnd + imgMid + thirdAlt + imgFoot + linksFoot + linksHead + fourthLine + linksMid + imgHead + fourthImage + fourthEnd + imgMid + fourthAlt + imgFoot + linksFoot + linksHead + fifthLine + linksMid + imgHead + fifthImage + fifthEnd + imgMid + fifthAlt + imgFoot + linksFoot + linksHead + sixthLine + linksMid + imgHead + sixthImage + sixthEnd + imgMid + sixthAlt + imgFoot + linksFoot; // Place the check for data parsing here checkParse(); out.println(""); out.println(""); out.println("" + SystemName + ""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" "); out.println(""); out.println(""); out.println(" "); out.println(""); out.println(""); out.println(" "); out.println("
"); out.println("
"); out.println(""); out.println("Help
"); if (Type == 1 || Type == 3) { out.println("Logout
"); } out.println("
"); out.println(""); out.println(""); out.println("
 
"); out.println(""); out.println(LinksLine); out.println(""); out.println("
"); out.println(""); out.println(" "); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("
"); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(""); out.println(" "); out.println("
"); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(""); out.println(" "); out.println(""); out.println(""); } else if (Type == 2) { out.println("Login
"); out.println("
to your account"); out.println(""); out.println(""); } else if (Type == 3) { out.println("Admin Tools"); out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); } out.println(" "); out.println("
"); if (Type == 1) { out.println("Tools
"); out.println("
for research
"); out.println("
"); out.println("° View a quote: "); out.println("
"); out.println(""); out.println(" "); out.println(""); out.println(""); out.println(""); out.println("
"); out.println(""); out.println(" "); out.println(""); out.println("
"); out.println("
"); out.println("
"); out.println("
"); out.println("
"); out.println(""); out.println("
"); out.println(""); out.println(""); out.println("
"); out.println(" 
"); out.println(" "); out.println(""); out.println("
"); out.println("° Forgot password?
"); out.println("

"); out.println("MoreCreate account

"); out.println("° Manage Users
"); out.println("° Manage Companies
"); out.println("° Watch Transactions
"); out.println("° Monitor News
"); out.println("° Parameters
"); out.println("
"); out.println("
"); out.println("
"); try { QuoteFlash(out, Type); } catch (Exception e) { e.printStackTrace(); } out.println("
"); out.println(""); out.println(""); out.println(""); out.println("
"); } public void printBot(PrintWriter out, String SessionId, int Type) throws IOException { Locale locale = new Locale("en","US"); DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale); String weekTitle = (String)null; String weekId = (String)null; java.util.Date weekDate = new java.util.Date(); java.util.Date weekDateO = new java.util.Date(); out.println(""); out.println(""); out.println(" "); out.println(""); out.println(""); out.println("
  "); out.println(""); out.println(" "); out.println(" "); out.println("
"); out.println(""); out.println(" "); out.println(" "); out.println(""); } else if (Type == 2) { out.println(" Market News"); } else if (Type == 3) { out.println(" Market News"); } out.println("
"); if (Type == 1) { out.println(" Market News
"); // We only want to get Headlines within 2 weeks of the current // date, set up the Date qualifier. String query = "select Title, Id, Date from News order by Date desc"; result = doQuery(query); out.println(""); int reps = 0; try { while (result.next() && reps < 6) { weekDateO = weekDate; reps++; weekTitle = result.getString("Title"); weekId = result.getString("Id"); weekDate = result.getDate("Date"); if (!weekDate.equals(weekDateO)) { // Just a formatting thing, don't want to push down the links // if it is printing the top one. if (reps > 1) { out.println(""); } out.println(""); if (Type == 1) { out.println(""); } else if (Type == 2) { out.println(""); } else if (Type == 3) { out.println(""); } } else { if (Type == 1) { out.println(""); } else if (Type == 2) { out.println(""); } else if (Type == 3) { out.println(""); } } } } catch (Exception e) { e.printStackTrace(); } out.println(""); if (SessionId != "") { // Check to see if this is a Company user. If so, give Add // News link. query = "select Type from Account where AccountId = " + getAccountId(SessionId); result = doQuery(query); String Typ = (String)null; try { while (result.next()) { Typ = result.getString("Type"); } } catch (Exception e) { e.printStackTrace(); } if (Typ.equals("C")) { out.println(""); } } if (Type == 1) { out.println(""); } else if (Type == 2) { out.println(""); } else if (Type == 3) { out.println(""); } out.println("

" + shortFormat.format(weekDate) + "
°" + weekTitle + "
°" + weekTitle + "
°" + weekTitle + "
°" + weekTitle + "
°" + weekTitle + "
°" + weekTitle + "

MoreAdd News
MoreAll Headlines
MoreAll Headlines

MoreAll Headlines
"); out.println("
"); out.println("
"); out.println("
"); out.println("


"); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(""); out.println(""); out.println(" "); out.println("
"); out.println("

"); if (Type == 1) { out.println("Home | "); out.println("Quotes & Research |"); out.println("Buy & Sell
"); out.println("My Portfolio |"); out.println(" My Account | "); out.println(" News Headlines |"); } else if (Type == 2) { out.println("Help |"); out.println("Home | "); out.println("Quotes & Research |"); out.println(" News Headlines"); } else if (Type == 3) { out.println("Help |"); out.println("Home | "); out.println("Quotes & Research |"); out.println("Buy & Sell
"); out.println(" News Headlines |"); } out.println("

Page-Top
"); out.println(""); out.println(""); } public boolean checkRules (String Symbol, int numShares, double Value, String Trans, int Action, String SessionId) throws IOException { double ChangeCap = 0; double ChangeValue = 0; double compValue = 0; int compShares = 0; double Cap = 0; ResultSet result = null; String query = (String)null; boolean pass = true; // The rules are coded as simple checks. The values for these rules can be // altered under the Administrative Parameters page so let's first retrieve // these values. // // Note, ChangeValue must be a decimal number. query = "select ChangeCap, ChangeValue from Parameters"; result = doQuery(query); try { while (result.next()) { ChangeCap = result.getDouble("ChangeCap"); ChangeValue = result.getDouble("ChangeValue"); } } catch (Exception e) { e.printStackTrace(); } // Okay, general format for the rules: // // If the trade would change the Market Cap more than ChangeCap, freeze // the transaction. // // If the trade changes the Value more than ChangeValue, then freeze. // // If the current value of the stock is less than or equal to $0.50 then // it can be modified 2*ChangeValue // Compute Capitalization for the stock double Capitalization = 0.00; ResultSet result2 = null; double userValue = 0; int userShares = 0; String userName = (String)null; query = "select Username from Account where Username != 'root' order by Username"; result2 = doQuery(query); try { while (result2.next()) { userName = result2.getString("Username"); query = "select * from " + userName + " where Symbol = '" + Symbol + "' and Trans != 'B' and Trans != 'FB'"; result = doQuery(query); while (result.next()) { userValue = result.getDouble("boughtAt"); userShares = result.getInt("NumShares"); Capitalization += (userValue * userShares); } } } catch (Exception e) { e.printStackTrace(); } // If ChangeCap = 0 then no check needs to be done if (ChangeCap > 0) { double checkCap = Value * (double)compShares; if ((checkCap - Capitalization) >= ChangeCap || (checkCap - Capitalization) <= -ChangeCap) { pass = false; } } // If ChangeValue = 0 then no check needs to be done if (ChangeValue > 0) { if (Value <= .5) { ChangeValue = ChangeValue * 2; } double changeAmt = compValue * ChangeValue; if (Value > (compValue+changeAmt) || Value < (compValue - changeAmt)) { pass = false; } } if (!pass && Action == 2) { // Transaction must have failed, let's move it to frozen. // First make sure this user holds the lock if (SessionId.equals(hasLock)) { // Delete the offer from the queue query = "delete from qt" + Symbol.toLowerCase() + " where AccountId = " + getAccountId(SessionId) + " and Trans = '" + Trans + "'"; doUpdate(query); // Switch to Frozen in User Holdings query = "update " + getUsername(SessionId) + " set Trans = 'F" + Trans + "' where Symbol = '" + Symbol + "' and Trans = '" + Trans + "'"; doUpdate(query); // Add to Frozen table query = "insert into Frozen (AccountId, Symbol, Trans, NumShares, tradeAt) values (" + getAccountId(SessionId) + ", '" + Symbol + "', '" + Trans + "', " + numShares + ", " + Value + ")"; doUpdate(query); } } return pass; } public void displayGraph(PrintWriter out, String Type, String Symbol, int Links) { out.println("

"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("</comment>No JDK 1.2 support for applet!"); out.println(""); String LinkTo = (String)null; if (Links == 1) { LinkTo = ".Quotes?Symbol=" + Symbol; } else if (Links == 2) { LinkTo = ".Admin?task=quote&Symbol=" + Symbol; } else if (Links == 3) { LinkTo = ".nonMember?task=viewQuote&Symbol=" + Symbol; } if (Links != 0) { out.println("
"); out.println(""); out.println(""); out.println(""); out.println(""); out.println("
TodayThis WeekThis MonthThis Year
"); } out.println("

"); } public boolean checkLock() throws IOException { String query = (String)null; ResultSet result = null; String Lock = (String)null; query = "select Locked from Parameters"; result = doQuery(query); try { while (result.next()) { Lock = result.getString("Locked"); } } catch (Exception e) { e.printStackTrace(); } if (Lock.equals("Y")) { return true; } else { return false; } } public boolean checkFreeze() throws IOException { String query = (String)null; ResultSet result = null; String Freeze = (String)null; query = "select Frozen from Parameters"; result = doQuery(query); try { while (result.next()) { Freeze = result.getString("Frozen"); } } catch (Exception e) { e.printStackTrace(); } if (Freeze.equals("Y")) { return true; } else { return false; } } // The findTrans methods will search the queue tables for a transaction // matching the proposed offer. // In the future add more findTrans methods to perform different searches. // This will move searches from individual code each time it is done to this // one set of common methods. // Looks for an offer match - this would check for multiple offers. public boolean findTrans(String Symbol, String Type, String Owner, String SessionId) throws IOException { String query = (String)null; String FoundId = ""; ResultSet result = null; // First double check the lock if (!SessionId.equals(hasLock)) { // Returning true here will result in an error - if SessionId doesn't // have the lock, we want an error thrown, so return true. return true; } else { query = "select AccountId from qt" + Symbol.toLowerCase() + " where Trans = '" + Type + "' and AccountId = '" + Owner + "'"; result = doQuery(query, SessionId); try { while (result.next()) { FoundId = result.getString("AccountId"); } } catch (Exception e) { e.printStackTrace(); } if (FoundId.equals("")) { // Check the Frozen table query = "select AccountId from Frozen where Trans = '" + Type + "' and AccountId = '" + Owner + "'"; result = doQuery(query, SessionId); try { while (result.next()) { FoundId = result.getString("AccountId"); } } catch (Exception e) { e.printStackTrace(); } } if (FoundId.equals(Owner)) { return true; } else { return false; } } } // This method will search the queue tables for an offer that fits the // specifications of the offer. public Vector findTrans(Offers current, String SessionId) throws IOException, ServletException { String Symbol = (String)null; String Type = (String)null; String AccountId = (String)null; double Value = 0; int numShares = 0; String query = (String)null; ResultSet result = null; String thisAcId = (String)null; double thisVal = 0; int thisShar = 0; Timestamp tradeSet = null; Vector Found = new Vector(); Symbol = current.getSymbol(); Type = current.getType(); Value = current.getValue(); numShares = current.getShares(); AccountId = current.getAccountId(); if (Type.equals("B")) { // We are looking for Sell offers that are equal to or less than // the specified Value // // Make sure the user isn't buying and selling to themself. query = "select tradeAt, NumShares, AccountId from qt" + Symbol.toLowerCase() + " where Trans = 'S' and tradeAt <= " + Value + " and AccountId != '" + AccountId + "' order by tradeAt, Dtime"; result = doQuery(query, SessionId); try { while (result.next()) { thisVal = result.getDouble("tradeAt"); thisShar = result.getInt("NumShares"); thisAcId = result.getString("AccountId"); Found.addElement(new Offers(Symbol, "S", thisVal, thisShar, tradeSet, thisAcId)); } } catch (Exception e) { e.printStackTrace(); } } else if (Type.equals("S")) { // We are looking for Buy offers equal to or greater than the // specified Value query = "select tradeAt, NumShares, AccountId from qt" + Symbol.toLowerCase() + " where Trans = 'B' and tradeAt >= " + Value + " and AccountId != '" + AccountId + "' order by tradeAt, Dtime"; result = doQuery(query, SessionId); try { while (result.next()) { thisVal = result.getDouble("tradeAt"); thisShar = result.getInt("NumShares"); thisAcId = result.getString("AccountId"); Found.addElement(new Offers(Symbol, "B", thisVal, thisShar, tradeSet, thisAcId)); } } catch (Exception e) { e.printStackTrace(); } } return Found; } // modQueue has several duties. It is responsible for adding, modifying and // removing transactions. When a transaction comes in, modQueue will check // the queue tables to see if the user already has an offer in the queue. If // not, it adds a new offer. If the user does, modQueue assumes a trade has // taken place and the offer is being changed. Then, depending on how much is // being traded, it will either remove or modify the old transaction. public boolean modQueue (Offers current, String SessionId) throws IOException, ServletException { String Symbol = (String)null; String Type = (String)null; String Owner = (String)null; double Value = 0; int numShares = 0; double existsShares = 0; double diffShares = 0; double finShares = 0; String query = (String)null; ResultSet result = null; Symbol = current.getSymbol(); Type = current.getType(); Owner = current.getAccountId(); Value = current.getValue(); numShares = current.getShares(); // Search the queue for an existing transaction query = "select numShares from qt" + Symbol.toLowerCase() + " where Trans = '" + Type + "' and AccountId = '" + Owner + "'"; result = doQuery(query, SessionId); try { while (result.next()) { existsShares = result.getInt("numShares"); } } catch (Exception e) { e.printStackTrace(); } if (existsShares > 0) { // Transaction already exists - simply modify it. // Figure out the remaining number of shares. diffShares = existsShares - numShares; if (diffShares == 0) { finShares = 0; } else if (diffShares < 0) { finShares = 0; } else if (diffShares > 0) { finShares = diffShares; } if (finShares == 0) { query = "delete from qt" + Symbol.toLowerCase() + " where Trans = '" + Type + "' and AccountId = '" + Owner + "'"; doUpdate(query, SessionId); } else { query = "update qt" + Symbol.toLowerCase() + " set numShares = " + finShares + " where Trans = '" + Type + "' and AccountId = '" + Owner + "'"; doUpdate(query, SessionId); } } else { // Transaction doesn't exist - add a new one. query = "insert into qt" + Symbol.toLowerCase() + " (AccountId, Trans, NumShares, tradeAt, Dtime) values ('" + Owner + "', '" + Type + "', " + numShares + ", " + Value + ", NOW())"; doUpdate(query, SessionId); } return true; } // modHoldings works very similarly to modQueue but with a users holdings // instead of changing the queue tables. Primarily, when a transaction comes // in that already exists in the users holdings, if it is a Buy order, the // Pending transaction will be modified and actual holdings will be modified. public boolean modHoldings (Offers current, String SessionId) throws IOException, ServletException { String Symbol = (String)null; String Type = (String)null; String Owner = (String)null; String OwnerName = (String)null; double Value = 0; int numShares = 0; int fixedHolds = 0; double heldShares = 0; double diffShares = 0; double finShares = 0; double boughtAt = 0; String query = (String)null; ResultSet result = null; Symbol = current.getSymbol(); Type = current.getType(); Owner = current.getAccountId(); Value = current.getValue(); numShares = current.getShares(); // Search the users Holdings to see if they have pending jobs OwnerName = getUser(Owner); query = "select NumShares from " + OwnerName + " where Trans = '" + Type + "' and Symbol = '" + Symbol + "'"; result = doQuery(query, SessionId); try { while (result.next()) { heldShares = result.getInt("NumShares"); } } catch (Exception e) { e.printStackTrace(); } if (heldShares > 0) { // Pending offer exists in holdings - modify it. diffShares = heldShares - numShares; if (Type.equals("B")) { if (diffShares == 0 || diffShares < 0) { // Remove the pending transaction query = "delete from " + OwnerName + " where Trans = '" + Type + "' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); // See if user already has fixed holdings query = "select NumShares from " + OwnerName + " where Trans = 'C' and Symbol = '" + Symbol + "'"; result = doQuery(query, SessionId); try { while (result.next()) { fixedHolds = result.getInt("NumShares"); } } catch (Exception e) { e.printStackTrace(); } if (fixedHolds > 0) { // Modify the existing holdings fixedHolds = fixedHolds + numShares; query = "update " + OwnerName + " set NumShares = " + fixedHolds + ", boughtAt = " + Value + " where Trans = 'C' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); } else { // Add the new holdings query = "insert into " + OwnerName + " (Symbol, NumShares, boughtAt, tradeAt, Trans, Dtime) values ('" + Symbol.toUpperCase() + "', " + numShares + ", " + Value + ", " + Value + ", 'C', NOW())"; doUpdate(query, SessionId); } } else if (diffShares > 0) { // Lower the amount Pending but add to Fixed query = "update " + OwnerName + " set NumShares = " + diffShares + " where Trans = '" + Type + "' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); // See if user already has fixed holdings query = "select NumShares from " + OwnerName + " where Trans = 'C' and Symbol = '" + Symbol + "'"; result = doQuery(query, SessionId); try { while (result.next()) { fixedHolds = result.getInt("NumShares"); } } catch (Exception e) { e.printStackTrace(); } if (fixedHolds > 0) { // Modify the existing holdings fixedHolds = fixedHolds + numShares; query = "update " + OwnerName + " set NumShares = " + fixedHolds + ", boughtAt = " + Value + " where Trans = 'C' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); } else { // Add the new holdings query = "insert into " + OwnerName + " (Symbol, NumShares, boughtAt, tradeAt, Trans, Dtime) values ('" + Symbol.toUpperCase() + "', " + numShares + ", " + Value + ", " + Value + ", 'C', NOW())"; doUpdate(query, SessionId); } } } else if (Type.equals("S")) { // Modifying Sell holdings is easy - just change the transaction. if (diffShares == 0 || diffShares < 0) { // Remove the transaction from Holdings query = "delete from " + OwnerName + " where Trans = '" + Type + "' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); } else if (diffShares > 0) { // Update the Holdings query = "update " + OwnerName + " set NumShares = " + diffShares + " where Trans = '" + Type + "' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); } } } else { // We're adding a new Pending task to Holdings. Action will be different // if it is a Buy or Sell. if (Type.equals("B")) { // Buy is easy - simply add a Pending task query = "insert into " + OwnerName + " (Symbol, NumShares, tradeAt, Trans, Dtime) values ('" + Symbol.toUpperCase() + "', " + numShares + ", " + Value + ", '" + Type + "', NOW())"; doUpdate(query, SessionId); } else if (Type.equals("S")) { // For Sell we have to add a new Pending transaction but the Fixed // holdings has to be modified as well. // First get the Fixed holdings query = "select NumShares, boughtAt from " + OwnerName + " where Trans = 'C' and Symbol = '" + Symbol + "'"; result = doQuery(query, SessionId); try { while (result.next()) { fixedHolds = result.getInt("NumShares"); boughtAt = result.getDouble("boughtAt"); } } catch (Exception e) { e.printStackTrace(); } // Decrease fixed holdings finShares = fixedHolds - numShares; if (finShares == 0) { query = "delete from " + OwnerName + " where Symbol = '" + Symbol + "' and Trans = 'C'"; doUpdate(query, SessionId); } else { query = "update " + OwnerName + " set NumShares = " + finShares + " where Trans = 'C' and Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); } // Add a pending job query = "insert into " + OwnerName + " (Symbol, NumShares, boughtAt, tradeAt, Trans, Dtime) values ('" + Symbol.toUpperCase() + "', " + numShares + ", " + boughtAt + ", " + Value + ", '" + Type + "', NOW())"; doUpdate(query, SessionId); } } return true; } // This modHoldings simply takes the Username and number of Shares and // changes that users fixed holdings. public void modHoldings(String User, String Symbol, int Shares) throws IOException { String query = (String)null; ResultSet result = null; int haveShares = 0; int newShares = 0; // Find out how many shares the user already has query = "select NumShares from " + User + " where Symbol = '" + Symbol + "' and Trans = 'C'"; result = doQuery(query); try { while (result.next()) { haveShares = result.getInt("NumShares"); } } catch (Exception e) { e.printStackTrace(); } if (haveShares > 0) { newShares = haveShares + Shares; if (newShares < 0) { newShares = 0; } } else { if (Shares < 0) { newShares = 0; } else { newShares = Shares; } } // Either update, insert or delete, depending on the value of newShares if (newShares > 0) { if (haveShares > 0) { query = "update " + User + " set NumShares = " + newShares + " where Symbol = '" + Symbol + "' and Trans = 'C'"; } else { query = "insert into " + User + " (Symbol, NumShares, Trans, Dtime) values ('" + Symbol + "', " + newShares + ", 'C', NOW())"; } doUpdate(query); } else { query = "delete from " + User + " where Symbol = '" + Symbol + "' and Trans = 'C'"; doUpdate(query); } } public void modBalance (String AccountId, double Amount, String Task) throws IOException, ServletException { double Balance = 0; String query = (String)null; ResultSet result = null; DecimalFormat numFormat = new DecimalFormat("################0.00"); query = "select Balance from Portfolio where AccountId = '" + AccountId + "'"; result = doQuery(query); try { while (result.next()) { Balance = result.getDouble("Balance"); } } catch (Exception e) { e.printStackTrace(); } if (Task.equals("-")) { Balance = Balance - Amount; } else { Balance = Balance + Amount; } query = "update Portfolio set Balance = " + numFormat.format(Balance) + " where AccountId = '" + AccountId + "'"; doUpdate(query); } // One thing that takes place a lot is printing of Confirmation messages. This // method makes that a more automated process. Not all confirmation tasks will be // able to use this, but many will. public void printConfirm(String Title, String Message, int On, String ConfLink, PrintWriter out, String SessionId) throws IOException, ServletException { // Add this in } // This method simply returns the Commission cost public double getCommission(String SessionId) throws IOException { String query = (String)null; ResultSet result = null; double Commission = 0.00; query = "select Commission from Parameters"; result = doQuery(query, SessionId); try { while (result.next()) { Commission = result.getDouble("Commission"); } } catch (Exception e) { e.printStackTrace(); } return Commission; } // This method parses the overall market value public void parseValue() throws IOException { String query = (String)null; String Symbol = (String)null; ResultSet result = null; double compVal = 0; double Avg = 0.00; int Count = 0; DecimalFormat numFormat = new DecimalFormat("################0.00"); query = "select Last, Symbol from Companies where Symbol != 'SYS'"; result = doQuery(query); try { while (result.next()) { compVal = result.getDouble("Last"); Symbol = result.getString("Symbol"); Avg += compVal; Count++; query = "insert into ht" + Symbol.toLowerCase() + "(Date, Time, Value) values (NOW(), NOW(), " + compVal + ")"; doUpdate(query); } } catch (Exception e) { e.printStackTrace(); } if (Count > 0) { Avg = Avg / Count; } // Using NOW() for SQL.Time is quirky so manually setting up the current // time is the preferred. java.util.Date setTime = new java.util.Date(); query = "insert into htsys (Date, Time, Value) values (NOW(), '" + setTime.getHours() + ":" + setTime.getMinutes() + ":" + setTime.getSeconds() + "', " + numFormat.format(Avg) + ")"; doUpdate(query); query = "update Companies set Last = " + Avg + " where Symbol = 'SYS'"; doUpdate(query); calcValue = new java.util.Date(); } // Parse the daily data public void parseDaily() throws IOException { String query = (String)null; ResultSet result = null; DecimalFormat numFormat = new DecimalFormat("################0.00"); // Grab the transaction lock hasLock = "9999"; isLocked = true; // First things first - make SURE the daily parse hasn't already been done. // If ehtsys has this date already, let's not parse again. java.util.Date chkDate = new java.util.Date(); int chkProc = 0; // dailyParse is the java.util.Date var used to store the date of the // previous parse query = "select Date from ehtsys where Date = '" + (chkDate.getYear() + 1900) + "-" + (chkDate.getMonth() + 1) + "-" + chkDate.getDate() + "'"; result = doQuery(query); try { while (result.next()) { chkProc++; } } catch (Exception e) { e.printStackTrace(); } if (chkProc == 0) { // Update the Companies entry for System - set its Open to the last value // in htsys double putVal = 0; query = "select Value from htsys order by Date, Time desc"; result = doQuery(query); try { // We only want one result.next(); putVal = result.getDouble("Value"); } catch (Exception e) { e.printStackTrace(); } query = "update Companies set Open = " + putVal + " where Symbol = 'SYS'"; doUpdate(query); Vector Cmps = new Vector(); Vector Dates = new Vector(); // Get the symbols of all companies and add to a Vector. query = "select Symbol from Companies where Symbol != 'SYS'"; result = doQuery(query); try { while (result.next()) { String Cmp = result.getString("Symbol"); Cmps.addElement((String)Cmp); } } catch(Exception e) { e.printStackTrace(); } // Loop through the Companies and parse whatever is in its // History table. for (int i = 0 ; i < Cmps.size() ; i++) { String Cmp = (String)Cmps.elementAt(i); double avg = 0.00; int count = 0; double val = 0.00; double Lst = 0.00; query = "select Last from Companies where Symbol = '" + Cmp + "'"; result = doQuery(query); try { // Set all daily values. Right now they just go to Last since // there are no numeric manipulations taking place. while (result.next()) { Lst = result.getDouble("Last"); } } catch (Exception e) { e.printStackTrace(); } query = "update Companies set Open = " + numFormat.format(Lst) + ", Previous = " + numFormat.format(Lst) + ", DayHi = " + numFormat.format(Lst) + ", DayLo = " + numFormat.format(Lst) + " where Symbol = '" + Cmp + "'"; doUpdate(query); // We don't want every date - just the unique ones. query = "select distinct(Date) from ht" + Cmp.toLowerCase(); result = doQuery(query); try { while (result.next()) { Dates.addElement((java.util.Date)result.getDate("Date")); } } catch (Exception e) { e.printStackTrace(); } for (int j = 0; j < Dates.size() ; j++) { java.util.Date findDate = (java.util.Date)Dates.elementAt(j); query = "select Value from ht" + Cmp.toLowerCase() + " where Date = " + findDate; result = doQuery(query); try { while (result.next()) { count++; val += result.getDouble("Value"); } } catch (Exception e) { e.printStackTrace(); } // Get the average value if (count != 0 && val != 0) { avg = val / count; } else { avg = 0; } // Add to symbol's Extended history if (avg > 0) { query = "insert into eht" + Cmp.toLowerCase() + " (Date, Value) values (" + findDate + ", " + numFormat.format(avg) + ")"; doUpdate(query); } count = 0; val = 0; avg = 0; } // Clear symbol's Volume query = "update Companies set Volume = 0 where Symbol = '" + Cmp + "'"; doUpdate(query); // Delete from History table query = "delete from ht" + Cmp.toLowerCase(); doUpdate(query); } // Calculate Extended Market Average int count = 0; double val = 0.00; query = "select Value from htsys"; result = doQuery(query); try { while (result.next()) { count++; val += result.getDouble("Value"); } } catch (Exception e) { } if (count > 0) { val = val / count; } if (val > 0) { query = "insert into ehtsys (Date, Value) values (NOW(), " + numFormat.format(val) + ")"; doUpdate(query); } query = "delete from htsys"; doUpdate(query); } // Update Parameters and Variable Locked time. query = "update Parameters set DailyParse = NOW()"; doUpdate(query); dailyParse = getDaily(); // Unlock everything isLocked = false; } // This method handles buying and selling. public void doTrans (Offers current, String SessionId, boolean adminCheck, HttpServletResponse response) throws IOException, ServletException { String TransOwner = (String)null; String Symbol = (String)null; String Type = (String)null; double offerValue = 0; int numShares = 0; String matchOwner = (String)null; double matchBalance = 0; double matchValue = 0; int matchShares = 0; int totalShares = 0; double Cost = 0; boolean notAll = false; double canBuy = 0; Double convVal = null; Integer convInt = null; double compVal = 0; String query = (String)null; ResultSet result = null; Offers matchOffer = new Offers(); boolean transAdded = false; boolean holdAdded = false; double shareValue = 0; double totalCost = 0; double boughtAt = 0; double Last = 0.00; int Volume = 0; double Hi = 0.00; double Lo = 0.00; double dayHi = 0.00; double dayLo = 0.00; Vector Queue = new Vector(); int transMatch = 0; String TransLog = ""; int numTrans = 0; String Message = ""; String Subject = ""; String compType = (String)null; String Locked = "9999"; boolean isLocked = true; boolean offersAvail = false; boolean passRules = true; int error = 0; // Initialize currency format DecimalFormat curFormat = new DecimalFormat("$##,######,###,###,##0.00"); DecimalFormat numFormat = new DecimalFormat("################0.00"); DecimalFormat intFormat = new DecimalFormat("################0"); // Lock trading while (isLocked) { Locked = LockTrading(SessionId); if (!Locked.equals("9999") && Locked.equals(SessionId)) { isLocked = false; } else if (!Locked.equals("9999") && !Locked.equals(SessionId)) { isLocked = false; error = 1; } } // Retrieve data from the Offer Symbol = current.getSymbol(); Type = current.getType(); offerValue = current.getValue(); numShares = current.getShares(); TransOwner = current.getAccountId(); // Make sure the user isn't trying to have multiple "buy" or "sell" // offers on the same company. if (error == 0) { if (findTrans(Symbol, Type, TransOwner, SessionId)) { error = 2; } } if (error == 0) { if (!adminCheck) { // Take the commission from the users balance // If this is being done by an Admin, the commission isn't // taken out. // Is this a company user? No commission is charged to company // accounts. query = "select Type from Account where AccountId = " + TransOwner; result = doQuery(query, SessionId); try { while (result.next()) { compType = result.getString("Type"); } } catch (Exception e) { e.printStackTrace(); } if (!compType.equals("C")) { modBalance(TransOwner, getCommission(SessionId), "-"); } } // Add the transaction to the queue // See documentation in BullyDB.java for info on modQueue transAdded = modQueue(current, SessionId); // Add the transaction to the users holdings // See documentation in BullyDB.java for info on modHoldings holdAdded = modHoldings(current, SessionId); // Make sure the transaction fits the rules. If not, add it to the // frozen transactions list. if (!adminCheck) { passRules = checkRules(Symbol, numShares, offerValue, Type, 2, SessionId); } if (passRules) { // Okay, the transaction has been added to the users Holdings and to the // company Queue. Time to search the queue to see if there are any // transactions that could be traded. Queue = findTrans(current, SessionId); transMatch = Queue.size(); if (transMatch > 0) { offersAvail = true; } while (offersAvail) { matchOffer = (Offers)Queue.elementAt(0); matchValue = matchOffer.getValue(); matchShares = matchOffer.getShares(); matchOwner = matchOffer.getAccountId(); // Load numShares again in case this is a repeated running // of the while loop. numShares = current.getShares(); if (numShares > matchShares) { totalShares = matchShares; } else { totalShares = numShares; } // It's a buyers market so calculate the cost based on // how the buyer will most benefit. if (Type.equals("B")) { Cost = matchValue * totalShares; shareValue = matchValue; } else { Cost = offerValue * totalShares; shareValue = offerValue; } totalCost += Cost; // If this is a Buy then a check has already been done // to ensure the user has sufficient money. If this is // a sell, we need to make sure the found buyer has the // money to cover this transaction. If the buyer doesn't // have enough money for their full transaction, do as // much as possible and in their trade message let them // know why they didn't buy as much as they wanted. If // they don't have enough money to buy any of the stock, // send a message letting them know. if (Type.equals("S")) { // Get the buyers balance query = "select Balance from Portfolio where AccountId = '" + matchOwner + "'"; result = doQuery(query, SessionId); try { while (result.next()) { matchBalance = result.getDouble("Balance"); } } catch (Exception e) { e.printStackTrace(); } if ((matchBalance - Cost) <= 0) { // User doesn't have enough money for the full purchase! Flag it. notAll = true; // Figure how many shares the user can buy if (Type.equals("B")) { canBuy = matchBalance / matchValue; } else { canBuy = matchBalance / offerValue; } // There has to be a better way to do this, but // the following is in place to convert the double // canBuy to an int value, making sure it rounds // down and not up. // Convert the value to an int convVal = new Double(canBuy); totalShares = convVal.intValue(); // Convert back to double convInt = new Integer(totalShares); compVal = convInt.doubleValue(); // If the new value is greater than the original // value, the conversion must have rounded up so // decrease it by one. if (compVal > canBuy) { compVal = compVal - 1; } // Once again, convert to an int convVal = new Double(compVal); totalShares = convVal.intValue(); } } // Make sure we have at least one share to trade if (totalShares > 0) { // Modify the offers to reflect the transaction. current.setShares(totalShares); matchOffer.setShares(totalShares); // Change the Queue tables for Buyer and Seller. modQueue(current, SessionId); modQueue(matchOffer, SessionId); // Change Buyer and Seller holdings modHoldings(current, SessionId); modHoldings(matchOffer, SessionId); // The current transaction needs to be changed to // reflect the remaining needed shares. current.setShares(numShares - totalShares); // Change Buyer and Seller money if (Type.equals("B")) { modBalance(current.getAccountId(), Cost, "-"); modBalance(matchOffer.getAccountId(), Cost, "+"); } else if (Type.equals("S")) { modBalance(current.getAccountId(), Cost, "+"); modBalance(matchOffer.getAccountId(), Cost, "-"); } // Add this trade to the Transaction string for email. TransLog += intFormat.format(totalShares) + " " + curFormat.format(shareValue) + " " + curFormat.format(Cost) + "\n"; numTrans++; } // Add an entry to the Transaction Log table. query = "insert into TransLog (Symbol, tradeFrom, tradeTo, Trans, Shares, Value, Time) values ('" + Symbol + "', '" + getUser(TransOwner) + "', '" + getUser(matchOwner) + "', '" + Type + "', " + intFormat.format(totalShares) + ", " + numFormat.format(shareValue) + ", NOW())"; doUpdate(query, SessionId); // Update Company and History tables query = "select Last, Volume, 52WkHi, 52WkLo, DayHi, DayLo from Companies where Symbol = '" + Symbol + "'"; result = doQuery(query, SessionId); try { while(result.next()) { Last = result.getDouble("Last"); Volume = result.getInt("Volume"); Hi = result.getDouble("52WkHi"); Lo = result.getDouble("52WkLo"); dayHi = result.getDouble("DayHi"); dayLo = result.getDouble("DayLo"); } } catch(Exception e) { e.printStackTrace(); } if (shareValue > dayHi) { dayHi = shareValue; } else if (shareValue < dayLo) { dayLo = shareValue; } if (shareValue > Hi) { Hi = shareValue; } else if (shareValue < Lo) { Lo = shareValue; } Volume += numShares; query = "update Companies set Last = " + numFormat.format(shareValue) + ", Volume = " + intFormat.format(Volume) + ", 52WkHi = " + numFormat.format(Hi) + ", 52WkLo = " + numFormat.format(Lo) + ", DayHi = " + numFormat.format(dayHi) + ", DayLo = " + numFormat.format(dayLo) + " where Symbol = '" + Symbol + "'"; doUpdate(query, SessionId); // Update System volume query = "select Volume from Companies where Symbol = 'SYS'"; result = doQuery(query, SessionId); try { while(result.next()) { Volume = result.getInt("Volume"); } } catch(Exception e) { e.printStackTrace(); } Volume += numShares; query = "update Companies set Volume = " + intFormat.format(Volume) + " where Symbol = 'SYS'"; doUpdate(query, SessionId); query = "insert into ht" + Symbol.toLowerCase() + " (Date, Time, Value) values (NOW(), NOW(), " + numFormat.format(shareValue) + ")"; doUpdate(query, SessionId); // Email the matchOffer Owner // If they didn't have the money for the full transaction, send a // special email if (notAll) { Subject = SystemName + " -- BUY of " + Symbol.toUpperCase() + " has been processed."; if (totalShares < 1) { Message = "A user has sent in a Sell offer that matches your Buy request. However, you\ndid not have sufficient funds to purchase any of the available shares.\nWhen making a Buy offer, keep in mind that payment doesn't take place\nuntil a Sell offer has been made that matches your request.\n\n" + SystemName + "\n"; } else { Message = "You have purchased " + intFormat.format(totalShares) + " of " + Symbol.toUpperCase() + " at " + numFormat.format(shareValue) + " a share\nfor a total cost of: " + numFormat.format(Cost) + ".\n\nYour initial offer was for " + intFormat.format(matchShares) + " but you did not have\nsufficient money for this transaction. Your remaining Buy\noffer is still in your queue. Please keep in mind that when\nyou make a Buy offer, payment doesn't take place until a Sell offer\nhas been made that matches your request.\n\n" + SystemName + "\n"; } } else { if (Type.equals("B")) { Subject = SystemName + " -- SELL of " + Symbol.toUpperCase() + " has been processed."; Message = "You have successfully sold " + intFormat.format(totalShares) + " of " + Symbol.toUpperCase() + " at " + numFormat.format(shareValue) + " a share\nfor a total gain of " + numFormat.format(Cost) + ".\n\nNote, if you offered more than " + intFormat.format(totalShares) + " shares, the remaining shares\nare still in the queue to be sold. The matching buy offer was only\nfor " + intFormat.format(totalShares) + ".\n\n" + SystemName + "\n"; } else { Subject = SystemName + " -- BUY of " + Symbol.toUpperCase() + " has been processed."; Message = "You have successfully purchased " + intFormat.format(totalShares) + " of " + Symbol.toUpperCase() + " at " + numFormat.format(shareValue) + " a share\nfor a total cost of " + numFormat.format(Cost) + ".\n\nNote, if you requested more than " + intFormat.format(totalShares) + " shares, the remaining shares\nare still in the queue to be purchased. The matching sell\noffer was only for " + intFormat.format(totalShares) + ".\n\n" + SystemName + "\n"; } } sendEmail(Subject, Message, matchOwner, SessionId); // Is there anything left to this offer? if ((numShares - totalShares) <= 0) { offersAvail = false; Queue = null; } else { Queue.removeElementAt(0); if (Queue.size() < 1) { offersAvail = false; } } } // Email the person making this transaction if (numTrans > 0) { if (Type.equals("B")) { Subject = SystemName + " -- BUY of " + Symbol.toUpperCase() + " has been processed."; } else { Subject = SystemName + " -- SELL of " + Symbol.toUpperCase() + " has been processed."; } if (numTrans > 1) { if (Type.equals("B")) { Message = "Your Buy offer of " + Symbol.toUpperCase() + " has been processed. Your offer matched\nmultiple Sell offers so the transaction has multiple parts:\nShares Cost per Share Total Cost\n" + TransLog + "\nFinal Cost: " + numFormat.format(totalCost) + "\n\n" + SystemName + "\n"; } else { Message = "Your Sell offer of " + Symbol.toUpperCase() + " has been processed. Your offer matched\nmultiple Buy offers so the transaction has multiple parts:\nShares Price per Share Total Gain\n" + TransLog + "\nFinal Gain: " + numFormat.format(totalCost) + "\n\n" + SystemName + "\n"; } } else { if (Type.equals("B")) { Message = "Your Buy offer of " + Symbol.toUpperCase() + " has been processed.\nShares Cost per Share Total Cost\n" + TransLog + "\n\n" + SystemName + "\n"; } else { Message = "Your Sell offer of " + Symbol.toUpperCase() + " has been processed.\nShares Gain per Share Total Gain\n" + TransLog + "\n\n" + SystemName + "\n"; } } sendEmail(Subject, Message, TransOwner, SessionId); } } } else { // Initialize output stream response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (error == 1) { if (adminCheck) { printTop(out, 24); } else { printTop(out, 4); } // Fill in the blanks from the template if (adminCheck) { out.println("\"Admin\"
"); } else { out.println("\"BSE
"); } out.println("

Error:

"); out.println("

A system error occured while trying to process your request. Please go back and try again. If the problem persists, send an email to " + SystemEmail + " detailing the problem.

"); if (adminCheck) { printBot(out, SessionId, 1); } else { printBot(out, SessionId, 3); } } else if (error == 2) { if (adminCheck) { printTop(out, 24); } else { printTop(out, 4); } // Fill in the blanks from the template if (adminCheck) { out.println("\"Admin\"
"); } else { 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.

"); if (adminCheck) { printBot(out, SessionId, 1); } else { printBot(out, SessionId, 3); } } out.close(); } // Unlock transaction while (!isLocked) { isLocked = UnLockTrading(SessionId); } // Everything seems to have gone okay, send user back to the Buy/Sell page response.sendRedirect(ServletURL + ".buysell"); } // Generates and sets a random password for a user public String genPass(String AccountId, boolean doSet) throws IOException { String query = (String)null; String newPass = (String)null; // The way password generation works: // A wordlist is set up in the array PassChoice. A random number is // generated to pick from this wordlist. At the end of the word picked, // a random number(0-99) is tagged, giving the user their random // password. String[] PassChoice = {"sporadic","gerbil","fruitcake","yellowsub","desktop","gerbil","sporadic","fruitcake","goofy","mother","raven","tiger","golfer","parseit","garbageday","bookshelf","beefjerky","hobbit"}; int rnum, rend; Random rand = new Random(); rnum = rand.nextInt(18); rend = rand.nextInt(100); newPass = PassChoice[rnum] + rend; if (doSet) { // Update the user entry in the database to contain the new password. query = "update Account set Password = password('" + newPass + "') where AccountId = " + AccountId; doUpdate(query); } return newPass; } // Lock the transactions to a particular user static String LockTrading (String SessionId) { String Locked = "9999"; if (isLocked == false) { isLocked = true; hasLock = SessionId; return hasLock; } else { return Locked; } } // Unlock transactions static boolean UnLockTrading (String SessionId) { if (isLocked == false || (!hasLock.equals(SessionId) && !hasLock.equals("9999"))) { return false; } else if (hasLock.equals("9999")) { return true; } else { hasLock = "9999"; isLocked = false; return true; } } }