DbPoolServlet.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. Common.MAPPER.writeValue(res.getOutputStream(), worlds);
  80. }
  81. catch (IOException ioe)
  82. {
  83. // do nothing
  84. }
  85. }
  86. }