DbMongoHandler.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package hello;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.google.common.net.MediaType;
  4. import com.mongodb.BasicDBObject;
  5. import com.mongodb.DB;
  6. import com.mongodb.DBObject;
  7. import io.undertow.server.HttpHandler;
  8. import io.undertow.server.HttpServerExchange;
  9. import io.undertow.util.Headers;
  10. import java.util.Objects;
  11. import static hello.HelloWebServer.JSON_UTF8;
  12. /**
  13. * Handles the single- and multiple-query database tests using MongoDB.
  14. */
  15. final class DbMongoHandler implements HttpHandler {
  16. private final ObjectMapper objectMapper;
  17. private final DB database;
  18. DbMongoHandler(ObjectMapper objectMapper, DB database) {
  19. this.objectMapper = Objects.requireNonNull(objectMapper);
  20. this.database = Objects.requireNonNull(database);
  21. }
  22. @Override
  23. public void handleRequest(HttpServerExchange exchange) throws Exception {
  24. if (exchange.isInIoThread()) {
  25. exchange.dispatch(this);
  26. return;
  27. }
  28. int queries = Helper.getQueries(exchange);
  29. World[] worlds = new World[queries];
  30. for (int i = 0; i < queries; i++) {
  31. DBObject object = database.getCollection("world").findOne(
  32. new BasicDBObject("id", Helper.randomWorld()));
  33. worlds[i] = new World(
  34. //
  35. // The creation script for the Mongo database inserts these numbers as
  36. // JavaScript numbers, which resolve to Doubles in Java.
  37. //
  38. ((Number) object.get("id")).intValue(),
  39. ((Number) object.get("randomNumber")).intValue());
  40. }
  41. exchange.getResponseHeaders().put(
  42. Headers.CONTENT_TYPE, JSON_UTF8);
  43. exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds));
  44. }
  45. }