Search in sources :

Example 96 with Future

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);
    }
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) Future(java.util.concurrent.Future) Waiter(net.jodah.concurrentunit.Waiter) FailsafeException(net.jodah.failsafe.FailsafeException) Assert.fail(org.testng.Assert.fail) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) RetryPolicy(net.jodah.failsafe.RetryPolicy) Executors(java.util.concurrent.Executors) Failsafe(net.jodah.failsafe.Failsafe) Waiter(net.jodah.concurrentunit.Waiter) ExecutionException(java.util.concurrent.ExecutionException) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Example 97 with Future

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;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 98 with Future

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());
}
Also used : Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ClientConfig(org.glassfish.jersey.client.ClientConfig) Assert.assertNotSame(org.junit.Assert.assertNotSame) Path(javax.ws.rs.Path) Client(javax.ws.rs.client.Client) CompletableFuture(java.util.concurrent.CompletableFuture) Application(javax.ws.rs.core.Application) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) AsyncInvoker(javax.ws.rs.client.AsyncInvoker) ClientBuilder(javax.ws.rs.client.ClientBuilder) Future(java.util.concurrent.Future) MediaType(javax.ws.rs.core.MediaType) JerseyTest(org.glassfish.jersey.test.JerseyTest) InvocationCallback(javax.ws.rs.client.InvocationCallback) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Assert.fail(org.junit.Assert.fail) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) POST(javax.ws.rs.POST) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Invocation(javax.ws.rs.client.Invocation) ThreadPoolExecutorProvider(org.glassfish.jersey.spi.ThreadPoolExecutorProvider) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Collectors(java.util.stream.Collectors) Entity.text(javax.ws.rs.client.Entity.text) NotFoundException(javax.ws.rs.NotFoundException) ExecutionException(java.util.concurrent.ExecutionException) GenericType(javax.ws.rs.core.GenericType) List(java.util.List) WriterInterceptorContext(javax.ws.rs.ext.WriterInterceptorContext) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) WebTarget(javax.ws.rs.client.WebTarget) ClientAsyncExecutor(org.glassfish.jersey.client.ClientAsyncExecutor) Assert.assertEquals(org.junit.Assert.assertEquals) Response(javax.ws.rs.core.Response) CompletableFuture(java.util.concurrent.CompletableFuture) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 99 with Future

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());
    }
}
Also used : ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) WebTarget(javax.ws.rs.client.WebTarget) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 100 with Future

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);
}
Also used : Destination(org.glassfish.jersey.examples.rx.domain.Destination) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) InvocationCallback(javax.ws.rs.client.InvocationCallback) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) Iterator(java.util.Iterator) Future(java.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) HashMap(java.util.HashMap) Map(java.util.Map) GET(javax.ws.rs.GET) ManagedAsync(org.glassfish.jersey.server.ManagedAsync)

Aggregations

Future (java.util.concurrent.Future)1138 ArrayList (java.util.ArrayList)479 ExecutorService (java.util.concurrent.ExecutorService)445 Test (org.junit.Test)413 ExecutionException (java.util.concurrent.ExecutionException)264 Callable (java.util.concurrent.Callable)206 IOException (java.io.IOException)177 ParallelTest (com.hazelcast.test.annotation.ParallelTest)148 QuickTest (com.hazelcast.test.annotation.QuickTest)148 HashMap (java.util.HashMap)92 List (java.util.List)84 CountDownLatch (java.util.concurrent.CountDownLatch)71 LinkedList (java.util.LinkedList)67 TimeoutException (java.util.concurrent.TimeoutException)63 HashSet (java.util.HashSet)62 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)59 Map (java.util.Map)58 ICompletableFuture (com.hazelcast.core.ICompletableFuture)57 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)53 File (java.io.File)46