Search in sources :

Example 6 with HttpResponseStatus

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

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

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

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

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

the class WebSocketHandler method handleRead.

@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
    if (e instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e;
        if (logger.isDebugEnabled()) {
            HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
            logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
        }
        WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
        HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
        HttpResponseHeaders responseHeaders = new HttpResponseHeaders(response.headers());
        if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
            switch(handler.onStatusReceived(status)) {
                case CONTINUE:
                    upgrade(channel, future, handler, response, responseHeaders);
                    break;
                default:
                    abort(channel, future, handler, status);
            }
        }
    } else if (e instanceof WebSocketFrame) {
        final WebSocketFrame frame = (WebSocketFrame) e;
        WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
        NettyWebSocket webSocket = handler.onCompleted();
        // retain because we might buffer the frame
        if (webSocket.isReady()) {
            webSocket.handleFrame(frame);
        } else {
            // WebSocket hasn't been open yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
            // as we want to keep sequential order (but can't notify user of open before upgrading so he doesn't to try send immediately), we have to buffer
            webSocket.bufferFrame(frame);
        }
    } else if (!(e instanceof LastHttpContent)) {
        // ignore, end of handshake response
        logger.error("Invalid message {}", e);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) NettyResponseStatus(org.asynchttpclient.netty.NettyResponseStatus) HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) NettyWebSocket(org.asynchttpclient.netty.ws.NettyWebSocket) HttpResponse(io.netty.handler.codec.http.HttpResponse) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) WebSocketUpgradeHandler(org.asynchttpclient.ws.WebSocketUpgradeHandler) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Aggregations

HttpResponseStatus (org.asynchttpclient.HttpResponseStatus)10 Test (org.testng.annotations.Test)9 State (org.asynchttpclient.AsyncHandler.State)5 Response (org.asynchttpclient.Response)5 Uri (org.asynchttpclient.uri.Uri)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)4 HttpResponseBodyPart (org.asynchttpclient.HttpResponseBodyPart)4 HttpResponseHeaders (org.asynchttpclient.HttpResponseHeaders)4 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)3 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 AsyncHandler (org.asynchttpclient.AsyncHandler)2 BasicHttpsTest (org.asynchttpclient.BasicHttpsTest)2 HttpRequest (io.netty.handler.codec.http.HttpRequest)1 HttpResponse (io.netty.handler.codec.http.HttpResponse)1 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)1 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)1 IOException (java.io.IOException)1