Search in sources :

Example 81 with AsyncHttpClient

use of org.asynchttpclient.AsyncHttpClient in project async-http-client by AsyncHttpClient.

the class RetryNonBlockingIssue method testRetryNonBlockingAsyncConnect.

@Test(groups = "standalone")
public void testRetryNonBlockingAsyncConnect() throws IOException, InterruptedException, ExecutionException {
    AsyncHttpClientConfig config = //
    config().setKeepAlive(//
    true).setMaxConnections(//
    100).setConnectTimeout(//
    60000).setRequestTimeout(//
    30000).build();
    try (AsyncHttpClient client = asyncHttpClient(config)) {
        List<ListenableFuture<Response>> res = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            res.add(testMethodRequest(client, 3, "servlet", UUID.randomUUID().toString()));
        }
        StringBuilder b = new StringBuilder();
        for (ListenableFuture<Response> r : res) {
            Response theres = r.get();
            assertEquals(theres.getStatusCode(), 200);
            b.append("==============\r\n");
            b.append("Response Headers\r\n");
            HttpHeaders heads = theres.getHeaders();
            b.append(heads + "\r\n");
            b.append("==============\r\n");
        }
        System.out.println(b.toString());
        System.out.flush();
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ArrayList(java.util.ArrayList) AsyncHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig) ListenableFuture(org.asynchttpclient.ListenableFuture) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 82 with AsyncHttpClient

use of org.asynchttpclient.AsyncHttpClient in project async-http-client by AsyncHttpClient.

the class TimeToLiveIssue method testTTLBug.

@Test(enabled = false, description = "https://github.com/AsyncHttpClient/async-http-client/issues/1113")
public void testTTLBug() throws Throwable {
    try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setConnectionTtl(1).setPooledConnectionIdleTimeout(1))) {
        for (int i = 0; i < 200000; ++i) {
            Request request = new RequestBuilder().setUrl(String.format("http://localhost:%d/", port1)).build();
            Future<Response> future = client.executeRequest(request);
            future.get(5, TimeUnit.SECONDS);
            // from sometimes winning over poll for the ownership of a connection.
            if (System.currentTimeMillis() % 100 == 0) {
                Thread.sleep(5);
            }
        }
    }
}
Also used : Response(org.asynchttpclient.Response) RequestBuilder(org.asynchttpclient.RequestBuilder) Request(org.asynchttpclient.Request) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest) Test(org.testng.annotations.Test)

Example 83 with AsyncHttpClient

use of org.asynchttpclient.AsyncHttpClient in project async-http-client by AsyncHttpClient.

the class NettyReactiveStreamsTest method testRetryingOnFailingStream.

@Test(groups = "standalone")
public void testRetryingOnFailingStream() throws Exception {
    try (AsyncHttpClient client = asyncHttpClient()) {
        // allows us to wait until subscriber has received the first body chunk
        final CountDownLatch streamStarted = new CountDownLatch(1);
        // allows us to hold the subscriber from processing further body chunks
        final CountDownLatch streamOnHold = new CountDownLatch(1);
        // allows us to block until the request is being replayed ( this is what we want to test here!)
        final CountDownLatch replayingRequest = new CountDownLatch(1);
        // a ref to the publisher is needed to get a hold on the channel (if there is a better way, this should be changed) 
        final AtomicReference<StreamedResponsePublisher> publisherRef = new AtomicReference<>(null);
        // executing the request
        client.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new ReplayedSimpleAsyncHandler(replayingRequest, new BlockedStreamSubscriber(streamStarted, streamOnHold)) {

            @Override
            public State onStream(Publisher<HttpResponseBodyPart> publisher) {
                if (!(publisher instanceof StreamedResponsePublisher)) {
                    throw new IllegalStateException(String.format("publisher %s is expected to be an instance of %s", publisher, StreamedResponsePublisher.class));
                } else if (!publisherRef.compareAndSet(null, (StreamedResponsePublisher) publisher)) {
                    // abort on retry
                    return State.ABORT;
                }
                return super.onStream(publisher);
            }
        });
        // before proceeding, wait for the subscriber to receive at least one body chunk
        streamStarted.await();
        // The stream has started, hence `StreamedAsyncHandler.onStream(publisher)` was called, and `publisherRef` was initialized with the `publisher` passed to `onStream`
        assertTrue(publisherRef.get() != null, "Expected a not null publisher.");
        // close the channel to emulate a connection crash while the response body chunks were being received.
        StreamedResponsePublisher publisher = publisherRef.get();
        final CountDownLatch channelClosed = new CountDownLatch(1);
        getChannel(publisher).close().addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                channelClosed.countDown();
            }
        });
        // the subscriber is set free to process new incoming body chunks.
        streamOnHold.countDown();
        // the channel is confirmed to be closed
        channelClosed.await();
        // now we expect a new connection to be created and AHC retry logic to kick-in automatically
        // wait until we are notified the request is being replayed
        replayingRequest.await();
        // Change this if there is a better way of stating the test succeeded 
        assertTrue(true);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) StreamedResponsePublisher(org.asynchttpclient.netty.handler.StreamedResponsePublisher) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) ReactiveStreamsTest(org.asynchttpclient.reactivestreams.ReactiveStreamsTest)

