DbResource.java 1.7 KB

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