Advertisement
Guest User

Untitled

a guest
Nov 27th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.35 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 = "khaname";
  32. String password = "Uclefask3";
  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/MADServer/SensorServerDB?sensordata=some_sensor_data_in_json_format");
  47. System.out.println("View last sensor reading at http://localhost:8080/MADServer/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. public void destroy() {
  58. try { conn.close(); } catch (SQLException se) {
  59. System.out.println(se);
  60. }
  61. } // destroy()
  62.  
  63.  
  64.  
  65. public SensorServerDB() {
  66. super();
  67. // TODO Auto-generated constructor stub
  68. }
  69.  
  70.  
  71. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  72. response.setStatus(HttpServletResponse.SC_OK);
  73. // Declare a SensorData object to hold the incoming data
  74. SensorData oneSensor = new SensorData("unknown", "unknown");
  75.  
  76. // Check to see whether the client is requesting data or sending it
  77. String getdata = request.getParameter("getdata");
  78.  
  79. // if no getdata parameter, client is sending data
  80. if (getdata == null){
  81. // getdata is null, therefore it is receiving data
  82. // Extract the parameter data holding the sensordata
  83. String sensorJsonString = request.getParameter("sensordata");
  84.  
  85. // Problem if sensordata parameter not sent, or is invalid json
  86. if (sensorJsonString != null) {
  87. // Convert the json string to an object of type SensorData
  88. oneSensor = gson.fromJson(sensorJsonString, SensorData.class);
  89. // now update the table
  90. updateSensorTable(oneSensor);
  91. } // endif sensorJsonString not null
  92. } // end if getdata is null
  93. else { // Retrieve and return data (JSON format)
  94. // Code to retrieve data
  95. String tagId = request.getParameter("tagid");
  96. String resultsJson = retrieveSensorData(tagId);
  97. // Update sensor values and send back response
  98. PrintWriter out = response.getWriter();
  99. out.println(resultsJson);
  100. out.close();
  101.  
  102. }
  103.  
  104. }
  105.  
  106. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  107. // Post is same as Get, so pass on parameters and do same
  108. doGet(request, response);
  109. }
  110.  
  111. private void updateSensorTable(SensorData oneSensor){
  112. try {
  113. // Create the INSERT statement from the parameters
  114. // set time inserted to be the current time on database server
  115. String updateSQL =
  116. "insert into sensorusage(tagid, value, userid, timeinserted) " +
  117. "values('"+oneSensor.getTagid() + "','" +
  118. oneSensor.getValue() + "','" +
  119. oneSensor.getUserid() + "'," +
  120. "now());";
  121. // String updateSQL =
  122. // "insert into sensorusage " +
  123. // "values('"+oneSensor.getTagid() + "','" +
  124. // oneSensor.getValue() + "'," +
  125. // oneSensor.getUserid() + "','" +
  126. // "now());";
  127.  
  128. System.out.println("DEBUG: Update: " + updateSQL);
  129. stmt.executeUpdate(updateSQL);
  130. System.out.println("DEBUG: Update successful ");
  131. } catch (SQLException se) {
  132. // Problem with update, return failure message
  133. System.out.println(se);
  134. System.out.println("\nDEBUG: Update error - see error trace above for help. ");
  135. return;
  136. }
  137.  
  138. // all ok, return
  139. return;
  140. }
  141. private String retrieveSensorData(String tagid) {
  142. String selectSQL = "select * from sensorusage where tagid='" + tagid + "' order by timeinserted asc";
  143. ResultSet rs;
  144.  
  145. // Declare ArrayList of sensors to hold results
  146. ArrayList<SensorData> allSensors = new ArrayList<SensorData>();
  147.  
  148. try {
  149. // create a result set of selected values
  150. rs = stmt.executeQuery(selectSQL);
  151.  
  152. // Declare a SensorData object to hold individual values,
  153. // initialise to defaults
  154. SensorData oneSensor = new SensorData("", ""); // fill in statement
  155. // iterate over the result set
  156. while (rs.next()) {
  157. oneSensor.setTagid(rs.getString("tagid"));
  158. oneSensor.setValue(rs.getString("value"));
  159. oneSensor.setUserid(rs.getString("userid"));
  160. oneSensor.setDate(rs.getString("timeinserted"));
  161. oneSensor.setTagid(rs.getString("tagid"));
  162. // add this sensor to ArrayList of Sensors
  163. allSensors.add(oneSensor);
  164. // debug print this sensor to console
  165. System.out.println(oneSensor.toString());
  166. }
  167. } catch (SQLException ex) {
  168. System.out.println("Error in SQL " + ex.getMessage());
  169. }
  170. // Convert sensor list to json array and send back to user
  171. String allSensorsJson = gson.toJson(allSensors);
  172.  
  173. // return this String from method
  174. return allSensorsJson;
  175.  
  176. }
  177.  
  178. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement