Application.java 2.3 KB

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