Skip to content

Instantly share code, notes, and snippets.

@jonefeewang
Forked from imasahiro/Handler.java
Created December 16, 2016 07:29
Show Gist options
  • Save jonefeewang/6e423491093bba124bc851be537c9541 to your computer and use it in GitHub Desktop.
Save jonefeewang/6e423491093bba124bc851be537c9541 to your computer and use it in GitHub Desktop.
private final class Handler implements HelloService.AsyncIface {
@Override
public void hello(String name, AsyncMethodCallback resultHandler) throws TException {
setAsyncResult(resultHandler, CompletableFuture.completedFuture("hello"));
}
}
public static <T> void setAsyncResult(AsyncMethodCallback<T> resultHandler,
ListenableFuture<T> future) {
Futures.addCallback(future, new FutureCallback<T>() {
@Override
public void onSuccess(@Nullable T result) {
resultHandler.onComplete(result);
}
@Override
public void onFailure(Throwable t) {
if (t instanceof Exception) {
resultHandler.onError((Exception) t);
}
}
});
}
public static <T> void setAsyncResult(AsyncMethodCallback<T> resultHandler,
CompletableFuture<T> future) {
future.handle(voidFunction((result, thrown) -> {
if (thrown != null) {
resultHandler.onError((Exception) thrown);
} else {
resultHandler.onComplete(result);
}
}));
}
// Server side
private final class HelloServiceHandler implements HelloService.AsyncIface {
@Override
public void hello(String name, AsyncMethodCallback resultHandler) throws TException {
resultHandler.onComplete(name);
}
}
private void setup() {
new ServerBuilder()
.port(8080, SessionProtocol.HTTP)
.serviceAt("/thrift", THttpService.of(new HelloServiceHandler()))
.build()
.start()
.join();
}
// Client side
public CompletableFuture<String> hello(String name) throws TException {
HelloService.AsyncIface async = Clients.newClient("http+tbinary://127.0.0.1:8080/thrift",
HelloService.AsyncIface.class);
ThriftCompletableFuture<String> future = new ThriftCompletableFuture<>();
async.hello(name, future);
return future;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment