Skip to content

Instantly share code, notes, and snippets.

@rmannibucau
Created February 21, 2016 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmannibucau/09a084c28d8b61c232cf to your computer and use it in GitHub Desktop.
Save rmannibucau/09a084c28d8b61c232cf to your computer and use it in GitHub Desktop.
import lombok.RequiredArgsConstructor;
import javax.ws.rs.client.InvocationCallback;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
public class JaxRsPromise {
// typed String cause of CXF-6793
private CompletableFuture<String> delegate;
public JaxRsPromise() {
delegate = new CompletableFuture<>();
}
public JaxRsPromise propagateCancel(final Future<?> future) {
delegate = delegate.whenComplete((result, exception) -> { // try to cancel the call if completable future is cancelled
if (CancellationException.class.isInstance(exception)) {
future.cancel(true);
}
});
return this;
}
public CompletableFuture<?> toFuture() {
return delegate;
}
public InvocationCallback<?> toJaxRsCallback() {
return new PromiseInvocationCallback(delegate);
}
@RequiredArgsConstructor
private static class PromiseInvocationCallback implements InvocationCallback<String> {
private final CompletableFuture<String> delegate;
@Override
public void completed(final String o) {
delegate.complete(o);
}
@Override
public void failed(final Throwable throwable) {
delegate.completeExceptionally(throwable);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment