Advertisement
Guest User

Untitled

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