Application.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package controllers;
  2. import akka.dispatch.Futures;
  3. import models.World;
  4. import play.api.libs.concurrent.Promise;
  5. import play.libs.Akka;
  6. import play.libs.F;
  7. import play.libs.Json;
  8. import static play.libs.Akka.future;
  9. import org.codehaus.jackson.node.ObjectNode;
  10. import org.codehaus.jackson.map.ObjectMapper;
  11. import play.mvc.Controller;
  12. import play.mvc.Result;
  13. import scala.concurrent.ExecutionContext;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.Random;
  17. import java.util.concurrent.Callable;
  18. import java.util.concurrent.ThreadLocalRandom;
  19. import java.util.concurrent.TimeUnit;
  20. public class Application extends Controller {
  21. private static final int TEST_DATABASE_ROWS = 10000;
  22. //http://stackoverflow.com/questions/3907929/should-i-make-jacksons-objectmapper-as-static-final
  23. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  24. private static final ExecutionContext DB_EC = Akka.system().dispatchers().lookup("akka.actor.db");
  25. public static Result json() {
  26. final ObjectNode result = OBJECT_MAPPER.createObjectNode();
  27. result.put("message", "Hello World!");
  28. return ok(result);
  29. }
  30. public static Result db(final Integer queries) {
  31. return async(
  32. future(new Callable<Result>() {
  33. @Override
  34. public Result call() {
  35. final Random random = ThreadLocalRandom.current();
  36. final List<F.Promise<? extends World>> promises = new ArrayList<F.Promise<? extends World>>(queries);
  37. for (int i = 0; i < queries; ++i) {
  38. // There's no convenience method for submitting a future on an EC in Java. There is
  39. // an issue that will address this though: https://github.com/playframework/Play20/issues/972
  40. // Meanwhile we call the Akka future directly and wrap its result in a promise.
  41. final F.Promise p = Akka.asPromise(Futures.future(
  42. findWorld(Long.valueOf(random.nextInt(TEST_DATABASE_ROWS) + 1)), DB_EC));
  43. promises.add(p);
  44. }
  45. final List<World> worlds = F.Promise.sequence(promises).get(5L * queries, TimeUnit.SECONDS);
  46. return ok(Json.toJson(worlds));
  47. }
  48. private Callable<World> findWorld(final Long id) {
  49. return new Callable<World>() {
  50. @Override
  51. public World call() {
  52. return World.find.byId(id);
  53. }
  54. };
  55. }
  56. })
  57. );
  58. }
  59. }