DbResource.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package hello;
  2. import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
  3. import com.sun.jersey.spi.resource.Singleton;
  4. import hello.domain.World;
  5. import java.util.concurrent.Callable;
  6. import java.util.concurrent.ExecutionException;
  7. import java.util.concurrent.Future;
  8. import java.util.concurrent.ThreadLocalRandom;
  9. import javax.ws.rs.GET;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.QueryParam;
  13. import javax.ws.rs.core.Context;
  14. import org.hibernate.Session;
  15. import org.hibernate.SessionFactory;
  16. @Singleton
  17. @Path("/db")
  18. public class DbResource {
  19. @Context
  20. private SessionFactory sessionFactory;
  21. @GET
  22. @Produces(APPLICATION_JSON)
  23. public Object db(@QueryParam("queries") String queryParam,
  24. @QueryParam("single") boolean isSingle)
  25. throws ExecutionException, InterruptedException {
  26. int queries = getQueries(queryParam);
  27. @SuppressWarnings("unchecked")
  28. Future<World>[] futureWorlds = new Future[queries];
  29. for (int i = 0; i < queries; i++) {
  30. Callable<World> callable =
  31. () -> {
  32. int id = ThreadLocalRandom.current().nextInt(DB_ROWS) + 1;
  33. Session session = sessionFactory.openSession();
  34. session.setDefaultReadOnly(true);
  35. try {
  36. return (World) session.byId(World.class).load(id);
  37. } finally {
  38. session.close();
  39. }
  40. };
  41. futureWorlds[i] = Common.EXECUTOR.submit(callable);
  42. }
  43. World[] worlds = new World[queries];
  44. for (int i = 0; i < queries; i++) {
  45. worlds[i] = futureWorlds[i].get();
  46. }
  47. return isSingle ? worlds[0] : worlds;
  48. }
  49. private static int getQueries(String proto) {
  50. int result = 1;
  51. try {
  52. if (proto != null && !proto.trim().isEmpty()) {
  53. result = Integer.parseInt(proto);
  54. }
  55. } catch (NumberFormatException ignored) {/* by test contract */}
  56. return Math.min(500, Math.max(1, result));
  57. }
  58. private static final int DB_ROWS = 10000;
  59. }