⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 brokermodeldbimpl.java

📁 this is a trade sale system realized by java. It can run some easy functions and has a good design p
💻 JAVA
字号:
package trader.db;

import java.util.*;
import java.sql.*;
import trader.*;

public class BrokerModelDbImpl implements BrokerModel {
  ArrayList changeListeners = new ArrayList(10);
  Connection theConnection;
  
  public BrokerModelDbImpl() throws Exception {
    this("localhost");
  }

  public BrokerModelDbImpl(String hostName) throws Exception {
    String  database = "sample";     // --action StockMarket
    String url;
    try {
      //** 1 Register a JDBC driver
      //**   The name of the pointbase driver class is
      //**   "com.pointbase.jdbc.jdbcUniversalDriver"
      Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
      //** 2 Construct the url string for JDBC access.
      //**   To be flexible use the local variables hostName
      //**   and database to construct the url string 
      url = "jdbc:pointbase://" + hostName +
        "/" + database;
      //** 3 Assign to theConnection attribute a connection
      //**   object obtained by invoking the getConnection
      //**   method on the DriverManager class
      theConnection = DriverManager.getConnection
        (url, "public", "public");
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  /** ---------------------------------------------------------
   * This is a helper method used by many methods.
   * It returns a Connection object. 
   * In a single threaded environment you can return a single
   * connection object stored in the attribute theConnection.
   * In a multi-threaded environment each thread will require
   * its own connection. A future subclass of this class can
   * override this method and obtain the connection object 
   * from a connection pool.
   */
  protected Connection obtainConnection() throws SQLException{
    // return the theConnection attribute
    return theConnection;
  }

  /** ---------------------------------------------------------
   * This is a helper method used by many methods
   * It returns true if the ssn (ie customer id) is found in 
   * the Customer table
   */
  protected boolean ssnExists(String ssn) {
    try {
      Connection con = obtainConnection();
      Statement stmt = con.createStatement();
      ResultSet result = stmt.executeQuery
        ("SELECT ssn FROM Customer WHERE ssn="+ "'" +ssn+ "'");
      return result.next();
    } catch (SQLException e) {
      System.err.println ("in ssnExists, query for " + ssn + " failed");
      e.printStackTrace();
      return false;
    }
  }

// Broker model state change listener registration methods
  /**-----------------------------------------------------------
   * Adds requester to the list of objects to be notified when an
   * object(Customer, Portfolio or Stock) in the broker model 
   * alters state   
   */
  public void addChangeListener(BrokerView bv)
    throws BrokerException {
    //** 1 add bv to changeListeners using the add method   
    changeListeners.add(bv);
  }
  

  /**-----------------------------------------------------------
   * This method notifies all registered BrokerView listeners
   * that a customer object has changed.
   */
  private void fireModelChangeEvent(Customer cust) {
    BrokerView v;
    for (int i=0; i<changeListeners.size(); i++) {
      try {    
        System.out.println("Model:fireModelChangeEvent loop " +i);
        v = (BrokerView) changeListeners.get(i);
        v.handleCustomerChange(cust);
      } catch(Exception e) {
        System.out.println(e.toString());
      }
    }
  }

// Iteration 1 Customer segment broker model methods
// Customer segment state change methods
  /**----------------------------------------------------------
   * Adds the Customer to the broker model 
   */ 
  public void addCustomer(Customer cust) 
    throws BrokerException {
    try {
      String id = null;
      String name = null;
      String addr = null;
      Connection con;
      Statement stmt;
      int rowCount;
      String request;
      //** 1 Assign id with id from cust object
      id = cust.getId();
      //** 2 Assign name with name from cust object
      name = cust.getName();
      //** 3 Assign addr with addr from cust object
      addr = cust.getAddr(); 
      //Q? what is the purpose of the following 3 code lines?
      if (ssnExists(id)) {
        throw new BrokerException("Duplicate id");
      }
      //** 4 Assign con by invoking the obtainConnection()
      //**   for example see similar step in ssnExists method
      con = obtainConnection();
      //** 5 Assign stmt by invoking createStatement on con
      //**   for example see similar step in ssnExists method
      stmt = con.createStatement();
      // The following creates the required INSERT SQL string
      request = 
        "INSERT INTO Customer (ssn, cust_name, address) VALUES ("
        + "'" + id + "'" + ","
        + "'" + name + "'" + ","
        + "'" + addr + "'" + ")";
      //** 6 Assign rowCount with the value returned by invoking 
      //**   executeUpdate(request) method on the stmt object
      rowCount = stmt.executeUpdate(request);
      //** 7 Invoke the fireModelChangeEvent with cust as param.
      //**   Q? why is this step necessary?
      fireModelChangeEvent(cust);
    } catch (Exception e) {
      e.printStackTrace();
      throw new BrokerException("BrokerDbImpl.addCustomer\n" +e);
    }
  }

  /**-------------------------------------------------------------
   * deletes the customer from the broker model
   */
  public void deleteCustomer(Customer cust)
    throws BrokerException{
    try {
      String id = null;
      Connection con;
      Statement stmt;
      int rowCount;
      String request;
      //** 1 Assign id with id from cust object
      id = cust.getId();
      //Q? What is the purpose of the following 4 code lines?
      if (!ssnExists(id)) {
        throw new BrokerException("Record for " + id +
          " not found");
      }
      //** 2 Assign con by invoking the obtainConnection()
      //**   for example see similar step in ssnExists method
      con = obtainConnection();
      //** 3 Assign stmt by invoking createStatement on con
      //**   for example see similar step in ssnExists method
      stmt = con.createStatement();
      // The following creates the required DELETE SQL string
      // to delete rows from the Shares table
      request = 
        "DELETE FROM Shares WHERE ssn=" + "'" + id + "'";
      //** 4 Assign rowCount with the value returned by invoking 
      //**   executeUpdate(request) method on the stmt object
      rowCount = stmt.executeUpdate(request);

      // The following creates the required DELETE SQL string
      // to delete the customer from the Customers table
      request = 
        "DELETE FROM Customer WHERE ssn=" + "'" + id + "'";
      //** 5 Assign rowCount with the value returned by invoking 
      //**   executeUpdate(request) method on the stmt object
      rowCount = stmt.executeUpdate(request);
      //** 6 Using the setName method set the string 
      //**   "- customer deleted -" to the name field of the
      //**   cust object . 
      cust.setName("- customer deleted -");
      //** 7 Invoke the fireModelChangeEvent with cust as param.
      fireModelChangeEvent(cust);
    } catch (Exception e) {
      e.printStackTrace();
      throw new BrokerException
        ("BrokerDbImpl.deleteCustomer\n" +e);
    }
  }


  /**-------------------------------------------------------------
   * Updates the customer in the broker model
   */
  public void updateCustomer(Customer cust)
    throws BrokerException {
    try {
      String id = null;
      String name = null;
      String addr = null;
      Connection con;
      Statement stmt;
      String request;
      int rowCount;
      //** 1 Assign id with id from cust object
      id = cust.getId();
      //** 2 Assign name with name from cust object
      name = cust.getName();
      //** 3 Assign addr with addr from cust object
      addr = cust.getAddr(); 
      //** Q? What is the purpose of the following 4 code lines
      if (!ssnExists(id)) {
        throw new BrokerException("Record for " + id +
          " not found");
      }
      //** 4 Assign con by invoking the obtainConnection()
      //**   for example see similar step in ssnExists method
      con = obtainConnection();
      //** 5 Assign stmt by invoking createStatement on con
      //**   for example see similar step in ssnExists method
      stmt = con.createStatement();
      // The following creates the required INSERT SQL string
      request = 
        "UPDATE Customer SET "
        + " cust_name=" + "'" + name + "'" + ","
        + " address=" +"'" + addr + "'"
        + " WHERE ssn=" +"'" + id + "'";
      //** 6 Assign rowCount with the value returned by invoking 
      //**   executeUpdate(request) method on the stmt object
      rowCount = stmt.executeUpdate(request);
      //** 7 Invoke the fireModelChangeEvent with cust as param.
      //**   Q? why is this step necessary?
      fireModelChangeEvent(cust);
    } catch (Exception e) {
      e.printStackTrace();
      throw new BrokerException
        ("BrokerDbImpl.updateCustomer\n" +e);
    }
  }

  
// Customer segment state query methods
  /**-------------------------------------------------------------
   * Given an id, returns the Customer from the model
   */
  public Customer getCustomer(String id)
    throws BrokerException {
    try {
      String name;
      String addr;
      Connection con;
      Statement stmt;
      ResultSet result = null;
      String request;
      Customer cr = null;
      //** 1 Assign con by invoking the obtainConnection()
      //**   for example see similar step in ssnExists method
      con = obtainConnection();
      //** 2 Assign stmt by invoking createStatement on con
      //**   for example see similar step in ssnExists method
      stmt = con.createStatement();
      // The following creates the required SELECT SQL string
      request = 
        "SELECT cust_name, address FROM Customer "
         + " WHERE ssn=" + "'" + id + "'";
      //** 3 Assign result with the value returned by invoking 
      //**   executeQuery(request) method on the stmt object
      result = stmt.executeQuery(request);

      // The following statement checks if query successful
      if (result.next()) {
        //** 4 Assign name with the value returned by invoking 
        //**   getString(1) method on the result object
        name = result.getString(1);
        //** 5 Assign addr with the value returned by invoking 
        //**   getString(2) method on the result object
        addr = result.getString(2);
        //** 6 Create a Customer object using (id, name, addr) 
        //**   and assign this object to cr
        cr = new Customer(id, name, addr);
      }
      else {
        // if query failed 
        throw new BrokerException("Record for " + id +
          " not found");
      }        
      // return cr
      return cr;
    } catch (SQLException e) {
      e.printStackTrace();
      throw new BrokerException("BrokerDbImpl.getCustomer\n" +e);
    }
  }
  

  /**-------------------------------------------------------------
   * Returns all customers in the broker model
   */
  public Customer[] getAllCustomers()
    throws BrokerException{
    String id;
    String name;
    String addr;
    Connection con;
    Statement stmt;
    ResultSet result = null;
    String request;
    Customer cr = null;
    Customer[] all;
    Customer[] temp = new Customer[1];
    ArrayList aList = new ArrayList(1);
    try {
      //** 1 assign con by invoking the obtainConnection()
      //**   for example see similar step in ssnExists method
      con = obtainConnection();
      //** 2 assign stmt by invoking createStatement on con
      //**   for example see similar step in ssnExists method
      stmt = con.createStatement();
      //** the following creates the required SELECT SQL string
      request = "SELECT * FROM CUSTOMER";
      //** 3 assign result with the value returned by invoking 
      //**   executeQuery(request) method on the stmt object
      result = stmt.executeQuery(request);
      while (result.next()) {
        //A* 4 assign id with the value returned by invoking 
        //**   getString(1) method on the result object
        id = result.getString(1);
        //A* 5 assign name with the value returned by invoking 
        //**   getString(2) method on the result object
        name = result.getString(2);
        //A* 6 assign addr with the value returned by invoking 
        //**   getString(3) method on the result object
        addr = result.getString(3);
        //A* 7 create a Customer object using (id, name, addr) 
        //**   and assign this object to cr
        cr = new Customer(id, name, addr);
        //A* 8 use the ArrayList add method to add cr to aList
        aList.add(cr);
      }
      if (aList.size() > 0) {
        //Q? for an explanation of the following line of code
        //** lookup javadoc for 
        all = (Customer[]) aList.toArray(temp);
      }
      else {
        all = null;
      }
      return all;
    } catch (SQLException e) {
      all = null;
      e.printStackTrace();
      throw new BrokerException
        ("BrokerDbImpl.getAllCustomers\n" + e);
    }
  }
  
  public void test() {
    try {  
      // getCustomer
      Customer cust = this.getCustomer("111-11-1111");
      System.out.println("testing getCustomer:\n" +
        "ssn 111-11-1111 " + cust);

      // updateCustomer - change addr for "111-11-1111"
      System.out.println("testing updateCustomer ");
      String addrOrig = cust.getAddr();
      cust.setAddr("++++++++++++++");
      this.updateCustomer(cust);
      cust = this.getCustomer("111-11-1111");
      System.out.println("after update:\nssn 111-11-1111 " 
        + cust);

      // updateCustomer - restore addr for "111-11-1111"
      System.out.println("restoring to before updateCustomer ");
      cust.setAddr(addrOrig);
      this.updateCustomer(cust);
      cust = this.getCustomer("111-11-1111");
      System.out.println("back to original:\nssn 111-11-1111 " 
        + cust);

      // getAllCustomers
      Customer[] custs = this.getAllCustomers();
      for (int i=0; i<custs.length; i++) {
        System.out.println("custs[" + i + "] " + custs[i].getName());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public static void main(String args[]) {
    String hostName = null;
    if (args.length < 1) {
       hostName = "localhost";
    }
    else {
      hostName = args[0];
    }
    try {
      BrokerModelDbImpl brokerDb=new BrokerModelDbImpl(hostName);
      brokerDb.test();
    } catch(Exception e) {
      System.out.println(e.toString());
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -