Application.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package controllers;
  2. import models.World;
  3. import play.libs.F;
  4. import play.libs.Json;
  5. import static play.libs.Akka.future;
  6. import org.codehaus.jackson.node.ObjectNode;
  7. import org.codehaus.jackson.map.ObjectMapper;
  8. import play.mvc.Controller;
  9. import play.mvc.Result;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.Random;
  13. import java.util.concurrent.Callable;
  14. import java.util.concurrent.ThreadLocalRandom;
  15. public class Application extends Controller {
  16. private static final int TEST_DATABASE_ROWS = 10000;
  17. //http://stackoverflow.com/questions/3907929/should-i-make-jacksons-objectmapper-as-static-final
  18. private static final ObjectMapper objectMapper = new ObjectMapper();
  19. public static Result json() {
  20. final ObjectNode result = objectMapper.createObjectNode();
  21. result.put("message", "Hello World!");
  22. return ok(result);
  23. }
  24. public static Result db(final Integer queries) {
  25. return async(
  26. future(new Callable<Result>() {
  27. @Override
  28. public Result call() {
  29. final Random random = ThreadLocalRandom.current();
  30. final List<F.Promise<? extends World>> promises = new ArrayList<F.Promise<? extends World>>(queries);
  31. for (int i = 0; i < queries; ++i) {
  32. promises.add(future(findWorld(Long.valueOf(random.nextInt(TEST_DATABASE_ROWS) + 1))));
  33. }
  34. final List<World> worlds = F.Promise.sequence(promises).get();
  35. return ok(Json.toJson(worlds));
  36. }
  37. private Callable<World> findWorld(final Long id) {
  38. return new Callable<World>() {
  39. @Override
  40. public World call() {
  41. return World.find.byId(id);
  42. }
  43. };
  44. }
  45. })
  46. );
  47. }
  48. }