DbPoolServlet.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package hello;
  2. import java.io.*;
  3. import java.sql.*;
  4. import java.util.*;
  5. import java.util.concurrent.*;
  6. import javax.annotation.*;
  7. import javax.servlet.*;
  8. import javax.servlet.http.*;
  9. import javax.sql.*;
  10. /**
  11. * Database connectivity (with a Servlet-container managed pool) test.
  12. */
  13. @SuppressWarnings("serial")
  14. public class DbPoolServlet extends HttpServlet
  15. {
  16. // Database details.
  17. private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?";
  18. private static final int DB_ROWS = 10000;
  19. // Database connection pool.
  20. @Resource(name="jdbc/hello_world")
  21. private DataSource mysqlDataSource;
  22. @Override
  23. protected void doGet(HttpServletRequest req, HttpServletResponse res)
  24. throws ServletException, IOException
  25. {
  26. // Set content type to JSON
  27. res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
  28. // Reference the data source.
  29. final DataSource source = mysqlDataSource;
  30. // Get the count of queries to run.
  31. int count = 1;
  32. try
  33. {
  34. count = Integer.parseInt(req.getParameter("queries"));
  35. // Bounds check.
  36. if (count > 500)
  37. {
  38. count = 500;
  39. }
  40. if (count < 1)
  41. {
  42. count = 1;
  43. }
  44. }
  45. catch (NumberFormatException nfexc)
  46. {
  47. // Do nothing.
  48. }
  49. // Fetch some rows from the database.
  50. final World[] worlds = new World[count];
  51. final Random random = ThreadLocalRandom.current();
  52. try (Connection conn = source.getConnection())
  53. {
  54. try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
  55. ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
  56. {
  57. // Run the query the number of times requested.
  58. for (int i = 0; i < count; i++)
  59. {
  60. final int id = random.nextInt(DB_ROWS) + 1;
  61. statement.setInt(1, id);
  62. try (ResultSet results = statement.executeQuery())
  63. {
  64. if (results.next())
  65. {
  66. worlds[i] = new World(id, results.getInt("randomNumber"));
  67. }
  68. }
  69. }
  70. }
  71. }
  72. catch (SQLException sqlex)
  73. {
  74. System.err.println("SQL Exception: " + sqlex);
  75. }
  76. // Write JSON encoded message to the response.
  77. try
  78. {
  79. if (count == 1)
  80. {
  81. Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]);
  82. }
  83. else
  84. {
  85. Common.MAPPER.writeValue(res.getOutputStream(), worlds);
  86. }
  87. }
  88. catch (IOException ioe)
  89. {
  90. // do nothing
  91. }
  92. }
  93. }