/* * Created on Aug 8, 2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package AppletInterface; import amber.server.application.ApplicationInterface; import amber.server.component.*; import amber.server.exception.ComponentHandlerException; import amber.server.panel.BaseFrame; import amber.server.panel.*; import amber.type.server.XYConstraints; import amber.utility.*; import java.awt.Color; import java.awt.event.*; import java.awt.event.ItemListener; import java.awt.*; import amber.awt.event.ComponentWindowEvent; import amber.awt.event.ComponentWindowListener; import DataClasses.*; import Validators.*; import XmlCommunication.*; import DatabaseCommunication.*; import java.sql.*; /** * This class handles the requirements for the specific manipulation of panels within * specific applications. In a lot of ways this class functions very similarly to the * ApplicationInterface class. * This is the overall intelligence for this particular panel. * * @author Insert your name here * @version 1.0.0 * @see amber.server.panel.BaseFrame */ /** * @author student * * This class is the main engine behind the application. It is responsible * for generation of stock values, updating information displayed, as well * as buying and selling stocks. * */ public class MainFrame extends BaseFrame implements ItemListener, ActionListener, TimerInterface, ComponentWindowListener, ComponentListener { private static int STABILITY_FACTOR = 4; //affects the generation of share prices. // based on the flat company tax rate in New Zealand as at 3 September, 2003. private static double TAX_RATE = 0.33; public final int FRAMEWIDTH = 1010; public final int FRAMEHEIGHT = 600; private User_Data user = getStockTradingApplication().getUser(); private UserAddress_Data address = getStockTradingApplication().getAddress(); private Stock_Data[] interested = user.getStocksInterested(); private Stock_Data[] totalstocks = getStockTradingApplication().getStocks(); private StockOwnership_Data[] ownedstocks = user.getStocksOwned(); private UserManager umanager = new UserManager(); private ServletConnection servletconn = new ServletConnection(); private XmlGenerator xmlgenerator = new XmlGenerator(); private XmlUnmarshal xmlunmarshal = new XmlUnmarshal(); private FloatButtonHandler btnMain = new FloatButtonHandler(getParentApplication()); private FloatButtonHandler btnBuy = new FloatButtonHandler(getParentApplication()); private ImageHandler imgBanner = new ImageHandler(getParentApplication()); private FloatButtonHandler btnSell = new FloatButtonHandler(getParentApplication()); private FloatButtonHandler btnUpdate = new FloatButtonHandler(getParentApplication()); private FloatButtonHandler btnLogout = new FloatButtonHandler(getParentApplication()); private LabelHandler lblInfo = new LabelHandler(getParentApplication()); private LabelHandler untitledLabel = new LabelHandler(getParentApplication()); private LabelHandler lblMain = new LabelHandler(getParentApplication()); private TimePlotHandler pltShares = new TimePlotHandler(getParentApplication()); private ChoiceHandler chShares = new ChoiceHandler(getParentApplication()); private ButtonHandler btnAdd = new ButtonHandler(getParentApplication()); private ButtonHandler btnRemove = new ButtonHandler(getParentApplication()); private int PlotLeft = 210; private int PlotTop = 355; private int PlotWidth = 200; private int PlotHeight = 200; private int currentCount = 0; private float[] lastLines = null; private float[] lines = new float[totalstocks.length]; private Timer timer; private Color seriesColors[] = { Color.red, Color.blue, Color.green, Color.magenta, Color.orange, Color.pink, Color.black, Color.cyan, Color.white, Color.gray }; private String[] stockNames; private GenericPanel pnlGraph = new GenericPanel(getParentApplication()); private LabelHandler lblStockName = new LabelHandler(getParentApplication()); private LabelHandler lblStockCode = new LabelHandler(getParentApplication()); private LabelHandler lblHigh = new LabelHandler(getParentApplication()); private LabelHandler lblLow = new LabelHandler(getParentApplication()); private LabelHandler lblDividends = new LabelHandler(getParentApplication()); private LabelHandler lblCps = new LabelHandler(getParentApplication()); private LabelHandler lblTs = new LabelHandler(getParentApplication()); private LabelHandler lblYld = new LabelHandler(getParentApplication()); private LabelHandler lblPeRatio = new LabelHandler(getParentApplication()); private LabelHandler lblNotes = new LabelHandler(getParentApplication()); private LabelHandler lblCpsDefinition = new LabelHandler(getParentApplication()); private LabelHandler lblTcDefinition = new LabelHandler(getParentApplication()); private LabelHandler lblYldDefinition = new LabelHandler(getParentApplication()); private LabelHandler lblPeRatioDefinition = new LabelHandler(getParentApplication()); private Font level1 = new Font("Arial", Font.BOLD, 14); private Font level2 = new Font("Arial", Font.ITALIC, 14); private GenericPanel pnlBuy = new GenericPanel(getParentApplication()); private LabelHandler lblBuy = new LabelHandler(getParentApplication()); private ChoiceHandler chBuyStocks = new ChoiceHandler(getParentApplication()); private LabelHandler lblAccountBuy = new LabelHandler(getParentApplication()); private LabelHandler lblCurrValueBuy = new LabelHandler(getParentApplication()); private LabelHandler lblQtyBuy = new LabelHandler(getParentApplication()); private TextFieldHandler txtQtyBuy = new TextFieldHandler(getParentApplication()); private LabelHandler lblTotalBuy = new LabelHandler(getParentApplication()); private LabelHandler lblBuyInfo = new LabelHandler(getParentApplication()); private GenericPanel pnlSell = new GenericPanel(getParentApplication()); private LabelHandler lblSell = new LabelHandler(getParentApplication()); private ChoiceHandler chSellStocks = new ChoiceHandler(getParentApplication()); private FloatButtonHandler btnViewInfo = new FloatButtonHandler(getParentApplication()); private LabelHandler lblAccountSell = new LabelHandler(getParentApplication()); private LabelHandler lblCurrValueSell = new LabelHandler(getParentApplication()); private LabelHandler lblQtySell = new LabelHandler(getParentApplication()); private TextFieldHandler txtQtySell = new TextFieldHandler(getParentApplication()); private LabelHandler lblTotalSell = new LabelHandler(getParentApplication()); private LabelHandler lblSellInfo = new LabelHandler(getParentApplication()); /** * This is the constructor for MainFrame.java */ public MainFrame() { super(); defineComponents(); } /** * The initialising constructor. * @param appHandler The handle to the main ApplicationInterface which * handles the functions of the overall application. */ public MainFrame(ApplicationInterface appHandler) { super(appHandler); defineComponents(); } /** * The initialising constructor. * @param id The int containing the id of the corresponding remote component * residing on the browser. * @param appHandler The handle to the main ApplicationInterface which * handles the functions of the overall application. */ public MainFrame(int id, ApplicationInterface appHandler) { super(id, appHandler); defineComponents(); } /** * This function would normally never need to be called, but is required * to be defined as it is called internally. * Its specific purpose is to set the controls to a known state once * they are created. */ public void fillControls() { } /** * This function determines if the panel can be closed. * The derived panels must determine if this panel can close. If this is * not possible the function should return false. * @return boolean false if it is not possible to close this panel. */ public boolean canClose() { return true; } /** * This function is called to save any required information in the panel. * This function is called externally when another panel wishes to take * over the base panel or when closing the panel. * This function need not actually do something. */ public void saveData() { } /** * This function is called to define the components which are a part of this * panel. * This function is called by the constructor to set up the normal static * components and their locations. * This method is required. */ protected void defineComponents() { try { setProperties(); addComponents(); addListeners(); //updateSellPanel(); //updateBuyPanel(); //updateSellPanelLabels(); //updateBuyPanelLabels(); redrawCaptions(); } catch (ComponentHandlerException ex) { ex.printStackTrace(); } } /** * This method is being used for setting the properties of components * being used in this frame. * @return void */ private void setProperties() { try { stockNames = new String[interested.length]; this.setTitle("Stock Trading Main Screen"); this.setBackground(Color.WHITE); imgBanner.setImage("stockBanner.jpg"); pnlGraph.setBackground(Color.LIGHT_GRAY); btnMain.setBackground(Color.LIGHT_GRAY); btnUpdate.setBackground(Color.LIGHT_GRAY); btnLogout.setBackground(Color.LIGHT_GRAY); btnBuy.setBackground(Color.GRAY); btnSell.setBackground(Color.GRAY); btnViewInfo.setBackground(Color.GRAY); lblInfo.setFont(level1); lblNotes.setFont(level1); lblDividends.setFont(level1); lblBuyInfo.setFont(level1); lblSellInfo.setFont(level1); btnMain.setLabel("MAIN"); btnBuy.setLabel("BUY"); btnSell.setLabel("SELL"); btnUpdate.setLabel("UPDATE"); btnLogout.setLabel("LOGOUT"); lblInfo.setText("Stock Information :"); untitledLabel.setText( "Please select the share price to observe and press Add."); lblMain.setText( "To remove a share price select the share and press Remove"); btnAdd.setLabel("Add"); btnRemove.setLabel("Remove"); btnViewInfo.setLabel("Ownership Information"); for (int f = 0; f < stockNames.length; f++) { stockNames[f] = interested[f].toString(); } for (int i = 0; i < stockNames.length; i++) { chShares.add(stockNames[i]); chBuyStocks.add(stockNames[i]); } System.out.println("no. of onwedstocks " + ownedstocks.length); for (int g = 0; g < ownedstocks.length; g++) { System.out.println( "+Owned Stock added:+ " + ownedstocks[g].toString()); chSellStocks.add(ownedstocks[g].toString()); } btnMain.setEnabled(false); // Create a timer to create the values timer = new Timer(3000L, this); timer.start(); pltShares.setBackground(new Color(220, 220, 220)); //Color.lightGray); pltShares.setSeriesCount(currentCount); pltShares.setXSampleCount(50); pltShares.setYIncrement(5); pltShares.setXLabel("Time"); pltShares.setCaption("Share Price"); pltShares.setYLabel("Val"); pltShares.setYMax(60F); pltShares.setSeriesCount(1); lblStockName.setText("Stock Name :"); lblStockCode.setText("Stock Code :"); lblHigh.setText("52 Week High :"); lblLow.setText("52 Week Low :"); lblDividends.setText("Dividends :"); lblCps.setText("EPS (cents):"); lblTs.setText("D/S (cents):"); lblYld.setText("Div YLD (%):"); lblPeRatio.setText("P/E Ratio:"); lblNotes.setText("NOTES :"); lblCpsDefinition.setText("EPS - Earnings per Share in cents."); lblTcDefinition.setText( "D/S - Dividends per issued share in cents."); lblYldDefinition.setText("Div YLD - Dividend Yield in percentage."); lblPeRatioDefinition.setText( "P/E Ratio - Price to earnings ratio."); pnlBuy.setName("pnlBuy"); lblBuy.setText("Please select the stock you wish to buy:"); lblAccountBuy.setText("Account : "); lblCurrValueBuy.setText("Current Value : "); lblQtyBuy.setText("Quantity : "); lblTotalBuy.setText("Total Purchase : "); lblBuyInfo.setText(""); //lblBuyInfo.setVisible(true); pnlSell.setName("pnlSell"); lblSell.setText("Please select the stock you wish to sell:"); lblAccountSell.setText("Account : "); lblCurrValueSell.setText("Current Value : "); lblQtySell.setText("Quantity : "); lblTotalSell.setText("Total Transaction : "); lblSellInfo.setText(""); //lblSellInfo.setVisible(true); } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This method is being used for adding the components to the frame * and the 3 panels. * @return void */ private void addComponents() { try { add(btnMain, new XYConstraints(264, 100, 154, 20)); add(btnBuy, new XYConstraints(800, 304, 154, 20)); add(imgBanner, new XYConstraints(0, 0, 1000, 100)); add(btnSell, new XYConstraints(820, 560, 154, 20)); add(btnUpdate, new XYConstraints(423, 100, 154, 20)); add(btnLogout, new XYConstraints(582, 100, 154, 20)); add(pnlBuy, new XYConstraints(745, 125, 255, 270)); add(pnlSell, new XYConstraints(745, 400, 255, 275)); add(pnlGraph, new XYConstraints(5, 125, 735, 550)); pnlGraph.add(untitledLabel, new XYConstraints(5, 5, 324, 20)); pnlGraph.add(lblMain, new XYConstraints(5, 25, 345, 24)); pnlGraph.add(pltShares, new XYConstraints(5, 50, 380, 300)); pnlGraph.add(chShares, new XYConstraints(5, 375, 180, 21)); pnlGraph.add(btnAdd, new XYConstraints(5, 400, 75, 20)); pnlGraph.add(btnRemove, new XYConstraints(90, 400, 75, 20)); pnlGraph.add(lblInfo, new XYConstraints(420, 25, 244, 20)); pnlGraph.add(lblStockName, new XYConstraints(420, 50, 200, 20)); pnlGraph.add(lblStockCode, new XYConstraints(420, 75, 150, 20)); pnlGraph.add(lblHigh, new XYConstraints(420, 100, 150, 20)); pnlGraph.add(lblLow, new XYConstraints(420, 125, 150, 20)); pnlGraph.add(lblDividends, new XYConstraints(420, 175, 200, 20)); pnlGraph.add(lblCps, new XYConstraints(420, 200, 120, 20)); pnlGraph.add(lblTs, new XYConstraints(420, 225, 120, 20)); pnlGraph.add(lblYld, new XYConstraints(420, 250, 120, 20)); pnlGraph.add(lblPeRatio, new XYConstraints(420, 275, 140, 20)); pnlGraph.add(lblNotes, new XYConstraints(420, 325, 140, 20)); pnlGraph.add( lblCpsDefinition, new XYConstraints(420, 350, 250, 20)); pnlGraph.add(lblTcDefinition, new XYConstraints(420, 375, 250, 20)); pnlGraph.add( lblYldDefinition, new XYConstraints(420, 400, 250, 20)); pnlGraph.add( lblPeRatioDefinition, new XYConstraints(420, 425, 250, 20)); //PANEL BUY.. pnlBuy.setBackground(Color.LIGHT_GRAY); //new Color(70, 70, 102)); pnlBuy.add(lblBuy, new XYConstraints(5, 5, 240, 20)); pnlBuy.add(chBuyStocks, new XYConstraints(25, 30, 200, 21)); pnlBuy.add(lblAccountBuy, new XYConstraints(25, 75, 200, 20)); pnlBuy.add(lblCurrValueBuy, new XYConstraints(25, 100, 200, 20)); pnlBuy.add(lblQtyBuy, new XYConstraints(25, 125, 50, 20)); pnlBuy.add(txtQtyBuy, new XYConstraints(75, 125, 100, 20)); pnlBuy.add(lblTotalBuy, new XYConstraints(25, 150, 200, 20)); pnlBuy.add(btnBuy, new XYConstraints(48, 245, 154, 20)); pnlBuy.add(lblBuyInfo, new XYConstraints(25, 220, 200, 20)); //pnlBuy.add (Label1, new XYConstraints (25, 275, 200, 20)) ; //PANEL SELL.. pnlSell.setBackground(Color.LIGHT_GRAY); //new Color(70, 70, 102)); pnlSell.add(lblSell, new XYConstraints(5, 5, 240, 20)); pnlSell.add(chSellStocks, new XYConstraints(25, 30, 200, 21)); pnlSell.add(btnViewInfo, new XYConstraints(48, 75, 154, 20)); pnlSell.add(lblAccountSell, new XYConstraints(25, 100, 200, 20)); pnlSell.add(lblCurrValueSell, new XYConstraints(25, 125, 200, 20)); pnlSell.add(lblQtySell, new XYConstraints(25, 150, 50, 20)); pnlSell.add(txtQtySell, new XYConstraints(75, 150, 100, 20)); pnlSell.add(lblTotalSell, new XYConstraints(25, 175, 200, 20)); pnlSell.add(btnSell, new XYConstraints(48, 245, 154, 20)); pnlSell.add(lblSellInfo, new XYConstraints(25, 220, 200, 20)); } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This method is being used for adding listeners to the components * that are being used in this user interface. * @return void */ private void addListeners() { try { btnAdd.addActionListener(this); btnRemove.addActionListener(this); btnBuy.addActionListener(this); btnSell.addActionListener(this); btnUpdate.addActionListener(this); btnLogout.addActionListener(this); btnViewInfo.addActionListener(this); chBuyStocks.addItemListener(this); chSellStocks.addItemListener(this); addWindowListener(this); addComponentListener(this); addActionListener(this); } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This function draws information on the captions for the graph on * the remote client. * @exception amber.server.exception with any messaging errors. */ protected void redrawCaptions() throws ComponentHandlerException { pnlGraph.removeAllDrawOperations(); // Draw the label area pnlGraph.addSetColour(Color.black); pnlGraph.addFillRect(PlotLeft + 5, PlotTop + 5, 170, 180); pnlGraph.addSetColour(new Color(220, 220, 220)); //Color.LIGHT_GRAY); pnlGraph.addFillRect(PlotLeft, PlotTop, 170, 180); // Now draw in the labels int offset = PlotTop + 20; int count = 0; for (int i = 0; i < totalstocks.length; i++) { if (totalstocks[i].getVisible()) { pnlGraph.addSetColour(seriesColors[count]); pnlGraph.addFillRect(PlotLeft + 5, offset, 5, 5); pnlGraph.addSetColour(Color.black); pnlGraph.addDrawRect(PlotLeft + 5, offset, 5, 5); pnlGraph.addDrawString( totalstocks[i].toString(), PlotLeft + 15, offset + 8); offset += 15; count++; } } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { try { int index = chShares.getSelectedIndex(); if (e.getSource() == btnAdd) { //add stocks to the graph.. String stockName = chShares.getSelectedItem(); Stock_Data sd = getStock(stockName); sd.setVisible(true); currentCount = 0; for (int i = 0; i < totalstocks.length; i++) if (totalstocks[i].getVisible()) currentCount++; pltShares.setSeriesCount(currentCount); redrawCaptions(); } else if (e.getSource() == btnRemove) { //remove stocks from the graph. String stockName = chShares.getSelectedItem(); Stock_Data sd = getStock(stockName); sd.setVisible(false); currentCount = 0; for (int i = 0; i < totalstocks.length; i++) if (totalstocks[i].getVisible()) currentCount++; pltShares.setSeriesCount(currentCount); redrawCaptions(); } else if (e.getSource() == btnBuy) { //buy stocks.. if (txtQtyBuy.getText() == null || txtQtyBuy.getText().length() == 0) { throw new ValidationException("You have to specify the quantity of stocks to buy."); } Timestamp now = new Timestamp(System.currentTimeMillis()); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++ACCOUNT VALIDATION++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Stock_Data stock = getStock(chBuyStocks.getSelectedItem()); stock.setQuantity(txtQtyBuy.getText()); AccountValidator av = new AccountValidator(); boolean accValid = av.validate(user, stock); if (!accValid) { throw new ValidationException(av.getMessage()); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Send Purchase XML to TMS++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //ON HOLD FOR NOW. Details in Technical documentation. //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Send Settlement XML to TMS++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //ON HOLD FOR NOW. Details in Technical documentation. //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update account (in memory)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ int quantity = Integer.parseInt(stock.getQuantity()); double ac = user.getAccount(); double cost = round((quantity * stock.getPrice()), 2); double newac = ac - cost; user.setAccount(round(newac, 2)); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update user account (in local DB)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ boolean successful = umanager.updateUser(user); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update user stocks owned++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (successful) { StockOwnership_Data[] owned = user.getStocksOwned(); System.out.println("owned :" + (owned == null)); if (owned == null) { owned = new StockOwnership_Data[1]; owned[0] = new StockOwnership_Data( stock.getStockCode(), stock.getCompanyName(), stock.getQuantity(), String.valueOf(cost), now, String.valueOf(cost), stock.getQuantity()); user.setStocksOwned(owned); } else { int filled = owned.length; boolean noEntry = true; for (int count = 0; count < filled; count++) { StockOwnership_Data temp = owned[count]; //if the stock is already owned by the user.. if (temp .getStockCode() .equals(stock.getStockCode())) { temp.setLastPurchaseAmount( String.valueOf(cost)); temp.setLastPurchaseQty(stock.getQuantity()); int oldQty = Integer.parseInt(temp.getQuantityOwned()); int newQty = oldQty + quantity; temp.setQuantityOwned(String.valueOf(newQty)); double oldTotal = Double .valueOf(temp.getTotalCost()) .doubleValue(); double newTotal = round((oldTotal + cost), 2); temp.setTotalCost(String.valueOf(newTotal)); temp.setLastPurchasedDate(now); noEntry = false; } } //if the stock is not owned by the user. if (noEntry) { StockOwnership_Data[] owned2 = new StockOwnership_Data[owned.length + 1]; for (int j = 0; j < owned.length; j++) owned2[j] = owned[j]; owned2[owned.length] = new StockOwnership_Data( stock.getStockCode(), stock.getCompanyName(), stock.getQuantity(), String.valueOf(cost), now, String.valueOf(cost), stock.getQuantity()); user.setStocksOwned(owned2); debugStocksOwned(user); } } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update stocks owned (in local DB)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ umanager.updateStocksOwned(user); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ lblBuyInfo.setText("The stock has been bought."); updateSellPanel(); System.out.println("The stock has been bought."); System.out.println("Time : " + now.toLocaleString()); getStockTradingApplication().setUser(user); } else if (e.getSource() == btnSell) { //sell stocks.. if (txtQtySell.getText() == null || txtQtySell.getText().length() == 0) { throw new ValidationException("You have to specify the quantity of stocks to sell."); } if (chSellStocks.getItemCount() <= 0) { throw new ValidationException("You have to specify an owned stock to sell."); } Timestamp now = new Timestamp(System.currentTimeMillis()); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++ACCOUNT VALIDATION++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Stock_Data stock = getStock(chSellStocks.getSelectedItem()); stock.setQuantity(txtQtySell.getText()); QuantityValidator qv = new QuantityValidator(); boolean qtyValid = qv.validate(user, stock); if (!qtyValid) { throw new ValidationException(qv.getMessage()); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Send Purchase XML to TMS++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //ON HOLD FOR NOW. Details in Technical documentation. //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Send Settlement XML to TMS++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //ON HOLD FOR NOW. Details in Technical documentation. //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update account (in memory)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ int quantity = Integer.parseInt(stock.getQuantity()); double ac = user.getAccount(); double cost = round((quantity * stock.getPrice()), 2); double newac = ac + cost; user.setAccount(round(newac, 2)); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update user account (in local DB)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ boolean successful = umanager.updateUser(user); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update user stocks owned++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (successful) { StockOwnership_Data[] owned = user.getStocksOwned(); StockOwnership_Data tempstock = null; System.out.println("owned :" + (owned == null)); if (owned != null) { int filled = 0; boolean noEntry = true; //find stock.. for (int i = 0; i < owned.length; i++) { if ((owned[i].getStockCode()) .equals(stock.getStockCode())) { tempstock = owned[i]; filled = i; } } int oldQty = Integer.parseInt(tempstock.getQuantityOwned()); int newQty = oldQty - quantity; tempstock.setQuantityOwned(String.valueOf(newQty)); double oldTotal = Double .valueOf(tempstock.getTotalCost()) .doubleValue(); double newTotal = round((oldTotal - cost), 2); tempstock.setTotalCost(String.valueOf(newTotal)); //if no more stocks owned. if (newQty <= 0) { //delete stock ownership.. StockOwnership_Data[] newOwnerships = new StockOwnership_Data[owned.length - 1]; for (int j = 0; j < newOwnerships.length; j++) { if (j < filled) newOwnerships[j] = owned[j]; else if (j >= filled) newOwnerships[j] = owned[j + 1]; } user.setStocksOwned(newOwnerships); //if stocks owned, just update the stock ownership information. } else { owned[filled] = tempstock; user.setStocksOwned(owned); } } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++Update stocks owned (in local DB)++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ umanager.updateStocksOwned(user); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ lblSellInfo.setText("The stock has been sold."); updateBuyPanel(); updateSellPanel(); System.out.println("The stock has been sold."); System.out.println("Time : " + now.toLocaleString()); getStockTradingApplication().setUser(user); } else if (e.getSource() == btnUpdate) { //show the update frame. UpdateFrame updateFrame = new UpdateFrame(getParentApplication(), this); add( updateFrame, getStockTradingApplication().getCentredWindowXYConstraints( updateFrame.FRAMEWIDTH, updateFrame.FRAMEHEIGHT)); updateFrame.setVisible(true); this.setVisible(false); } else if (e.getSource() == btnViewInfo) { //show the stock ownership frame. OwnershipFrame ownFrame = new OwnershipFrame( getParentApplication(), chSellStocks.getSelectedItem()); add( ownFrame, getStockTradingApplication().getCentredWindowXYConstraints( ownFrame.FRAMEWIDTH, ownFrame.FRAMEHEIGHT)); ownFrame.setVisible(true); } else if (e.getSource() == btnLogout) { try { setVisible(false); shutDown(); //closeWindow(); // Shut down the program getParentApplication().shutDownClient(); getParentApplication().shutDown(); } catch (Exception ex) { getParentApplication().getLog().logException( Log.LoggingLow, "Error closing application", ex); } } } catch (Exception ex) { ex.printStackTrace(); displayMessageBox("Error", ex.getMessage()); } } /* (non-Javadoc) * @see amber.server.application.ApplicationInterface#shutDown() */ public void shutDown() { // Shut down the timer timer.stopTimer(); } /* (non-Javadoc) * @see amber.utility.TimerInterface#timeEventOccurred() */ public void timeEventOccurred() { generateStockValues(); updateGraph(); calculateRatios(); updateStockInfo(); updateBuyPanelLabels(); updateSellPanelLabels(); } /** * This method is being used for generating stock values at each timer event. * @return void */ public void generateStockValues() { // System.out.println ( "Timer event" ) ; int count = 0; for (int i = 0; i < totalstocks.length; i++) { if (lastLines != null) { double d = Math.abs( lastLines[count] + (float) ((Math.random() * STABILITY_FACTOR) - STABILITY_FACTOR / 2)); //System.out.println(d); float val = (float) round(d, 2); totalstocks[i].setPrice(val); //System.out.println("Val1 : "+val); lines[count] = val; double high = Double.valueOf(totalstocks[i].getWeekHigh()).doubleValue(); double low = Double.valueOf(totalstocks[i].getWeekLow()).doubleValue(); if (val > high) totalstocks[i].setWeekHigh(String.valueOf(val)); else if (val < low) totalstocks[i].setWeekLow(String.valueOf(val)); count++; } else { double base = Double.valueOf(totalstocks[i].getBaseValue()).doubleValue(); double d = Math.abs( base + (float) ((Math.random() * STABILITY_FACTOR) - STABILITY_FACTOR / 2)); //System.out.println(d); float val = (float) round(d, 2); totalstocks[i].setPrice(val); //System.out.println("Val 2 : "+val); double high = Double.valueOf(totalstocks[i].getWeekHigh()).doubleValue(); double low = Double.valueOf(totalstocks[i].getWeekLow()).doubleValue(); if (val > high) totalstocks[i].setWeekHigh(String.valueOf(val)); else if (val < low) totalstocks[i].setWeekLow(String.valueOf(val)); lines[count] = val; count++; } } lastLines = lines; } /** * This method is being used for adding the updated stock values to * the graph - TimePlotHandler. * @return void */ private void updateGraph() { //check for all visible stock values, and add to pltShares.. if (currentCount > 0) { float[] visibleLines = new float[currentCount]; int localCount = 0; for (int j = 0; j < totalstocks.length; j++) { if (totalstocks[j].getVisible() == true) { visibleLines[localCount] = totalstocks[j].getPrice(); System.out.println( "Debug " + totalstocks[j].toString() + " : " + totalstocks[j].getPrice() + " : " + j + " : " + currentCount + " : "); localCount++; } } try { System.out.println("adding lines to display"); System.out.println(); //pltShares.setSeriesCount(currentCount); pltShares.addSampleValues(visibleLines); } catch (Exception ex) { ex.getMessage(); } } } /** * This method is being used for refreshing the user interface after * updating user information. * @return void */ public void refresh() { try { //updates all info by retrieving from the ApplicationHandler. user = getStockTradingApplication().getUser(); address = getStockTradingApplication().getAddress(); //timer.stop(); timer.stopTimer(); currentCount = 0; Stock_Data[] interested = user.getStocksInterested(); stockNames = new String[interested.length]; chShares.removeAll(); chBuyStocks.removeAll(); chSellStocks.removeAll(); for (int e = 0; e < totalstocks.length; e++) { totalstocks[e].setVisible(false); } for (int f = 0; f < stockNames.length; f++) { stockNames[f] = interested[f].toString(); } for (int i = 0; i < stockNames.length; i++) { chShares.add(stockNames[i]); chBuyStocks.add(stockNames[i]); } StockOwnership_Data[] owned = user.getStocksOwned(); for (int g = 0; g < owned.length; g++) chSellStocks.add(owned[g].toString()); //Create a timer to create the values timer = new Timer(3000L, this); timer.start(); redrawCaptions(); } catch (Exception e) { System.out.println("Refresh exception : " + e.toString()); } } /** * This method is being used for calling calculateRatio() * for each stock. * @return void */ public void calculateRatios() { for (int i = 0; i < totalstocks.length; i++) { calculatePERatio(totalstocks[i]); calculateDividendYield(totalstocks[i]); } } /** * This method is being used for calculating the PERatio of the given * stock. * @param stock The stock for which PE ratio is to be calculated. * @return void */ public void calculatePERatio(Stock_Data stock) { double price = stock.getPrice(); double eps = Double.valueOf(stock.getEarningsPerShare()).doubleValue(); double peratio = price / eps; double result = round(peratio, 2); stock.setPeRatio((float) result); } /** * This method is being used for calculating the dividend yield for * a given stock. * @param stock The stock for which the dividend yield has to * be calculated. * @return void */ public void calculateDividendYield(Stock_Data stock) { double divpershare = Double.valueOf(stock.getDividendsPerShare()).doubleValue(); double denominator = 1 - TAX_RATE; double priceincents = stock.getPrice() * 100; double divYield = ((divpershare / denominator) / priceincents) * 100.00; double result = round(divYield, 2); stock.setDivYield((float) result); } /** * This method is being used for updating the displayed stock information * in the centre og the main frame. * @return void */ public void updateStockInfo() { try { Stock_Data stock = getStock(chShares.getSelectedItem()); lblStockName.setText( "Stock Name : " + stock.getCompanyName()); lblStockCode.setText("Stock Code : " + stock.getStockCode()); lblHigh.setText("52 Week High : " + stock.getWeekHigh()); lblLow.setText("52 Week Low : " + stock.getWeekLow()); //lblDividends.setText ("Dividends : ") ; lblCps.setText( "EPS (cents): " + Double.valueOf(stock.getEarningsPerShare()).doubleValue() * 100); lblTs.setText( "D/S (cents): " + Double.valueOf(stock.getDividendsPerShare()).doubleValue() * 100); lblYld.setText("Div YLD (%): " + stock.getDivYield() * 100); lblPeRatio.setText("P/E Ratio: " + stock.getPeRatio()); } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This method is being used for updating stock information in the buy * panel (Top right of main frame). * @return void */ public void updateBuyPanel() { try { String index = chBuyStocks.getSelectedItem(); Stock_Data stock = getStock(index); java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); lblAccountBuy.setText( "Account : $" + df.format(user.getAccount())); lblCurrValueBuy.setText("Current Value : $" + stock.getPrice()); if (txtQtyBuy.getText().length() > 0 && isNumber(txtQtyBuy.getText())) { double totalPurchase = stock.getPrice() * Integer.parseInt(txtQtyBuy.getText()); lblTotalBuy.setText( "Total Purchase : $" + round(totalPurchase, 2)); } } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This method is being used for updating only the labels in the buy * panel (top right of the main frame). * @return void */ public void updateBuyPanelLabels() { try { if (chBuyStocks.getItemCount() > 0) { String index = chBuyStocks.getSelectedItem(); Stock_Data stock = getStock(index); java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); lblAccountBuy.setText( "Account : $" + df.format(user.getAccount())); lblCurrValueBuy.setText( "Current Value : $" + stock.getPrice()); if (txtQtyBuy.getText().length() > 0 && isNumber(txtQtyBuy.getText())) { double totalPurchase = stock.getPrice() * Integer.parseInt(txtQtyBuy.getText()); lblTotalBuy.setText( "Total Purchase : $" + round(totalPurchase, 2)); } } } catch (Exception ex) { System.err.println(ex.toString()); } } /** * This method is being used for updating stock information in the sell * panel (bottom right of the main frame). * @return void */ public void updateSellPanel() { try { chSellStocks.removeAll(); StockOwnership_Data[] owned = user.getStocksOwned(); for (int g = 0; g < owned.length; g++) chSellStocks.add(owned[g].toString()); String index = ""; if (chSellStocks.getItemCount() > 0) { index = chSellStocks.getSelectedItem(); } if (index != null && index.length() > 0) { lblAccountSell.setText("Account : "); lblCurrValueSell.setText("Current Value : "); lblTotalSell.setText("Total Transaction : "); } else { Stock_Data stock = getStock(index); java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); lblAccountSell.setText( "Account : $" + df.format(user.getAccount())); lblCurrValueSell.setText( "Current Value : $" + stock.getPrice()); if (txtQtySell.getText().length() > 0 && isNumber(txtQtySell.getText())) { double totalTransaction = stock.getPrice() * Integer.parseInt(txtQtySell.getText()); lblTotalSell.setText( "Total Transaction : $" + round(totalTransaction, 2)); } } } catch (Exception ex) { System.err.println(ex.toString()); } } /** * Method: updateSellPanelLabels * This method is being used for updating only the labels in the sell * panel (bottom right of the main frame). * @return void */ public void updateSellPanelLabels() { try { StockOwnership_Data[] owned = user.getStocksOwned(); if (chSellStocks.getItemCount() > 0) { String index = chSellStocks.getSelectedItem(); Stock_Data stock = getStock(index); lblCurrValueSell.setText( "Current Value : $" + stock.getPrice()); if (txtQtySell.getText().length() > 0 && isNumber(txtQtySell.getText())) { double totalTransaction = stock.getPrice() * Integer.parseInt(txtQtySell.getText()); lblTotalSell.setText( "Total Transaction : $" + round(totalTransaction, 2)); } } java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); lblAccountSell.setText( "Account : $" + df.format(user.getAccount())); } catch (Exception ex) { System.err.println(ex.toString()); } } /* (non-Javadoc) * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent) */ public void itemStateChanged(ItemEvent ie) { try { if (ie.getSource() == chBuyStocks) { updateBuyPanelLabels(); } else if (ie.getSource() == chSellStocks) { updateSellPanelLabels(); } else if (ie.getSource() == this.chShares) { updateStockInfo(); } } catch (Exception ex) { System.out.println("Exception : " + ex.toString()); } } /** * This method is being used as a utility method for rounding a given double * value to the given number of decimal places. * @param x The original double value. * @param dec The number of decimal places to be rounded to. * @return double The rounded double value. */ public double round(double x, int dec) { double multiple = Math.pow(10, dec); return Math.round(x * multiple) / multiple; } /** * This method is being used as a utility method to get the stocks defined * by the names. * @param names The array of names of stocks which are to be retrieved. * @return Stock_Data[] The array of stocks that are returned based on the given * names. */ private Stock_Data[] getStocks(String[] names) { Stock_Data[] result = null; if (names != null) { result = new Stock_Data[names.length]; int count = 0; for (int f = 0; f < names.length; f++) { for (int g = 0; g < totalstocks.length; g++) { Stock_Data temp = (Stock_Data) totalstocks[g]; if (((String) names[f]).equals(temp.toString())) { result[count] = temp; System.out.println(temp.toString()); count++; break; } } } } return result; } /** * This method is being used as a utility method to get a specified stock * given a stock name. * @param name The name of the stock. * @return Stock_Data The stock which has the name defined by param name. */ private Stock_Data getStock(String name) { Stock_Data result = null; if (name != null) { int count = 0; for (int g = 0; g < totalstocks.length; g++) { Stock_Data temp = (Stock_Data) totalstocks[g]; if (name.equals(temp.toString())) { result = temp; count++; break; } } } return result; } /** * This method is being used as a utility method for debugging purpose. * @param user The user whose information is to be displayed. * @return void */ private void debugStocksOwned(User_Data user) { System.out.println("++++++++DEBUG STOCKS OWNED+++++++++"); StockOwnership_Data[] owned = user.getStocksOwned(); for (int c = 0; c < owned.length; c++) { StockOwnership_Data temp = owned[c]; System.out.println(); System.out.println("STOCK # " + (c + 1)); System.out.println("code " + temp.getStockCode()); System.out.println("total qty " + temp.getQuantityOwned()); System.out.println("total cost " + temp.getTotalCost()); System.out.println("date " + temp.getLastPurchasedDate()); System.out.println("qty " + temp.getLastPurchaseQty()); System.out.println("amount " + temp.getLastPurchaseAmount()); } System.out.println("+++++++++++++++++++++++++++++++++++"); } /** * This method is being used for getting the parent application. * @return StockTradingApplication The parent application. */ protected StockTradingApplication getStockTradingApplication() { return (StockTradingApplication) getParentApplication(); } /** * This utility method is being used to check if the * given string is an int or not. * @param s The string which may contain a number. * @return boolean Specifies whether validation is successful. */ private boolean isNumber(String s) { for (int j = 0; j < s.length(); j++) { if (!Character.isDigit(s.charAt(j))) { return false; } } return true; } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowOpened(amber.awt.event.ComponentWindowEvent) */ public void windowOpened(ComponentWindowEvent e) { } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowClosing(amber.awt.event.ComponentWindowEvent) */ public void windowClosing(ComponentWindowEvent e) { try { setVisible(false); timer.stopTimer(); // Shut down the program getParentApplication().shutDownClient(); getParentApplication().shutDown(); } catch (Exception ex) { getParentApplication().getLog().logException( Log.LoggingLow, "Error closing application", ex); } } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowClosed(amber.awt.event.ComponentWindowEvent) */ public void windowClosed(ComponentWindowEvent e) { try { setVisible(false); timer.stopTimer(); // Shut down the program getParentApplication().shutDownClient(); getParentApplication().shutDown(); } catch (Exception ex) { getParentApplication().getLog().logException( Log.LoggingLow, "Error closing application", ex); } } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowIconified(amber.awt.event.ComponentWindowEvent) */ public void windowIconified(ComponentWindowEvent e) { } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowDeiconified(amber.awt.event.ComponentWindowEvent) */ public void windowDeiconified(ComponentWindowEvent e) { } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowActivated(amber.awt.event.ComponentWindowEvent) */ public void windowActivated(ComponentWindowEvent e) { } /* (non-Javadoc) * @see amber.awt.event.ComponentWindowListener#windowDeactivated(amber.awt.event.ComponentWindowEvent) */ public void windowDeactivated(ComponentWindowEvent e) { } /* (non-Javadoc) * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent) */ public void componentResized(ComponentEvent e) { } /* (non-Javadoc) * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent) */ public void componentMoved(ComponentEvent e) { } /* (non-Javadoc) * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent) */ public void componentShown(ComponentEvent e) { } /* (non-Javadoc) * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent) */ public void componentHidden(ComponentEvent e) { } }