Using async mongo driver with Java play

731 views Asked by At

I am starting new Java Play project with mongo DB. I looked through Play! documentation, but there is no mongo Java async drivers. Only Scala reactive driver is mentioned. SO has number of similar questions, but they all are outdated.

What is the best way now to deal with mongo DB in async way?

Let's say I have just one documents collection with orders and I need to add an OrderController that will return all orders from mongo.

1

There are 1 answers

0
YuriR On

Finally i managed to do it. Posting code for other programmers. The code goes to Mongo using async driver and returns json with database names.

public class MyController extends Controller {

    public CompletionStage<Result> getDBNames() throws InterruptedException {
        CompletionStage<List<String>> mongoDBNames = new MongoServiceWithPromises().getMongoDBNames();
        return mongoDBNames.thenApply(stringListToJson);
    }

    Function<List<String>, Result> stringListToJson = obj -> {
        JsonNode jsonNode = Json.toJson(obj);
        return ok(jsonNode);
    };
}

public class MongoServiceWithPromises {
    // Open the client
    private MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost:27017"));


    public CompletionStage<List<String>> getMongoDBNames() {
        final CompletableFuture<List<String>> future = new CompletableFuture<>();

        final SingleResultCallback<List<String>> callback = (dbNames, cb) -> {
            if (cb == null) {
                future.complete(dbNames);
            } else {
                future.completeExceptionally(cb);
            }
        };
        mongoClient.listDatabaseNames().into(new ArrayList<>(), callback);
        return future;
    }
}