QueriesMongoAsyncHandler.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package hello;
  2. import static hello.Helper.getQueries;
  3. import static hello.Helper.randomWorldNumber;
  4. import static hello.Helper.sendException;
  5. import static hello.Helper.sendJson;
  6. import com.mongodb.async.client.MongoCollection;
  7. import com.mongodb.async.client.MongoDatabase;
  8. import com.mongodb.client.model.Filters;
  9. import io.undertow.server.HttpHandler;
  10. import io.undertow.server.HttpServerExchange;
  11. import java.util.concurrent.CompletableFuture;
  12. import org.bson.Document;
  13. /**
  14. * Handles the multi-query database test using MongoDB with an asynchronous API.
  15. */
  16. final class QueriesMongoAsyncHandler implements HttpHandler {
  17. private final MongoCollection<Document> worldCollection;
  18. QueriesMongoAsyncHandler(MongoDatabase db) {
  19. worldCollection = db.getCollection("world");
  20. }
  21. @Override
  22. public void handleRequest(HttpServerExchange exchange) {
  23. int queries = getQueries(exchange);
  24. nWorlds(queries).whenComplete(
  25. (worlds, exception) -> {
  26. if (exception != null) {
  27. sendException(exchange, exception);
  28. } else {
  29. sendJson(exchange, worlds);
  30. }
  31. });
  32. }
  33. private CompletableFuture<World[]> nWorlds(int n) {
  34. @SuppressWarnings({ "unchecked", "rawtypes" })
  35. CompletableFuture<World>[] futures = new CompletableFuture[n];
  36. for (int i = 0; i < futures.length; i++) {
  37. futures[i] = oneWorld();
  38. }
  39. return CompletableFuture.allOf(futures).thenApply(
  40. nil -> {
  41. World[] worlds = new World[futures.length];
  42. for (int i = 0; i < futures.length; i++) {
  43. worlds[i] = futures[i].join();
  44. }
  45. return worlds;
  46. });
  47. }
  48. private CompletableFuture<World> oneWorld() {
  49. CompletableFuture<World> future = new CompletableFuture<>();
  50. worldCollection
  51. .find(Filters.eq(randomWorldNumber()))
  52. .map(Helper::mongoDocumentToWorld)
  53. .first(
  54. (world, exception) -> {
  55. if (exception != null) {
  56. future.completeExceptionally(exception);
  57. } else {
  58. future.complete(world);
  59. }
  60. });
  61. return future;
  62. }
  63. }