SHARE
TWEET

Untitled

a guest Nov 6th, 2018 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import javax.servlet.ServletConfig;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7.  
  8. import com.google.gson.Gson;
  9.  
  10. import java.util.*;
  11. import java.io.*;
  12. import java.sql.*;
  13.  
  14.  
  15. /**
  16.  * Servlet implementation class sensorToDB
  17.  */
  18. @WebServlet("/SensorServerDB")
  19. public class sensorServerDB extends HttpServlet {
  20.    
  21.         private static final long serialVersionUID = 1L;
  22.  
  23.         Gson gson = new Gson();
  24.        
  25.        Connection conn = null;
  26.        Statement stmt;
  27.  
  28.       public void init(ServletConfig config) throws ServletException {
  29.       // init method is run once at the start of the servlet loading
  30.       // This will load the driver and establish a connection
  31.         super.init(config);
  32.         String user = "maliki";
  33.         String password = "hansderG4";
  34.         // Note none default port used, 6306 not 3306
  35.         String url = "jdbc:mysql://mudfoot.doc.stu.mmu.ac.uk:6306/"+user;
  36.  
  37.         // Load the database driver
  38.         try {  Class.forName("com.mysql.jdbc.Driver").newInstance();
  39.             } catch (Exception e) {
  40.                 System.out.println(e);
  41.             }
  42.  
  43.             // get a connection with the user/pass
  44.         try {
  45.             conn = DriverManager.getConnection(url, user, password);
  46.               System.out.println("Sensor to DB  server is up and running\n");  
  47.               System.out.println("Upload sensor data with http://localhost:8080/MDAssignment-server/sensorServerDB?sensorData=some_sensor_data_in_json_format");
  48.               System.out.println("View last sensor reading at  http://localhost:8080/MDAssignment-server/sensorServerDB?getdata=true\n\n");      
  49.  
  50.             // System.out.println("DEBUG: Connection to database successful.");
  51.             stmt = conn.createStatement();
  52.         } catch (SQLException se) {
  53.             System.out.println(se);
  54.             System.out.println("\nDid you alter the lines to set user/password in the sensor server code?");
  55.         }
  56.       } // init()
  57.  
  58.       public void destroy() {
  59.             try { conn.close(); } catch (SQLException se) {
  60.                 System.out.println(se);
  61.             }
  62.       } // destroy()
  63.      
  64.    
  65.    
  66.     public sensorServerDB() {
  67.         super();
  68.         // TODO Auto-generated constructor stub
  69.     }
  70.  
  71.  
  72.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  73.         response.setStatus(HttpServletResponse.SC_OK);
  74.         // Declare a SensorData object to hold the incoming data
  75.         sensorData oneSensor = new sensorData("unknown", "unknown", "unknown");
  76.        
  77.         // Check to see whether the client is requesting data or sending it
  78.         String getdata = request.getParameter("getdata");
  79.  
  80.         // if no getdata parameter, client is sending data
  81.         if (getdata == null){
  82.                 // getdata is null, therefore it is receiving data
  83.                 // Extract the parameter data holding the sensordata
  84.             String sensorJsonString = request.getParameter("sensordata");
  85.            
  86.             // Problem if sensordata parameter not sent, or is invalid json
  87.             if (sensorJsonString != null) {
  88.                 // Convert the json string to an object of type SensorData
  89.                 oneSensor = gson.fromJson(sensorJsonString, sensorData.class);
  90.                 // now update the table
  91.                 updateSensorTable(oneSensor);
  92.             } // endif sensorJsonString not null
  93.         } // end if getdata is null
  94.         else {  // Retrieve and return data (JSON format)
  95.                // Code to retrieve data
  96.            String sensorName = request.getParameter("sensorname");
  97.                String resultsJson = retrieveSensorData(sensorName);
  98.             // Update sensor values and send back response
  99.             PrintWriter out = response.getWriter();
  100.             out.println(resultsJson);
  101.             out.close();
  102.  
  103.             }
  104.  
  105.     }
  106.    
  107.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  108.         // Post is same as Get, so pass on parameters and do same
  109.         doGet(request, response);
  110.     }
  111.  
  112. private void updateSensorTable(sensorData oneSensor){
  113.     try {
  114.         // Create the INSERT statement from the parameters
  115.         // set time inserted to be the current time on database server
  116.         String updateSQL =
  117.             "insert into sensorusage(userid, sensorname, sensorvalue) " +
  118.             "values('"+oneSensor.getUserid()      + "','" +
  119.                        oneSensor.getName()  + "','" +
  120.                        oneSensor.getVlaue()  + "'," +
  121.                        "now());";
  122.                        
  123.             System.out.println("DEBUG: Update: " + updateSQL);
  124.             stmt.executeUpdate(updateSQL);
  125.             System.out.println("DEBUG: Update successful ");
  126.     } catch (SQLException se) {
  127.         // Problem with update, return failure message
  128.         System.out.println(se);
  129.         System.out.println("\nDEBUG: Update error - see error trace above for help. ");
  130.         return;
  131.     }
  132.  
  133.     // all ok,  return
  134.     return;
  135. }  
  136.     private String retrieveSensorData(String sensorname) {
  137.         String selectSQL = "select * from sensorusage where sensorname='" +
  138.                     sensorname + "' order by timeinserted asc";
  139.         ResultSet rs;
  140.  
  141.         // Declare ArrayList of sensors to hold results
  142.         ArrayList<sensorData> allSensors = new ArrayList<sensorData>();
  143.  
  144.         try {          
  145.            // create a result set of selected values
  146.             rs = stmt.executeQuery(selectSQL);
  147.  
  148.             // Declare  a SensorData object to hold individual values,
  149.             // initialise to defaults
  150.             sensorData oneSensor = new sensorData("unknown", "unknown", "unknown"); // fill in statement
  151.             // iterate over the result set
  152.             while (rs.next()) {
  153.                 oneSensor.setName(rs.getString("sensorname"));
  154.                 oneSensor.setValue(rs.getString("sensorvalue"));
  155.                 oneSensor.setUserid(rs.getString("userid"));
  156.                 oneSensor.setName(rs.getString("sensorname"));
  157.                 //oneSensor.setSensordate(rs.getString("timeinserted"));
  158.                 // add this sensor to ArrayList of Sensors
  159.                 allSensors.add(oneSensor);
  160.                 // debug print this sensor to console
  161.                 System.out.println(oneSensor.toString());
  162.             }
  163.             } catch (SQLException ex) {
  164.                     System.out.println("Error in SQL " + ex.getMessage());
  165.             }
  166.             // Convert sensor list to json array and send back to user
  167.             String allSensorsJson = gson.toJson(allSensors);
  168.    
  169.             // return this String from method
  170.             return allSensorsJson;
  171.    
  172.     }
  173.    
  174. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top