Advertisement
Guest User

Untitled

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