Search in sources :

Example 1 with HttpResponseBodyPart

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

the class ResumableAsyncHandlerTest method testOnBodyPartReceivedWithResumableListenerThrowsException.

@Test
public void testOnBodyPartReceivedWithResumableListenerThrowsException() throws Exception {
    ResumableAsyncHandler handler = new ResumableAsyncHandler();
    ResumableListener resumableListener = PowerMockito.mock(ResumableListener.class);
    doThrow(new IOException()).when(resumableListener).onBytesReceived(anyObject());
    handler.setResumableListener(resumableListener);
    HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
    State state = handler.onBodyPartReceived(bodyPart);
    assertEquals(state, AsyncHandler.State.ABORT, "State should be ABORT if the resumableListener threw an exception in onBodyPartReceived");
}
Also used : State(org.asynchttpclient.AsyncHandler.State) IOException(java.io.IOException) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 2 with HttpResponseBodyPart

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

the class ZeroCopyFileTest method zeroCopyFileTest.

@Test(groups = "standalone")
public void zeroCopyFileTest() throws IOException, ExecutionException, TimeoutException, InterruptedException, URISyntaxException {
    File tmp = new File(System.getProperty("java.io.tmpdir") + File.separator + "zeroCopy.txt");
    tmp.deleteOnExit();
    try (AsyncHttpClient client = asyncHttpClient()) {
        try (FileOutputStream stream = new FileOutputStream(tmp)) {
            Response resp = client.preparePost("http://localhost:" + port1 + "/").setBody(SIMPLE_TEXT_FILE).execute(new AsyncHandler<Response>() {

                public void onThrowable(Throwable t) {
                }

                public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                    stream.write(bodyPart.getBodyPartBytes());
                    return State.CONTINUE;
                }

                public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                    return State.CONTINUE;
                }

                public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                    return State.CONTINUE;
                }

                public Response onCompleted() throws Exception {
                    return null;
                }
            }).get();
            assertNull(resp);
            assertEquals(SIMPLE_TEXT_FILE.length(), tmp.length());
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) AsyncHandler(org.asynchttpclient.AsyncHandler) HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) FileOutputStream(java.io.FileOutputStream) File(java.io.File) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) BasicHttpsTest(org.asynchttpclient.BasicHttpsTest) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 3 with HttpResponseBodyPart

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

the class ZeroCopyFileTest method zeroCopyFileWithBodyManipulationTest.

@Test(groups = "standalone")
public void zeroCopyFileWithBodyManipulationTest() throws IOException, ExecutionException, TimeoutException, InterruptedException, URISyntaxException {
    File tmp = new File(System.getProperty("java.io.tmpdir") + File.separator + "zeroCopy.txt");
    tmp.deleteOnExit();
    try (AsyncHttpClient client = asyncHttpClient()) {
        try (FileOutputStream stream = new FileOutputStream(tmp)) {
            Response resp = client.preparePost("http://localhost:" + port1 + "/").setBody(SIMPLE_TEXT_FILE).execute(new AsyncHandler<Response>() {

                public void onThrowable(Throwable t) {
                }

                public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                    stream.write(bodyPart.getBodyPartBytes());
                    if (bodyPart.getBodyPartBytes().length == 0) {
                        return State.ABORT;
                    }
                    return State.CONTINUE;
                }

                public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                    return State.CONTINUE;
                }

                public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                    return State.CONTINUE;
                }

                public Response onCompleted() throws Exception {
                    return null;
                }
            }).get();
            assertNull(resp);
            assertEquals(SIMPLE_TEXT_FILE.length(), tmp.length());
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) AsyncHandler(org.asynchttpclient.AsyncHandler) HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) FileOutputStream(java.io.FileOutputStream) File(java.io.File) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) BasicHttpsTest(org.asynchttpclient.BasicHttpsTest) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 4 with HttpResponseBodyPart

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

the class AsyncHttpClientHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);
    try {
        if (attribute instanceof OnLastHttpContentCallback && msg instanceof LastHttpContent) {
            ((OnLastHttpContentCallback) attribute).call();
        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            future.touch();
            handleRead(channel, future, msg);
        } else if (attribute instanceof StreamedResponsePublisher) {
            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;
            publisher.future().touch();
            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.readableBytes() > 0) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content, false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.INSTANCE) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute, msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : Channel(io.netty.channel.Channel) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart)

Example 5 with HttpResponseBodyPart

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

the class HttpHandler method handleChunk.

private //
void handleChunk(//
HttpContent chunk, //
final Channel channel, //
final NettyResponseFuture<?> future, AsyncHandler<?> handler) throws IOException, Exception {
    boolean abort = false;
    boolean last = chunk instanceof LastHttpContent;
    // Netty 4: the last chunk is not empty
    if (last) {
        LastHttpContent lastChunk = (LastHttpContent) chunk;
        HttpHeaders trailingHeaders = lastChunk.trailingHeaders();
        if (!trailingHeaders.isEmpty()) {
            abort = handler.onHeadersReceived(new HttpResponseHeaders(trailingHeaders, true)) == State.ABORT;
        }
    }
    ByteBuf buf = chunk.content();
    if (!abort && !(handler instanceof StreamedAsyncHandler) && (buf.readableBytes() > 0 || last)) {
        HttpResponseBodyPart bodyPart = config.getResponseBodyPartFactory().newResponseBodyPart(buf, last);
        abort = handler.onBodyPartReceived(bodyPart) == State.ABORT;
    }
    if (abort || last) {
        boolean keepAlive = !abort && future.isKeepAlive();
        finishUpdate(future, channel, keepAlive, !last);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) StreamedAsyncHandler(org.asynchttpclient.handler.StreamedAsyncHandler) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) 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