SHARE
TWEET

Untitled

a guest Dec 11th, 2019 1,089 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package solutions;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.time.LocalDateTime;
  11. import java.time.format.DateTimeFormatter;
  12. import java.util.ArrayList;
  13.  
  14. import javax.servlet.ServletConfig;
  15. import javax.servlet.ServletException;
  16. import javax.servlet.annotation.WebServlet;
  17. import javax.servlet.http.HttpServlet;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20.  
  21. import com.google.gson.Gson;
  22.  
  23. @WebServlet("/ValidateTag")
  24.  
  25. public class ValidateTag extends HttpServlet {
  26.    
  27.     // Collects or returns data for sensorname, sensorvalue parameters
  28.     private static final long serialVersionUID = 1L;
  29.    
  30.     // Local variables holding last values stored for each parameter
  31.     SensorData lastSensor = new SensorData("unknown", "unknown");
  32.     Gson gson = new Gson();
  33.     Connection conn = null;
  34.     Statement stmt;
  35.        
  36.     public ValidateTag() {
  37.         super();
  38.     }
  39.       public void init(ServletConfig config) throws ServletException {
  40.           super.init(config);
  41.           System.out.println("Sensor server is up and running\n"); 
  42.           System.out.println("Upload sensor data with http://localhost:8080/PhidgetServer2019/ValidateTag?sensordata=someSensorJson");
  43.           System.out.println("View last sensor reading at  http://localhost:8080/PhidgetServer2019/ValidateTag?getdata=true \n\n");      
  44.       }
  45.      
  46.       private void getConnection() {
  47.           // This will load the driver and establish a connection
  48.             String user = "jadczakd";
  49.             String password = "labenTra8";
  50.  
  51.             // Note none default port used, 6306 not 3306
  52.             String url = "jdbc:mysql://mudfoot.doc.stu.mmu.ac.uk:6306/"+user;
  53.  
  54.             // Load the database driver
  55.             try {  Class.forName("com.mysql.jdbc.Driver").newInstance();
  56.                 } catch (Exception e) {
  57.                     System.out.println(e);
  58.                 }
  59.                 // get a connection with the user/pass
  60.                 try {
  61.                     conn = DriverManager.getConnection(url, user, password);
  62.                     // System.out.println("DEBUG: Connection to database successful.");
  63.                     stmt = conn.createStatement();
  64.                 } catch (SQLException se) {
  65.                     System.out.println(se);
  66.                     System.out.println("\nDid you alter the lines to set user/password in the sensor server code?");
  67.                 }
  68.       }
  69.  
  70.       private void closeConnection() {
  71.             // get a connection with the user/pass
  72.             try {
  73.                 conn.close();
  74.             } catch (Exception e) {
  75.                 System.out.println(e);
  76.             }
  77.      
  78.       }
  79.      
  80.       public void destroy() {
  81.             try { // conn.close();  // should have no need to close connection
  82.                   // add anything extra to do when servlet closes
  83.             } catch (Exception e) {
  84.                 System.out.println(e);
  85.             }
  86.       } // destroy()
  87.  
  88.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  89.         response.setStatus(HttpServletResponse.SC_OK);
  90.         // Declare a SensorData object to hold the incoming data
  91.         SensorData oneSensor = new SensorData("unknown", "unknown");
  92.        
  93.         // Check to see whether the client is requesting data or sending it
  94.         String getdata = request.getParameter("getdata");
  95.  
  96.         // if no getdata parameter, client is sending data
  97.         if (getdata == null){
  98.                 // getdata is null, therefore it is receiving data
  99.                 // Extract the parameter data holding the sensordata
  100.             String sensorJsonString = request.getParameter("sensordata");
  101.            
  102.             // Problem if sensordata parameter not sent, or is invalid json
  103.             if (sensorJsonString != null) {
  104.                 // Convert the json string to an object of type SensorData
  105.                 oneSensor = gson.fromJson(sensorJsonString, SensorData.class);
  106.                 // now update the table
  107.                        
  108.             } // endif sensorJsonString not null
  109.         } // end if getdata is null
  110.         else {  // Retrieve and return data (JSON format)
  111.                // Code to retrieve data
  112.             String tagId = request.getParameter("tagid");
  113.             String resultsJson = retrieveSensorData(tagId);
  114.                 // Update sensor values and send back response
  115.             PrintWriter out = response.getWriter();
  116.             out.println(resultsJson);
  117.             System.out.println("validated card, sending back json"+resultsJson.toString());
  118.             out.close();
  119.            
  120.             //sendJSONString(response);
  121.  
  122.             }
  123.  
  124.     }
  125.  
  126.     /*private String updateSensorValues(SensorData oneSensor){
  127.         // all ok, update last known values and return
  128.         lastSensor = oneSensor;
  129.         System.out.println("DEBUG : Last sensor tagid " + oneSensor.getTagid() + ", readerid "+oneSensor.getReaderid() +", roomid "+oneSensor.getReaderid());
  130.         return "Sensor value updated.";
  131.     }*/
  132.    
  133.     /*private void sendJSONString(HttpServletResponse response) throws IOException{
  134.           response.setContentType("application/json");  
  135.           String json = gson.toJson(lastSensor);
  136.          
  137.           PrintWriter out = response.getWriter();
  138.           System.out.println("DEBUG: sensorServer JSON: "+lastSensor.toString());
  139.  
  140.           out.println(json);
  141.           out.close();
  142.     }*/
  143.    
  144.     private String retrieveSensorData(String tagid ) {
  145.         String selectSQL = "select * from validtags where tagid='" +
  146.                     tagid + "'";
  147.         ResultSet rs;
  148.  
  149.         // Declare ArrayList of sensors to hold results
  150.         ArrayList<SensorData> allSensors = new ArrayList<SensorData>();
  151.  
  152.         try {          
  153.            // create a result set of selected values
  154.             getConnection();
  155.             rs = stmt.executeQuery(selectSQL);
  156.            
  157.             // iterate over the result set
  158.             while (rs.next()) {
  159.                 // Declare  a SensorData object to hold individual values,
  160.                 // initialise to defaults
  161.                  // fill in statement
  162.                 SensorData oneSensor = new SensorData("unknown", "unknown","unknown");
  163.                 oneSensor.setTagid(rs.getString("tagid"));
  164.                 oneSensor.setReaderid(rs.getString("readerid"));
  165.                 oneSensor.setDoorid(rs.getString("roomid"));
  166.                 oneSensor.valid = true;
  167.                 // add this sensor to ArrayList of Sensors
  168.                 allSensors.add(oneSensor);
  169.                 // debug print this sensor to console
  170.                
  171.             }
  172.            
  173.             } catch (SQLException ex) {
  174.                     System.out.println("Error in SQL " + ex.getMessage());
  175.             }
  176.             // close connection to databse
  177.             closeConnection();
  178.            
  179.             // Convert sensor list to json array and send back to user
  180.             String allSensorsJson = gson.toJson(allSensors);
  181.            
  182.             // return this String from method
  183.             return allSensorsJson;
  184.    
  185.     }
  186.    
  187.     /**
  188.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  189.      */
  190.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  191.         doGet(request, response);
  192.     }
  193.  
  194. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top