use of java.util.concurrent.Future in project failsafe by jhalterman.
the class Issue76 method shouldAbortOnAsyncError.
public void shouldAbortOnAsyncError() throws Exception {
final AssertionError error = new AssertionError();
Waiter waiter = new Waiter();
Future<?> future = Failsafe.with(new RetryPolicy().abortOn(AssertionError.class)).with(Executors.newSingleThreadScheduledExecutor()).onAbort(e -> {
waiter.assertEquals(e, error);
waiter.resume();
}).run(() -> {
throw error;
});
waiter.await(1000);
try {
future.get();
fail();
} catch (ExecutionException e) {
assertEquals(e.getCause(), error);
}
}
use of java.util.concurrent.Future 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.Future in project jersey by jersey.
the class BasicClientTest method testAsyncClientInvocation.
@Test
public void testAsyncClientInvocation() throws InterruptedException, ExecutionException {
final WebTarget resource = target().path("resource");
Future<Response> f1 = resource.request().async().post(text("post1"));
final Response response = f1.get();
assertEquals("post1", response.readEntity(String.class));
Future<String> f2 = resource.request().async().post(text("post2"), String.class);
assertEquals("post2", f2.get());
Future<List<JaxbString>> f3 = resource.request().async().get(new GenericType<List<JaxbString>>() {
});
assertEquals(Arrays.asList("a", "b", "c").toString(), f3.get().stream().map(input -> input.value).collect(Collectors.toList()).toString());
CompletableFuture<String> future1 = new CompletableFuture<>();
final TestCallback<Response> c1 = new TestCallback<Response>(future1) {
@Override
protected String process(Response result) {
return result.readEntity(String.class);
}
};
resource.request().async().post(text("post"), c1);
assertEquals("post", future1.get());
CompletableFuture<String> future2 = new CompletableFuture<>();
final TestCallback<String> c2 = new TestCallback<String>(future2) {
@Override
protected String process(String result) {
return result;
}
};
resource.request().async().post(text("post"), c2);
assertEquals("post", future2.get());
CompletableFuture<String> future3 = new CompletableFuture<>();
final TestCallback<List<JaxbString>> c3 = new TestCallback<List<JaxbString>>(future3) {
@Override
protected String process(List<JaxbString> result) {
return result.stream().map(jaxbString -> jaxbString.value).collect(Collectors.toList()).toString();
}
};
resource.request().async().get(c3);
assertEquals(Arrays.asList("a", "b", "c").toString(), future3.get());
}
use of java.util.concurrent.Future in project jersey by jersey.
the class SubResourceTest method testConcurrentSubResourceAccess.
/**
* Test concurrent sub-resource access. (See JERSEY-1421).
*
* @throws Exception in case of test failure.
*/
@Test
public void testConcurrentSubResourceAccess() throws Exception {
final WebTarget subResource = target("root/sub/sub2");
final int MAX = 25;
final List<Future<String>> results = new ArrayList<Future<String>>(MAX);
for (int i = 0; i < MAX; i++) {
results.add(subResource.request().async().get(String.class));
}
for (Future<String> resultFuture : results) {
assertEquals(SubResource.MESSAGE, resultFuture.get());
}
}
use of java.util.concurrent.Future in project jersey by jersey.
the class AsyncAgentResource method async.
@GET
@ManagedAsync
public void async(@Suspended final AsyncResponse async) {
final long time = System.nanoTime();
final AgentResponse response = new AgentResponse();
final CountDownLatch outerLatch = new CountDownLatch(2);
final Queue<String> errors = new ConcurrentLinkedQueue<>();
// Obtain visited destinations.
destination.path("visited").request().header("Rx-User", "Async").async().get(new InvocationCallback<List<Destination>>() {
@Override
public void completed(final List<Destination> destinations) {
response.setVisited(destinations);
outerLatch.countDown();
}
@Override
public void failed(final Throwable throwable) {
errors.offer("Visited: " + throwable.getMessage());
outerLatch.countDown();
}
});
// Obtain recommended destinations. (does not depend on visited ones)
destination.path("recommended").request().header("Rx-User", "Async").async().get(new InvocationCallback<List<Destination>>() {
@Override
public void completed(final List<Destination> recommended) {
final CountDownLatch innerLatch = new CountDownLatch(recommended.size() * 2);
// Forecasts. (depend on recommended destinations)
final Map<String, Forecast> forecasts = Collections.synchronizedMap(new HashMap<>());
for (final Destination dest : recommended) {
forecast.resolveTemplate("destination", dest.getDestination()).request().async().get(new InvocationCallback<Forecast>() {
@Override
public void completed(final Forecast forecast) {
forecasts.put(dest.getDestination(), forecast);
innerLatch.countDown();
}
@Override
public void failed(final Throwable throwable) {
errors.offer("Forecast: " + throwable.getMessage());
innerLatch.countDown();
}
});
}
// Calculations. (depend on recommended destinations)
final List<Future<Calculation>> futures = recommended.stream().map(dest -> calculation.resolveTemplate("from", "Moon").resolveTemplate("to", dest.getDestination()).request().async().get(Calculation.class)).collect(Collectors.toList());
final Map<String, Calculation> calculations = new HashMap<>();
while (!futures.isEmpty()) {
final Iterator<Future<Calculation>> iterator = futures.iterator();
while (iterator.hasNext()) {
final Future<Calculation> f = iterator.next();
if (f.isDone()) {
try {
final Calculation calculation = f.get();
calculations.put(calculation.getTo(), calculation);
innerLatch.countDown();
} catch (final Throwable t) {
errors.offer("Calculation: " + t.getMessage());
innerLatch.countDown();
} finally {
iterator.remove();
}
}
}
}
// Have to wait here for dependent requests ...
try {
if (!innerLatch.await(10, TimeUnit.SECONDS)) {
errors.offer("Inner: Waiting for requests to complete has timed out.");
}
} catch (final InterruptedException e) {
errors.offer("Inner: Waiting for requests to complete has been interrupted.");
}
// Recommendations.
final List<Recommendation> recommendations = new ArrayList<>(recommended.size());
for (final Destination dest : recommended) {
final Forecast fore = forecasts.get(dest.getDestination());
final Calculation calc = calculations.get(dest.getDestination());
recommendations.add(new Recommendation(dest.getDestination(), fore != null ? fore.getForecast() : "N/A", calc != null ? calc.getPrice() : -1));
}
response.setRecommended(recommendations);
outerLatch.countDown();
}
@Override
public void failed(final Throwable throwable) {
errors.offer("Recommended: " + throwable.getMessage());
outerLatch.countDown();
}
});
// ... and have to wait also here for independent requests.
try {
if (!outerLatch.await(10, TimeUnit.SECONDS)) {
errors.offer("Outer: Waiting for requests to complete has timed out.");
}
} catch (final InterruptedException e) {
errors.offer("Outer: Waiting for requests to complete has been interrupted.");
}
// Do something with errors.
// ...
response.setProcessingTime((System.nanoTime() - time) / 1000000);
async.resume(response);
}
Aggregations