use of java.util.concurrent.CompletableFuture in project failsafe by jhalterman.
the class Issue52 method shouldCancelExecutionViaCompletableFuture.
public void shouldCancelExecutionViaCompletableFuture() throws Throwable {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
AtomicInteger counter = new AtomicInteger();
CompletableFuture<String> proxyFuture = Failsafe.with(new RetryPolicy().withDelay(10, TimeUnit.MILLISECONDS)).with(scheduler).future(exec -> {
counter.incrementAndGet();
CompletableFuture<String> result = new CompletableFuture<>();
result.completeExceptionally(new RuntimeException());
return result;
});
Thread.sleep(100);
proxyFuture.cancel(true);
int count = counter.get();
assertTrue(proxyFuture.isCancelled());
Asserts.assertThrows(() -> proxyFuture.get(), CancellationException.class);
// Assert that execution has actually stopped
Thread.sleep(20);
assertEquals(count, counter.get());
}
use of java.util.concurrent.CompletableFuture in project jersey by jersey.
the class NettyConnector method apply.
@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
final URI requestUri = jerseyRequest.getUri();
String host = requestUri.getHost();
int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if ("https".equals(requestUri.getScheme())) {
// making client authentication optional for now; it could be extracted to configurable property
JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
p.addLast(jdkSslContext.newHandler(ch.alloc()));
}
// http proxy
Configuration config = jerseyRequest.getConfiguration();
final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
if (proxyUri != null) {
final URI u = getProxyUri(proxyUri);
final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
}
p.addLast(new HttpClientCodec());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpContentDecompressor());
p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
}
});
// connect timeout
Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
if (connectTimeout > 0) {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
}
// Make the connection attempt.
final Channel ch = b.connect(host, port).sync().channel();
// guard against prematurely closed channel
final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
@Override
public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
if (!settableFuture.isDone()) {
settableFuture.completeExceptionally(new IOException("Channel closed."));
}
}
};
ch.closeFuture().addListener(closeListener);
HttpRequest nettyRequest;
if (jerseyRequest.hasEntity()) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
} else {
nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
}
// headers
for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
nettyRequest.headers().add(e.getKey(), e.getValue());
}
// host header - http 1.1
nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
if (jerseyRequest.hasEntity()) {
if (jerseyRequest.getLengthLong() == -1) {
HttpUtil.setTransferEncodingChunked(nettyRequest, true);
} else {
nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
}
}
if (jerseyRequest.hasEntity()) {
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
return jerseyChunkedInput;
}
});
if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
ch.write(new HttpChunkedInput(jerseyChunkedInput));
} else {
ch.write(jerseyChunkedInput);
}
executorService.execute(new Runnable() {
@Override
public void run() {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
try {
jerseyRequest.writeEntity();
} catch (IOException e) {
jerseyCallback.failure(e);
settableFuture.completeExceptionally(e);
}
}
});
ch.flush();
} else {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
}
} catch (InterruptedException e) {
settableFuture.completeExceptionally(e);
return settableFuture;
}
return settableFuture;
}
use of java.util.concurrent.CompletableFuture in project jersey by jersey.
the class JettyConnector method apply.
@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback callback) {
final Request jettyRequest = translateRequest(jerseyRequest);
final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest);
final ContentProvider entity = getStreamProvider(jerseyRequest);
if (entity != null) {
jettyRequest.content(entity);
}
final AtomicBoolean callbackInvoked = new AtomicBoolean(false);
final Throwable failure;
try {
final CompletableFuture<ClientResponse> responseFuture = new CompletableFuture<ClientResponse>().whenComplete((clientResponse, throwable) -> {
if (throwable != null && throwable instanceof CancellationException) {
// take care of future cancellation
jettyRequest.abort(throwable);
}
});
final AtomicReference<ClientResponse> jerseyResponse = new AtomicReference<>();
final ByteBufferInputStream entityStream = new ByteBufferInputStream();
jettyRequest.send(new Response.Listener.Adapter() {
@Override
public void onHeaders(final Response jettyResponse) {
HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName());
if (responseFuture.isDone()) {
if (!callbackInvoked.compareAndSet(false, true)) {
return;
}
}
final ClientResponse response = translateResponse(jerseyRequest, jettyResponse, entityStream);
jerseyResponse.set(response);
callback.response(response);
}
@Override
public void onContent(final Response jettyResponse, final ByteBuffer content) {
try {
entityStream.put(content);
} catch (final InterruptedException ex) {
final ProcessingException pe = new ProcessingException(ex);
entityStream.closeQueue(pe);
// try to complete the future with an exception
responseFuture.completeExceptionally(pe);
Thread.currentThread().interrupt();
}
}
@Override
public void onComplete(final Result result) {
entityStream.closeQueue();
// try to complete the future with the response only once truly done
responseFuture.complete(jerseyResponse.get());
}
@Override
public void onFailure(final Response response, final Throwable t) {
entityStream.closeQueue(t);
// try to complete the future with an exception
responseFuture.completeExceptionally(t);
if (callbackInvoked.compareAndSet(false, true)) {
callback.failure(t);
}
}
});
processContent(jerseyRequest, entity);
return responseFuture;
} catch (final Throwable t) {
failure = t;
}
if (callbackInvoked.compareAndSet(false, true)) {
callback.failure(failure);
}
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeExceptionally(failure);
return future;
}
use of java.util.concurrent.CompletableFuture in project hbase by apache.
the class AsyncAggregationClient method std.
public static <R, S, P extends Message, Q extends Message, T extends Message> CompletableFuture<Double> std(RawAsyncTable table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) {
CompletableFuture<Double> future = new CompletableFuture<>();
AggregateRequest req;
try {
req = validateArgAndGetPB(scan, ci, false);
} catch (IOException e) {
future.completeExceptionally(e);
return future;
}
AbstractAggregationCallback<Double> callback = new AbstractAggregationCallback<Double>(future) {
private S sum;
private S sumSq;
private long count;
@Override
protected void aggregate(HRegionInfo region, AggregateResponse resp) throws IOException {
if (resp.getFirstPartCount() > 0) {
sum = ci.add(sum, getPromotedValueFromProto(ci, resp, 0));
sumSq = ci.add(sumSq, getPromotedValueFromProto(ci, resp, 1));
count += resp.getSecondPart().asReadOnlyByteBuffer().getLong();
}
}
@Override
protected Double getFinalResult() {
double avg = ci.divideForAvg(sum, count);
double avgSq = ci.divideForAvg(sumSq, count);
return Math.sqrt(avgSq - avg * avg);
}
};
table.coprocessorService(channel -> AggregateService.newStub(channel), (stub, controller, rpcCallback) -> stub.getStd(controller, req, rpcCallback), scan.getStartRow(), scan.includeStartRow(), scan.getStopRow(), scan.includeStopRow(), callback);
return future;
}
use of java.util.concurrent.CompletableFuture in project hbase by apache.
the class AsyncAggregationClient method avg.
public static <R, S, P extends Message, Q extends Message, T extends Message> CompletableFuture<Double> avg(RawAsyncTable table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) {
CompletableFuture<Double> future = new CompletableFuture<>();
AggregateRequest req;
try {
req = validateArgAndGetPB(scan, ci, false);
} catch (IOException e) {
future.completeExceptionally(e);
return future;
}
AbstractAggregationCallback<Double> callback = new AbstractAggregationCallback<Double>(future) {
private S sum;
long count = 0L;
@Override
protected void aggregate(HRegionInfo region, AggregateResponse resp) throws IOException {
if (resp.getFirstPartCount() > 0) {
sum = ci.add(sum, getPromotedValueFromProto(ci, resp, 0));
count += resp.getSecondPart().asReadOnlyByteBuffer().getLong();
}
}
@Override
protected Double getFinalResult() {
return ci.divideForAvg(sum, count);
}
};
table.coprocessorService(channel -> AggregateService.newStub(channel), (stub, controller, rpcCallback) -> stub.getAvg(controller, req, rpcCallback), scan.getStartRow(), scan.includeStartRow(), scan.getStopRow(), scan.includeStopRow(), callback);
return future;
}
Aggregations