Guest User

Untitled

a guest
May 12th, 2016
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.20 KB | None | 0 0
  1. package api;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.net.URI;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13. import java.sql.Timestamp;
  14. import java.time.Instant;
  15. import java.util.HashMap;
  16. import java.util.LinkedHashMap;
  17. import java.util.Map;
  18. import java.util.Scanner;
  19. import java.util.Set;
  20.  
  21. import org.json.JSONArray;
  22. import org.json.JSONException;
  23. import org.json.JSONObject;
  24.  
  25. import com.sun.net.httpserver.Headers;
  26. import com.sun.net.httpserver.HttpExchange;
  27. import com.sun.net.httpserver.HttpHandler;
  28.  
  29. import jdk.nashorn.internal.scripts.JO;
  30.  
  31. public class API implements HttpHandler {
  32. Connection db;
  33.  
  34. public API() throws ClassNotFoundException, SQLException {
  35. Class.forName("org.postgresql.Driver");
  36. this.db = DriverManager.getConnection("jdbc:postgresql://localhost/", "postgres", "123456");
  37. }
  38.  
  39. @Override
  40. public void handle(HttpExchange t) throws IOException {
  41. String method = t.getRequestMethod();
  42. URI uri = t.getRequestURI();
  43. String[] paths = uri.getPath().replaceFirst("^/", "").split("/");
  44. String query = uri.getQuery();
  45. if (query == null)
  46. query = "";
  47. Map<String, String> map = queryToMap(query);
  48. try {
  49. process(t, method, paths, map);
  50. } catch (SQLException e) {
  51. e.printStackTrace();
  52. respond(t, formatError(method, map, "Unknown error."), 500);
  53. }
  54. }
  55.  
  56. private void process(HttpExchange t, String method, String[] paths, Map<String, String> query)
  57. throws IOException, SQLException {
  58. Headers h = t.getResponseHeaders();
  59. h.add("Content-Type", "application/json");
  60.  
  61. InputStream is = t.getRequestBody();
  62. Scanner s = new Scanner(is);
  63. s.useDelimiter("\\A");
  64. String body = s.hasNext() ? s.next() : "";
  65. s.close();
  66. is.close();
  67.  
  68. switch (paths[1]) {
  69. case "event":
  70. eventEndpoint(t, method, paths, query, body);
  71. break;
  72. default: {
  73. String response = "{a:\"aaaa\", b}";
  74. respond(t, response, 200);
  75. }
  76. }
  77. }
  78.  
  79. private void eventEndpoint(HttpExchange t, String method, String[] paths, Map<String, String> query, String body)
  80. throws IOException, SQLException {
  81. if (paths.length >= 3) {
  82. switch (paths[2]) {
  83. case "list":
  84. eventListVerb(t, method, paths, query);
  85. break;
  86. }
  87. }
  88. switch (method) {
  89. case "GET": {
  90. try {
  91. String sID = query.get("id");
  92. if (sID == null)
  93. respond(t, formatError(method, query, "Missing argument 'id'."), 400);
  94. else {
  95. int id = Integer.parseInt(sID);
  96. Statement stmt = this.db.createStatement();
  97. ResultSet rs = stmt.executeQuery("SELECT * FROM Events WHERE id = " + id);
  98. if (!rs.next())
  99. respond(t, formatError(method, query, "Event does not exist."), 400);
  100. else
  101. respond(t, eventResultToJSON(rs).toString(), 200);
  102. }
  103. } catch (NumberFormatException e) {
  104. respond(t, formatError(method, query, "Invalid request parameters."), 400);
  105. }
  106. }
  107. break;
  108. case "PUT":
  109. eventCreate(t, method, query, body);
  110. break;
  111. default:
  112. respond(t, formatError(method, query, "Invalid method."), 404);
  113. }
  114. }
  115.  
  116. private void eventCreate(HttpExchange t, String method, Map<String, String> query, String body)
  117. throws IOException, SQLException {
  118. try {
  119. JSONObject jo = new JSONObject(body).getJSONObject("create_event");
  120. PreparedStatement stmt = this.db.prepareStatement(
  121. "INSERT INTO Events (type, description, location, coords) VALUES (?, ?, ?, Point(?, ?))");
  122. stmt.setInt(1, jo.getInt("type"));
  123. stmt.setString(2, jo.getString("description"));
  124.  
  125. if (jo.has("location"))
  126. stmt.setString(3, jo.getString("location"));
  127. else
  128. stmt.setNull(3, java.sql.Types.NULL);
  129.  
  130. if (jo.has("latitude") && jo.has("longitude")) {
  131. stmt.setFloat(4, (float)jo.getDouble("latitude"));
  132. stmt.setFloat(5, (float)jo.getDouble("longitude"));
  133. } else {
  134. stmt.setNull(4, java.sql.Types.NULL);
  135. stmt.setNull(5, java.sql.Types.NULL);
  136. }
  137.  
  138. if (stmt.executeUpdate() == 0)
  139. respond(t, formatError(method, query, "Invalid request parameters."), 400);
  140. else
  141. respond(t, formatSuccess(method, query), 200);
  142. } catch (JSONException e) {
  143. respond(t, formatError(method, query, "Invalid request."), 400);
  144. return;
  145. }
  146.  
  147. }
  148.  
  149. private String findMissingArgument(Map<String, String> query, String... requireds) {
  150. for (String required : requireds) {
  151. if (query.get(required) == null)
  152. return required;
  153. }
  154. return null;
  155. }
  156.  
  157. private JSONObject eventResultToJSON(ResultSet rs) throws JSONException, SQLException {
  158. JSONObject jo = new JSONObject();
  159. jo.put("id", rs.getInt("id"));
  160. jo.put("type", rs.getInt("type"));
  161. jo.put("description", rs.getString("description"));
  162.  
  163. String location = rs.getString("location");
  164. String coords = rs.getString("coords");
  165. if (location != null)
  166. jo.put("location", location);
  167. if (coords != null)
  168. jo.put("coordinates", coords);
  169.  
  170. jo.put("datetime", rs.getTimestamp("datetime"));
  171. return jo;
  172. }
  173.  
  174. private void eventListVerb(HttpExchange t, String method, String[] paths, Map<String, String> query)
  175. throws IOException, SQLException {
  176. if (!method.equals("GET")) {
  177. String response = formatError(method, query, "Invalid method.");
  178. respond(t, response, 404);
  179. } else {
  180. Statement stmt = this.db.createStatement();
  181. ResultSet rs = stmt.executeQuery("SELECT * FROM Events ORDER BY datetime DESC");
  182. JSONArray ja = new JSONArray();
  183. while (rs.next()) {
  184. ja.put(eventResultToJSON(rs));
  185. }
  186. respond(t, ja.toString(), 200);
  187. rs.close();
  188. stmt.close();
  189. }
  190. }
  191.  
  192. /***********************************
  193. ************** UTILS **************
  194. ***********************************/
  195.  
  196. private String formatError(String method, Map<String, String> query, String errorMsg) {
  197. JSONObject jo = new JSONObject();
  198. JSONObject joError = new JSONObject();
  199. joError.put("oper", method);
  200. if (query != null)
  201. for (Map.Entry<String, String> entry : query.entrySet()) {
  202. joError.put(entry.getKey(), entry.getValue());
  203. }
  204. joError.put("msg", errorMsg);
  205. jo.put("error", joError);
  206. return jo.toString();
  207. }
  208.  
  209. private String formatSuccess(String method, Map<String, String> query) {
  210. JSONObject jo = new JSONObject();
  211. JSONObject joSuccess = new JSONObject();
  212. joSuccess.put("oper", method);
  213. if (query != null)
  214. for (Map.Entry<String, String> entry : query.entrySet()) {
  215. joSuccess.put(entry.getKey(), entry.getValue());
  216. }
  217. jo.put("success", joSuccess);
  218. return jo.toString();
  219. }
  220.  
  221. private void respond(HttpExchange t, String response, int code) throws IOException {
  222. t.sendResponseHeaders(200, response.getBytes().length);
  223. OutputStream os = t.getResponseBody();
  224. os.write(response.getBytes());
  225. os.close();
  226. }
  227.  
  228. private Map<String, String> queryToMap(String query) {
  229. Map<String, String> result = new LinkedHashMap<String, String>();
  230. for (String param : query.split("&")) {
  231. String pair[] = param.split("=");
  232. if (pair.length > 1) {
  233. result.put(pair[0].toLowerCase(), pair[1]);
  234. } else {
  235. result.put(pair[0].toLowerCase(), "");
  236. }
  237. }
  238. return result;
  239. }
  240. }
Add Comment
Please, Sign In to add comment