Advertisement
Guest User

Untitled

a guest
May 19th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. public class DB {
  2.  
  3. ComboPooledDataSource dataSource;
  4. HttpServletResponse response;
  5.  
  6. public Connection conn;
  7. public static DB db = new DB();
  8.  
  9. private DB(){
  10. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  11. try {
  12. dataSource.setDriverClass("com.mysql.jdbc.Driver");
  13.  
  14. String db = System.getProperty("RDS_DB_NAME");
  15. String username = System.getProperty("RDS_USERNAME");
  16. String password = System.getProperty("RDS_PASSWORD");
  17. String hostname = System.getProperty("RDS_HOSTNAME");
  18. String port = System.getProperty("RDS_PORT");
  19.  
  20. String jdbcURL = "jdbc:mysql://" + hostname + ":" + port + "/" + db + "?user=" + username + "&password=" + password;
  21.  
  22. dataSource.setJdbcUrl(jdbcURL);
  23.  
  24. this.dataSource = dataSource;
  25. } catch (PropertyVetoException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29.  
  30. /**
  31. * Get database name
  32. * @return Databse name
  33. */
  34. public static String dbN(){
  35. return DATABASE;
  36. }
  37.  
  38. /**
  39. * Gets the database connection
  40. * @return Database connection
  41. * @throws SQLException
  42. */
  43. public Connection getDatabase() throws SQLException{
  44. return dataSource.getConnection();
  45. }}
  46.  
  47. @GET
  48. @Path("/{session}")
  49. @Produces("application/json")
  50. public Response getAll(@PathParam("session") String session){
  51.  
  52. JSONArray response = new JSONArray();
  53. Connection conn = null;
  54. PreparedStatement prepared = null;
  55. ResultSet rs = null;
  56.  
  57. try {
  58. conn = DB.db.getDatabase();
  59. prepared = conn.prepareStatement("SQL STATEMENT");
  60. prepared.setString(1, session);
  61. prepared.setTimestamp(2, new Timestamp(Time.current()));
  62.  
  63. rs = prepared.executeQuery();
  64.  
  65. while(rs.next()){
  66. JSONObject obj = new JSONObject();
  67. obj.put("id", rs.getInt("id"));
  68. obj.put("name", rs.getString("name"));
  69. obj.put("color", rs.getString("color"));
  70.  
  71. response.put(obj);
  72. }
  73. } catch (SQLException e) {
  74. e.printStackTrace();
  75. return Response.status(500).build();
  76. } finally{
  77. try{
  78. prepared.close();
  79. rs.close();
  80. conn.close();
  81. }
  82. catch (SQLException e){
  83. e.printStackTrace();
  84. }
  85. }
  86. return Response.status(200).entity(response.toString()).build();
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement