Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MongoDB Async Java Driver in Play Framework 2.x action?

I want to use MongoDB Async Java Driver in a Play Framework 2 project, MongoDB Async Java Driver return SingleResponseCallback. I do not know how to handle this kind of result in Play controllers.

For example how to return count from the following code in a Play controller:

collection.count(
 new SingleResultCallback<Long>() {
  @Override
  public void onResult(final Long count, final Throwable t) {
      System.out.println(count);
  }
});

How can i get result from SingleResultCallback and then convert it to Promise? is it good way? What is the best practice in this situations?

like image 829
Saeed Zarinfam Avatar asked Oct 31 '22 22:10

Saeed Zarinfam


1 Answers

You have to resolve the promise yourself. Remember that the Play promises are wrappers to scala futures and that the only way to resolve a future is using scala Promises (different from play promises) (I know, it's kinda confusing). You'd have to do something like this:

Promise<Long> promise = Promise$.MODULE$.apply();
collection.count(
 new SingleResultCallback<Long>() {
   @Override
   public void onResult(final Long count, final Throwable t) {
     promise.success(count);
  }
});
return F.Promise.wrap(promise.future());

That thing about the Promise$.MODULE$.apply() is just the way to access scala objects from java.

like image 90
Alejandro Navas Avatar answered Nov 15 '22 07:11

Alejandro Navas