Search in sources :

Example 41 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project async-http-client by AsyncHttpClient.

the class AsyncStreamHandlerTest method asyncStreamJustStatusLine.

@Test(timeOut = 3000)
public void asyncStreamJustStatusLine() throws Throwable {
    withClient().run(client -> withServer(server).run(server -> {
        server.enqueueEcho();
        final int STATUS = 0;
        final int COMPLETED = 1;
        final int OTHER = 2;
        final boolean[] whatCalled = new boolean[] { false, false, false };
        final CountDownLatch latch = new CountDownLatch(1);
        Future<Integer> statusCode = client.prepareGet(getTargetUrl()).execute(new AsyncHandler<Integer>() {

            private int status = -1;

            @Override
            public void onThrowable(Throwable t) {
                whatCalled[OTHER] = true;
                latch.countDown();
            }

            @Override
            public State onBodyPartReceived(HttpResponseBodyPart bodyPart) {
                whatCalled[OTHER] = true;
                latch.countDown();
                return State.ABORT;
            }

            @Override
            public State onStatusReceived(HttpResponseStatus responseStatus) {
                whatCalled[STATUS] = true;
                status = responseStatus.getStatusCode();
                latch.countDown();
                return State.ABORT;
            }

            @Override
            public State onHeadersReceived(HttpHeaders headers) {
                whatCalled[OTHER] = true;
                latch.countDown();
                return State.ABORT;
            }

            @Override
            public Integer onCompleted() {
                whatCalled[COMPLETED] = true;
                latch.countDown();
                return status;
            }
        });
        if (!latch.await(2, TimeUnit.SECONDS)) {
            fail("Timeout");
            return;
        }
        Integer status = statusCode.get(TIMEOUT, TimeUnit.SECONDS);
        assertEquals((int) status, 200, "Expected status code failed.");
        if (!whatCalled[STATUS]) {
            fail("onStatusReceived not called.");
        }
        if (!whatCalled[COMPLETED]) {
            fail("onCompleted not called.");
        }
        if (whatCalled[OTHER]) {
            fail("Other method of AsyncHandler got called.");
        }
    }));
}
Also used : AfterClass(org.testng.annotations.AfterClass) ThrowableUtil.unknownStackTrace(org.asynchttpclient.util.ThrowableUtil.unknownStackTrace) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) BeforeClass(org.testng.annotations.BeforeClass) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.testng.annotations.Test) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestUtils(org.asynchttpclient.test.TestUtils) TimeUnit(java.util.concurrent.TimeUnit) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) CountDownLatch(java.util.concurrent.CountDownLatch) Future(java.util.concurrent.Future) Assert(org.testng.Assert) Dsl.config(org.asynchttpclient.Dsl.config) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpServer(org.asynchttpclient.testserver.HttpServer) HttpTest(org.asynchttpclient.testserver.HttpTest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Future(java.util.concurrent.Future) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test) HttpTest(org.asynchttpclient.testserver.HttpTest)

Example 42 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project async-http-client by AsyncHttpClient.

the class AsyncStreamLifecycleTest method testStream.

@Test
public void testStream() throws Exception {
    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 {
                if (e.length() != 0) {
                    String s = new String(e.getBodyPartBytes());
                    logger.info("got part: {}", s);
                    queue.put(s);
                }
                return State.CONTINUE;
            }

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

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

            public Object onCompleted() {
                latch.countDown();
                return null;
            }
        });
        assertTrue(latch.await(1, TimeUnit.SECONDS), "Latch failed.");
        assertFalse(err.get());
        assertEquals(queue.size(), 2);
        assertTrue(queue.contains("part1"));
        assertTrue(queue.contains("part2"));
        assertTrue(status.get());
        assertEquals(headers.get(), 1);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.testng.annotations.Test)

Example 43 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project async-http-client by AsyncHttpClient.

the class BasicHttpTest method postUnboundedInputStreamAsBodyStream.

@Test
public void postUnboundedInputStreamAsBodyStream() throws Throwable {
    withClient().run(client -> withServer(server).run(server -> {
        HttpHeaders h = new DefaultHttpHeaders();
        h.add(CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
        server.enqueue(new AbstractHandler() {

            EchoHandler chain = new EchoHandler();

            @Override
            public void handle(String target, org.eclipse.jetty.server.Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
                assertEquals(request.getHeader(TRANSFER_ENCODING.toString()), HttpHeaderValues.CHUNKED.toString());
                assertNull(request.getHeader(CONTENT_LENGTH.toString()));
                chain.handle(target, request, httpServletRequest, httpServletResponse);
            }
        });
        server.enqueueEcho();
        client.preparePost(getTargetUrl()).setHeaders(h).setBody(new ByteArrayInputStream("{}".getBytes(StandardCharsets.ISO_8859_1))).execute(new AsyncCompletionHandlerAdapter() {

            @Override
            public Response onCompleted(Response response) {
                assertEquals(response.getStatusCode(), 200);
                assertEquals(response.getResponseBody(), "{}");
                return response;
            }
        }).get(TIMEOUT, SECONDS);
    }));
}
Also used : java.util(java.util) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ServletException(javax.servlet.ServletException) EchoHandler(org.asynchttpclient.testserver.HttpServer.EchoHandler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.testng.annotations.Test) EventCollectingHandler(org.asynchttpclient.test.EventCollectingHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpServletRequest(javax.servlet.http.HttpServletRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) Assert(org.testng.Assert) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectException(java.net.ConnectException) HttpServer(org.asynchttpclient.testserver.HttpServer) AfterClass(org.testng.annotations.AfterClass) ThrowableUtil.unknownStackTrace(org.asynchttpclient.util.ThrowableUtil.unknownStackTrace) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) java.util.concurrent(java.util.concurrent) UTF_8(java.nio.charset.StandardCharsets.UTF_8) BeforeClass(org.testng.annotations.BeforeClass) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Cookie(io.netty.handler.codec.http.cookie.Cookie) UnknownHostException(java.net.UnknownHostException) TestUtils(org.asynchttpclient.test.TestUtils) StandardCharsets(java.nio.charset.StandardCharsets) DateUtils.unpreciseMillisTime(org.asynchttpclient.util.DateUtils.unpreciseMillisTime) SSLException(javax.net.ssl.SSLException) MaxRedirectException(org.asynchttpclient.handler.MaxRedirectException) Dsl(org.asynchttpclient.Dsl) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) StringPart(org.asynchttpclient.request.body.multipart.StringPart) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpTest(org.asynchttpclient.testserver.HttpTest) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) EchoHandler(org.asynchttpclient.testserver.HttpServer.EchoHandler) Test(org.testng.annotations.Test) HttpTest(org.asynchttpclient.testserver.HttpTest)

Example 44 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project dubbo by alibaba.

the class HttpProcessHandler method http_200.

private static final FullHttpResponse http_200(String result) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(result.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 45 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project dubbo by alibaba.

the class HttpProcessHandler method http_500.

private static final FullHttpResponse http_500(String errorMessage) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(errorMessage.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Aggregations

HttpHeaders (io.netty.handler.codec.http.HttpHeaders)248 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)119 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)67 Test (org.junit.Test)61 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)56 Test (org.testng.annotations.Test)51 Test (org.junit.jupiter.api.Test)50 HttpRequest (io.netty.handler.codec.http.HttpRequest)33 AsciiString (io.netty.util.AsciiString)29 ByteBuf (io.netty.buffer.ByteBuf)27 BStruct (org.ballerinalang.model.values.BStruct)26 HttpResponse (io.netty.handler.codec.http.HttpResponse)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)21 Cookie (io.netty.handler.codec.http.cookie.Cookie)20 HttpServletResponse (javax.servlet.http.HttpServletResponse)20 BValue (org.ballerinalang.model.values.BValue)19 ChannelPromise (io.netty.channel.ChannelPromise)18 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)18 BString (org.ballerinalang.model.values.BString)18 DefaultCookie (io.netty.handler.codec.http.cookie.DefaultCookie)17