Search in sources :

Example 26 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project async-http-client by AsyncHttpClient.

the class ResumableAsyncHandlerTest method testOnHeadersReceived.

@Test
public void testOnHeadersReceived() throws Exception {
    ResumableAsyncHandler handler = new ResumableAsyncHandler();
    HttpHeaders responseHeaders = new DefaultHttpHeaders();
    State status = handler.onHeadersReceived(responseHeaders);
    assertEquals(status, AsyncHandler.State.CONTINUE, "State should be CONTINUE for a successful onHeadersReceived");
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) State(org.asynchttpclient.AsyncHandler.State) Test(org.testng.annotations.Test)

Example 27 with HttpHeaders

use of org.apache.flink.shaded.netty4.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) HashMap(java.util.HashMap) 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) Map(java.util.Map) 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 28 with HttpHeaders

use of org.apache.flink.shaded.netty4.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) URLDecoder(java.net.URLDecoder) 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) URLEncoder(java.net.URLEncoder) 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) UnsupportedEncodingException(java.io.UnsupportedEncodingException) 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 29 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project async-http-client by AsyncHttpClient.

the class SimpleAsyncHttpClientTest method testSimpleTransferListener.

@Test
public void testSimpleTransferListener() throws Exception {
    final List<Error> errors = Collections.synchronizedList(new ArrayList<>());
    SimpleAHCTransferListener listener = new SimpleAHCTransferListener() {

        public void onStatus(Uri uri, int statusCode, String statusText) {
            try {
                assertEquals(statusCode, 200);
                assertEquals(uri.toUrl(), getTargetUrl());
            } catch (Error e) {
                errors.add(e);
                throw e;
            }
        }

        public void onHeaders(Uri uri, HttpHeaders headers) {
            try {
                assertEquals(uri.toUrl(), getTargetUrl());
                assertNotNull(headers);
                assertTrue(!headers.isEmpty());
                assertEquals(headers.get("X-Custom"), "custom");
            } catch (Error e) {
                errors.add(e);
                throw e;
            }
        }

        public void onCompleted(Uri uri, int statusCode, String statusText) {
            try {
                assertEquals(statusCode, 200);
                assertEquals(uri.toUrl(), getTargetUrl());
            } catch (Error e) {
                errors.add(e);
                throw e;
            }
        }

        public void onBytesSent(Uri uri, long amount, long current, long total) {
            try {
                assertEquals(uri.toUrl(), getTargetUrl());
            // FIXME Netty bug, see
            // https://github.com/netty/netty/issues/1855
            // assertEquals(total, MY_MESSAGE.getBytes().length);
            } catch (Error e) {
                errors.add(e);
                throw e;
            }
        }

        public void onBytesReceived(Uri uri, long amount, long current, long total) {
            try {
                assertEquals(uri.toUrl(), getTargetUrl());
                assertEquals(total, -1);
            } catch (Error e) {
                errors.add(e);
                throw e;
            }
        }
    };
    try (SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder().setUrl(getTargetUrl()).setHeader("Custom", "custom").setListener(listener).build()) {
        ByteArrayOutputStream o = new ByteArrayOutputStream(10);
        InputStreamBodyGenerator generator = new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes()));
        OutputStreamBodyConsumer consumer = new OutputStreamBodyConsumer(o);
        Future<Response> future = client.post(generator, consumer);
        Response response = future.get();
        if (!errors.isEmpty()) {
            for (Error e : errors) {
                e.printStackTrace();
            }
            throw errors.get(0);
        }
        assertEquals(response.getStatusCode(), 200);
        assertEquals(o.toString(), MY_MESSAGE);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Uri(org.asynchttpclient.uri.Uri) Response(org.asynchttpclient.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 30 with HttpHeaders

use of org.apache.flink.shaded.netty4.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)

Aggregations

HttpHeaders (io.netty.handler.codec.http.HttpHeaders)286 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)149 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)83 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)73 Test (org.junit.Test)68 Test (org.junit.jupiter.api.Test)57 Test (org.testng.annotations.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)43 HttpResponse (io.netty.handler.codec.http.HttpResponse)40 AsciiString (io.netty.util.AsciiString)29 ByteBuf (io.netty.buffer.ByteBuf)27 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)27 BStruct (org.ballerinalang.model.values.BStruct)26 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)22 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)22 HttpServletResponse (javax.servlet.http.HttpServletResponse)20 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)19 Cookie (io.netty.handler.codec.http.cookie.Cookie)19 BValue (org.ballerinalang.model.values.BValue)19 ChannelPromise (io.netty.channel.ChannelPromise)18