DbMongoAsyncHandler.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package hello;
  2. import static hello.Helper.randomWorldNumber;
  3. import static hello.Helper.sendException;
  4. import static hello.Helper.sendJson;
  5. import com.mongodb.async.client.MongoCollection;
  6. import com.mongodb.async.client.MongoDatabase;
  7. import com.mongodb.client.model.Filters;
  8. import io.undertow.server.HttpHandler;
  9. import io.undertow.server.HttpServerExchange;
  10. import org.bson.Document;
  11. /**
  12. * Handles the single-query database test using MongoDB with an asynchronous
  13. * API.
  14. */
  15. final class DbMongoAsyncHandler implements HttpHandler {
  16. private final MongoCollection<Document> worldCollection;
  17. DbMongoAsyncHandler(MongoDatabase db) {
  18. worldCollection = db.getCollection("world");
  19. }
  20. @Override
  21. public void handleRequest(HttpServerExchange exchange) {
  22. worldCollection
  23. .find(Filters.eq(randomWorldNumber()))
  24. .map(Helper::mongoDocumentToWorld)
  25. .first(
  26. (world, exception) -> {
  27. if (exception != null) {
  28. sendException(exchange, exception);
  29. } else {
  30. sendJson(exchange, world);
  31. }
  32. });
  33. }
  34. }