Example 84 with AsyncHttpClient

use of org.asynchttpclient.AsyncHttpClient in project async-http-client by AsyncHttpClient.

the class NtlmTest method ntlmAuthTest.

private void ntlmAuthTest(Realm.Builder realmBuilder) throws IOException, InterruptedException, ExecutionException {
    try (AsyncHttpClient client = asyncHttpClient(config().setRealm(realmBuilder))) {
        Future<Response> responseFuture = client.executeRequest(get(getTargetUrl()));
        int status = responseFuture.get().getStatusCode();
        Assert.assertEquals(status, 200);
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient)

Example 85 with AsyncHttpClient

use of org.asynchttpclient.AsyncHttpClient in project async-http-client by AsyncHttpClient.

the class ProxyTest method testUseProxySelector.

// @Test(groups = "standalone")
public void testUseProxySelector() throws IOException, ExecutionException, TimeoutException, InterruptedException {
    ProxySelector originalProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {

        public List<Proxy> select(URI uri) {
            if (uri.getHost().equals("127.0.0.1")) {
                return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port1)));
            } else {
                return Arrays.asList(Proxy.NO_PROXY);
            }
        }

        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        }
    });
    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxySelector(true))) {
        String proxifiedTarget = "http://127.0.0.1:1234/";
        Future<Response> f = client.prepareGet(proxifiedTarget).execute();
        Response resp = f.get(3, TimeUnit.SECONDS);
        assertNotNull(resp);
        assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
        assertEquals(resp.getHeader("target"), "/");
        String nonProxifiedTarget = "http://localhost:1234/";
        f = client.prepareGet(nonProxifiedTarget).execute();
        try {
            f.get(3, TimeUnit.SECONDS);
            fail("should not be able to connect");
        } catch (ExecutionException e) {
        // ok, no proxy used
        }
    } finally {
        // FIXME not threadsafe
        ProxySelector.setDefault(originalProxySelector);
    }
}
Also used : ProxySelector(java.net.ProxySelector) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) List(java.util.List) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ExecutionException(java.util.concurrent.ExecutionException) URI(java.net.URI) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient)

Aggregations

AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)146 Test (org.testng.annotations.Test)119 Response (org.asynchttpclient.Response)71 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)66 HttpServletResponse (javax.servlet.http.HttpServletResponse)40 CountDownLatch (java.util.concurrent.CountDownLatch)31 DefaultAsyncHttpClient (org.asynchttpclient.DefaultAsyncHttpClient)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)23 RequestBuilder (org.asynchttpclient.RequestBuilder)16 IOException (java.io.IOException)14 RouteBuilder (org.apache.camel.builder.RouteBuilder)14 ExecutionException (java.util.concurrent.ExecutionException)13 Request (org.asynchttpclient.Request)13 WebSocket (org.asynchttpclient.ws.WebSocket)12 Test (org.junit.Test)11 AsyncHttpClientConfig (org.asynchttpclient.AsyncHttpClientConfig)10 File (java.io.File)9 WebSocketTextListener (org.asynchttpclient.ws.WebSocketTextListener)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7