Advertisement
Guest User

Untitled

a guest
Mar 14th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.75 KB | None | 0 0
  1. import java.sql.*;
  2. // You should use this class so that you can represent SQL points as
  3. // Java PGpoint objects.
  4. import org.postgresql.geometric.PGpoint;
  5.  
  6. // If you are looking for Java data structures, these are highly useful.
  7. // However, you can write the solution without them.  And remember
  8. // that part of your mark is for doing as much in SQL (not Java) as you can.
  9. import java.util.ArrayList;
  10. import java.util.Collections;
  11. import java.util.HashMap;
  12. import java.util.HashSet;
  13. import java.util.Set;
  14. import java.sql.Timestamp;
  15.  
  16. public class Assignment2 {
  17.  
  18.    // A connection to the database
  19.    Connection connection;
  20.  
  21.    Assignment2() throws SQLException {
  22.       try {
  23.          Class.forName("org.postgresql.Driver");
  24.       } catch (ClassNotFoundException e) {
  25.          e.printStackTrace();
  26.       }
  27.    }
  28.  
  29.   /**
  30.    * Connects and sets the search path.
  31.    *
  32.    * Establishes a connection to be used for this session, assigning it to
  33.    * the instance variable 'connection'.  In addition, sets the search
  34.    * path to uber.
  35.    *
  36.    * @param  url       the url for the database
  37.    * @param  username  the username to connect to the database
  38.    * @param  password  the password to connect to the database
  39.    * @return           true if connecting is successful, false otherwise
  40.    */
  41.    public boolean connectDB(String URL, String username, String password) {
  42.       // Implement this method!
  43.       try{
  44.         connection = DriverManager.getConnection(URL, username, password);
  45.       }
  46.       catch (SQLException ex) {
  47.       //return false;
  48.       }
  49.     if (connection != null ){
  50.         String queryString = "SET search_path TO uber";
  51.         PreparedStatement pStatement = connection.prepareStatement(queryString);
  52.         pStatement.execute();
  53.         return true;
  54.       }
  55.         return false;  
  56.       }
  57.  
  58.  
  59.   /**
  60.    * Closes the database connection.
  61.    *
  62.    * @return true if the closing was successful, false otherwise
  63.    */
  64.    public boolean disconnectDB() {
  65.       // Implement this method!
  66.       try {
  67.           connection.close();
  68.       }
  69.       catch (SQLException ex) {
  70.           return false;
  71.       }
  72.       return true;
  73.    }
  74.    
  75.    /* ======================= Driver-related methods ======================= */
  76.  
  77.    /**
  78.     * Records the fact that a driver has declared that he or she is available
  79.     * to pick up a client.  
  80.     *
  81.     * Does so by inserting a row into the Available table.
  82.     *
  83.     * @param  driverID  id of the driver
  84.     * @param  when      the date and time when the driver became available
  85.     * @param  location  the coordinates of the driver at the time when
  86.     *                   the driver became available
  87.     * @return           true if the insertion was successful, false otherwise.
  88.     */
  89.    public boolean available(int driverID, Timestamp when, PGpoint location) {
  90.       // Implement this method!
  91.      
  92.       String UpdateString = "INSERT INTO Available Values " +
  93.                     "(?, ?, ?)";
  94.       PreparedStatement ps = connection.prepareStatement(UpdateString);
  95.       ps.setInt(1, driverID);
  96.       ps.setTimestamp(2, when);
  97.       ps.setObject(3, location);
  98.       if (ps.executeUpdate()==1) {
  99.         return true;}
  100.       else {
  101.       return false;}
  102.     }
  103.  
  104.    /**
  105.     * Records the fact that a driver has picked up a client.
  106.     *
  107.     * If the driver was dispatched to pick up the client and the corresponding
  108.     * pick-up has not been recorded, records it by adding a row to the
  109.     * Pickup table, and returns true.  Otherwise, returns false.
  110.     *
  111.     * @param  driverID  id of the driver
  112.     * @param  clientID  id of the client
  113.     * @param  when      the date and time when the pick-up occurred
  114.     * @return           true if the operation was successful, false otherwise
  115.     */
  116.     // Request, dispatch, pickup
  117.    public boolean picked_up(int driverID, int clientID, Timestamp when) {
  118.       // Implement this method!
  119.       // Step 1: Check if driverID clientID matches the joined table request and dispatch and finds request ID
  120.       String QueryString =  "SELECT request_id, p.timestamp " +
  121.                             "FROM Request r JOIN Dispatch d " +
  122.                             "ON r.request_id=d.request_id "+
  123.                             "LEFT JOIN Pickup p "+
  124.                             "ON d.request_id = p.request_id "+
  125.                             "WHERE r.client_id=? AND d.driver_id=? "+
  126.                             "ORDER BY d.timestamp DESC";// We're assuming they get picked up by the most recent request that has not been picked up for client, in case there is a null value for when
  127.       PreparedStatement ps=connection.prepareStatement(QueryString);
  128.       ps.setInt(1,clientID);
  129.       ps.setInt(2,driverID);
  130.       ResultSet rs=ps.executeQuery();
  131.       while(rs.next()) {
  132.           //If there are elements in the results, it will return a non-0 value.
  133.           // Step 2: If driver ID, clientID matches the joined table, check if it exists in pickup table, if not, insert it.
  134.           //  if the time is different, from it, it has been called a different time, defer it.
  135.           int r_id=rs.getInt("request_id");
  136.           Timestamp time=rs.getTimestamp("timestamp");
  137.           if (time == null) {
  138.               //Assumption: If dispatch is missed, it is the one we're looking for
  139.               String UpdateString = "INSERT INTO Pickup Values " +
  140.                             " ( ?, ?)";
  141.               ps = connection.prepareStatement(UpdateString);
  142.               ps.setInt(1,r_id);
  143.               ps.setTimestamp(2, when);
  144.               return true;
  145.            }
  146.            else if(time == when) {
  147.                // If timestamps matches input, then it is already in the pickup table, so don't do anything
  148.                return false;
  149.            }
  150.       }
  151.       //If timestamp value is different from input, continue to next value.
  152.  
  153.       return false;
  154.    }
  155.    
  156.    /* ===================== Dispatcher-related methods ===================== */
  157.  
  158.    /**
  159.     * Dispatches drivers to the clients who've requested rides in the area
  160.     * bounded by NW and SE.
  161.     *
  162.     * For all clients who have requested rides in this area (i.e., whose
  163.     * request has a source location in this area), dispatches drivers to them
  164.     * one at a time, from the client with the highest total billings down
  165.     * to the client with the lowest total billings, or until there are no
  166.     * more drivers available.
  167.     *
  168.     * Only drivers who (a) have declared that they are available and have
  169.     * not since then been dispatched, and (b) whose location is in the area
  170.     * bounded by NW and SE, are dispatched.  If there are several to choose
  171.     * from, the one closest to the client's source location is chosen.
  172.     * In the case of ties,  any one of the tied drivers may be dispatched.
  173.     *
  174.     * Area boundaries are inclusive.  For example, the point (4.0, 10.0)
  175.     * is considered within the area defined by
  176.     *         NW = (1.0, 10.0) and SE = (25.0, 2.0)
  177.     * even though it is right at the upper boundary of the area.
  178.     *
  179.     * Dispatching a driver is accomplished by adding a row to the
  180.     * Dispatch table.  All dispatching that results from a call to this
  181.     * method is recorded to have happened at the same time, which is
  182.     * passed through parameter 'when'.
  183.  
  184.     * @param  NW    x, y coordinates in the northwest corner of this area.
  185.     * @param  SE    x, y coordinates in the southeast corner of this area.
  186.     * @param  when  the date and time when the dispatching occurred
  187.     */
  188.    public void dispatch(PGpoint NW, PGpoint SE, Timestamp when) {
  189.       // Implement this method!
  190.       // Matching clients with drivers, and the result is to match all of them until there is no more drivers in the area.
  191.       // Step 1: Find all the available (open request) client in the area and order by total billing, find all avaiable driver in the area.
  192.       String Querystring = "((SELECT client_id, location"+ // Sort all clients by their patronage
  193.                            "FROM Request r LEFT JOIN Billed b ON r.request_id=b.request_id " +
  194.                            "GROUP BY client_id " +
  195.                            "ORDER BY sum(amount) DESC NULLS LAST) " +
  196.                            "JOIN " +
  197.                            "(SELECT client_id " +// Find all open request for clients within the area
  198.                            "FROM Request r JOIN Place p "+
  199.                            "ON r.source = p.location " +
  200.                            // Definition: open request - request that has not been fulfilled yet(not billed)
  201.                            "WHERE r.request_id NOT IN  ( " +
  202.                                "SELECT request_id " +
  203.                                "FROM Billed b ) " +
  204.                            "AND location[0]>= ? AND location[0]<= ? " +//within the specified area
  205.                            "AND location[1]<= ? AND location[1]>= ? )) " +
  206.                            "AS Availble_client"
  207.                            ;
  208.  
  209.       PreparedStatement ps = connection.prepareStatement(Querystring);
  210.       ps.setDouble(1,NW.x);
  211.       ps.setDouble(2,SE.x);
  212.       ps.setDouble(3,NW.y);
  213.       ps.setDouble(4,SE.y);
  214.       ResultSet c_ID=ps.executeQuery();
  215.          // Actually available - the available timestamp > dispatched timestamp
  216.       Querystring = "(SELECT x.driver_id, x.location, x.datetime " + //Finds most recent available time for all drivers
  217.                             "FROM (" +
  218.                                 "SELECT driver_id , max(datetime) " +
  219.                                 "FROM Available a" +
  220.                                 "GROUP BY driver_id " +
  221.                                 ") "+
  222.                                 "AS x " +
  223.                             "WHERE x.datetime > ( " +// Finds the dispatch
  224.                                 "SELECT max(d.datetime) " +
  225.                                 "FROM Dispatch d " +
  226.                                 "GROUP BY d.driver_id " +
  227.                                 "WHERE x.driver_id = d.driver_id " +
  228.                                 " )" +
  229.                             "AND x.location[0]>= ? AND x.location[0]<= ? " +// with in the area
  230.                             "AND x.location[1]<= ? AND x.location[1]>= ? " +
  231.                             ")" +
  232.                             "AS Available_driver";
  233.       ps = connection.prepareStatement(Querystring);
  234.       ps.setDouble(1,NW.x);
  235.       ps.setDouble(2,SE.x);
  236.       ps.setDouble(3,NW.y);
  237.       ps.setDouble(4,SE.y);
  238.       ResultSet d_ID=ps.executeQuery();
  239.    }
  240.  
  241.    public static void main(String[] args) {
  242.       // You can put testing code in here. It will not affect our autotester.
  243.     Assignment2
  244.     A2 = new Assignment2();
  245.     String url = "jdbc:postgresql://localhost:5432/csc343h-c6fanjia";
  246.     A2.connectDB(url, "c6fanjia","");
  247.     System.out.println("Boo!");
  248.    }
  249.  
  250. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement