Search in sources :

Example 6 with HttpResponseBodyPart

use of org.asynchttpclient.HttpResponseBodyPart 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 7 with HttpResponseBodyPart

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

the class EmptyBodyTest method testEmptyBody.

@Test(groups = "standalone")
public void testEmptyBody() throws IOException {
    try (AsyncHttpClient ahc = asyncHttpClient()) {
        final AtomicBoolean err = new AtomicBoolean(false);
        final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
        final AtomicBoolean status = new AtomicBoolean(false);
        final AtomicInteger headers = new AtomicInteger(0);
        final CountDownLatch latch = new CountDownLatch(1);
        ahc.executeRequest(ahc.prepareGet(getTargetUrl()).build(), new AsyncHandler<Object>() {

            public void onThrowable(Throwable t) {
                fail("Got throwable.", t);
                err.set(true);
            }

            public State onBodyPartReceived(HttpResponseBodyPart e) throws Exception {
                byte[] bytes = e.getBodyPartBytes();
                if (bytes.length != 0) {
                    String s = new String(bytes);
                    logger.info("got part: {}", s);
                    logger.warn("Sampling stacktrace.", new Throwable("trace that, we should not get called for empty body."));
                    queue.put(s);
                }
                return State.CONTINUE;
            }

            public State onStatusReceived(HttpResponseStatus e) throws Exception {
                status.set(true);
                return AsyncHandler.State.CONTINUE;
            }

            public State onHeadersReceived(HttpResponseHeaders e) throws Exception {
                if (headers.incrementAndGet() == 2) {
                    throw new Exception("Analyze this.");
                }
                return State.CONTINUE;
            }

            public Object onCompleted() throws Exception {
                latch.countDown();
                return null;
            }
        });
        try {
            assertTrue(latch.await(1, TimeUnit.SECONDS), "Latch failed.");
        } catch (InterruptedException e) {
            fail("Interrupted.", e);
        }
        assertFalse(err.get());
        assertEquals(queue.size(), 0);
        assertTrue(status.get());
        assertEquals(headers.get(), 1);
    }
}
Also used : HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 8 with HttpResponseBodyPart

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

the class ResumableAsyncHandlerTest method testOnBodyPartReceivedWithDecoratedAsyncHandler.

@Test
public void testOnBodyPartReceivedWithDecoratedAsyncHandler() throws Exception {
    HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
    when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
    ByteBuffer buffer = ByteBuffer.allocate(0);
    when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);
    @SuppressWarnings("unchecked") AsyncHandler<Response> decoratedAsyncHandler = mock(AsyncHandler.class);
    State mockState = mock(State.class);
    when(decoratedAsyncHandler.onBodyPartReceived(bodyPart)).thenReturn(mockState);
    // following is needed to set the url variable
    HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
    when(mockResponseStatus.getStatusCode()).thenReturn(200);
    Uri mockUri = mock(Uri.class);
    when(mockUri.toUrl()).thenReturn("http://non.null");
    when(mockResponseStatus.getUri()).thenReturn(mockUri);
    ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);
    handler.onStatusReceived(mockResponseStatus);
    State state = handler.onBodyPartReceived(bodyPart);
    assertEquals(state, mockState, "State should be equal to the state returned from decoratedAsyncHandler");
}
Also used : Response(org.asynchttpclient.Response) State(org.asynchttpclient.AsyncHandler.State) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) ByteBuffer(java.nio.ByteBuffer) Uri(org.asynchttpclient.uri.Uri) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 9 with HttpResponseBodyPart

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

the class ResumableAsyncHandlerTest method testOnBodyPartReceived.

@Test
public void testOnBodyPartReceived() throws Exception {
    ResumableAsyncHandler handler = new ResumableAsyncHandler();
    HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
    when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
    ByteBuffer buffer = ByteBuffer.allocate(0);
    when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);
    State state = handler.onBodyPartReceived(bodyPart);
    assertEquals(state, AsyncHandler.State.CONTINUE, "State should be CONTINUE for a successful onBodyPartReceived");
}
Also used : State(org.asynchttpclient.AsyncHandler.State) ByteBuffer(java.nio.ByteBuffer) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 10 with HttpResponseBodyPart

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

the class NettyResponse method getResponseBodyAsByteBuffer.

@Override
public ByteBuffer getResponseBodyAsByteBuffer() {
    int length = 0;
    for (HttpResponseBodyPart part : bodyParts) length += part.length();
    ByteBuffer target = ByteBuffer.wrap(new byte[length]);
    for (HttpResponseBodyPart part : bodyParts) target.put(part.getBodyPartBytes());
    target.flip();
    return target;
}
Also used : ByteBuffer(java.nio.ByteBuffer) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart)

Aggregations

HttpResponseBodyPart (org.asynchttpclient.HttpResponseBodyPart)10 Test (org.testng.annotations.Test)7 AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)4 HttpResponseHeaders (org.asynchttpclient.HttpResponseHeaders)4 HttpResponseStatus (org.asynchttpclient.HttpResponseStatus)4 ByteBuffer (java.nio.ByteBuffer)3 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)3 State (org.asynchttpclient.AsyncHandler.State)3 Response (org.asynchttpclient.Response)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 ByteBuf (io.netty.buffer.ByteBuf)2 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 IOException (java.io.IOException)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 AsyncHandler (org.asynchttpclient.AsyncHandler)2 BasicHttpsTest (org.asynchttpclient.BasicHttpsTest)2 Channel (io.netty.channel.Channel)1