Search in sources :

Example 21 with HttpHeaders

use of 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 22 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project ambry by linkedin.

the class CopyForcingByteBuf method conversionWithGoodInputTest.

/**
 * Tests conversion of {@link HttpRequest} to {@link NettyRequest} given good input.
 * @throws RestServiceException
 */
@Test
public void conversionWithGoodInputTest() throws RestServiceException, CertificateException, SSLException {
    // headers
    HttpHeaders headers = new DefaultHttpHeaders(false);
    headers.add(HttpHeaderNames.CONTENT_LENGTH, new Random().nextInt(Integer.MAX_VALUE));
    headers.add("headerKey", "headerValue1");
    headers.add("headerKey", "headerValue2");
    headers.add("overLoadedKey", "headerOverloadedValue");
    headers.add("paramNoValueInUriButValueInHeader", "paramValueInHeader");
    // params
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    List<String> values = new ArrayList<String>(2);
    values.add("paramValue1");
    values.add("paramValue2");
    params.put("paramKey", values);
    values = new ArrayList<String>(1);
    values.add("paramOverloadedValue");
    params.put("overLoadedKey", values);
    params.put("paramNoValue", null);
    params.put("paramNoValueInUriButValueInHeader", null);
    params.put(BLACKLISTED_QUERY_PARAM, values);
    StringBuilder uriAttachmentBuilder = new StringBuilder("?");
    for (Map.Entry<String, List<String>> param : params.entrySet()) {
        if (param.getValue() != null) {
            for (String value : param.getValue()) {
                uriAttachmentBuilder.append(param.getKey()).append("=").append(value).append("&");
            }
        } else {
            uriAttachmentBuilder.append(param.getKey()).append("&");
        }
    }
    uriAttachmentBuilder.deleteCharAt(uriAttachmentBuilder.length() - 1);
    String uriAttachment = uriAttachmentBuilder.toString();
    NettyRequest nettyRequest;
    String uri;
    Set<Cookie> cookies = new HashSet<>();
    Cookie httpCookie = new DefaultCookie("CookieKey1", "CookieValue1");
    cookies.add(httpCookie);
    httpCookie = new DefaultCookie("CookieKey2", "CookieValue2");
    cookies.add(httpCookie);
    headers.add(RestUtils.Headers.COOKIE, getCookiesHeaderValue(cookies));
    for (MockChannel channel : Arrays.asList(new MockChannel(), new MockChannel().addSslHandlerToPipeline())) {
        uri = "/GET" + uriAttachment;
        nettyRequest = createNettyRequest(HttpMethod.GET, uri, headers, channel);
        validateRequest(nettyRequest, RestMethod.GET, uri, headers, params, cookies, channel);
        closeRequestAndValidate(nettyRequest, channel);
        RecvByteBufAllocator savedAllocator = channel.config().getRecvByteBufAllocator();
        int[] bufferWatermarks = { -1, 0, 1, DEFAULT_WATERMARK };
        for (int bufferWatermark : bufferWatermarks) {
            NettyRequest.bufferWatermark = bufferWatermark;
            uri = "/POST" + uriAttachment;
            nettyRequest = createNettyRequest(HttpMethod.POST, uri, headers, channel);
            validateRequest(nettyRequest, RestMethod.POST, uri, headers, params, cookies, channel);
            if (bufferWatermark > 0) {
                assertTrue("RecvAllocator should have changed", channel.config().getRecvByteBufAllocator() instanceof DefaultMaxBytesRecvByteBufAllocator);
            } else {
                assertEquals("RecvAllocator not as expected", savedAllocator, channel.config().getRecvByteBufAllocator());
            }
            closeRequestAndValidate(nettyRequest, channel);
            assertEquals("Allocator not as expected", savedAllocator, channel.config().getRecvByteBufAllocator());
        }
        for (int bufferWatermark : bufferWatermarks) {
            NettyRequest.bufferWatermark = bufferWatermark;
            uri = "/PUT" + uriAttachment;
            nettyRequest = createNettyRequest(HttpMethod.PUT, uri, headers, channel);
            validateRequest(nettyRequest, RestMethod.PUT, uri, headers, params, cookies, channel);
            if (bufferWatermark > 0) {
                assertTrue("RecvAllocator should have changed", channel.config().getRecvByteBufAllocator() instanceof DefaultMaxBytesRecvByteBufAllocator);
            } else {
                assertEquals("RecvAllocator not as expected", savedAllocator, channel.config().getRecvByteBufAllocator());
            }
            closeRequestAndValidate(nettyRequest, channel);
            assertEquals("Allocator not as expected", savedAllocator, channel.config().getRecvByteBufAllocator());
        }
        NettyRequest.bufferWatermark = DEFAULT_WATERMARK;
        uri = "/DELETE" + uriAttachment;
        nettyRequest = createNettyRequest(HttpMethod.DELETE, uri, headers, channel);
        validateRequest(nettyRequest, RestMethod.DELETE, uri, headers, params, cookies, channel);
        closeRequestAndValidate(nettyRequest, channel);
        uri = "/HEAD" + uriAttachment;
        nettyRequest = createNettyRequest(HttpMethod.HEAD, uri, headers, channel);
        validateRequest(nettyRequest, RestMethod.HEAD, uri, headers, params, cookies, channel);
        closeRequestAndValidate(nettyRequest, channel);
        uri = "/OPTIONS" + uriAttachment;
        nettyRequest = createNettyRequest(HttpMethod.OPTIONS, uri, headers, channel);
        validateRequest(nettyRequest, RestMethod.OPTIONS, uri, headers, params, cookies, channel);
        closeRequestAndValidate(nettyRequest, channel);
    }
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultMaxBytesRecvByteBufAllocator(io.netty.channel.DefaultMaxBytesRecvByteBufAllocator) RecvByteBufAllocator(io.netty.channel.RecvByteBufAllocator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DefaultMaxBytesRecvByteBufAllocator(io.netty.channel.DefaultMaxBytesRecvByteBufAllocator) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) Random(java.util.Random) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 23 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project ambry by linkedin.

the class CopyForcingByteBuf method keepAliveTest.

@Test
public void keepAliveTest() throws RestServiceException {
    NettyRequest request = createNettyRequest(HttpMethod.GET, "/", null, new MockChannel());
    // by default, keep-alive is true for HTTP 1.1
    assertTrue("Keep-alive not as expected", request.isKeepAlive());
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    request = createNettyRequest(HttpMethod.GET, "/", headers, new MockChannel());
    assertTrue("Keep-alive not as expected", request.isKeepAlive());
    headers = new DefaultHttpHeaders();
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    request = createNettyRequest(HttpMethod.GET, "/", headers, new MockChannel());
    assertFalse("Keep-alive not as expected", request.isKeepAlive());
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Test(org.junit.Test)

Example 24 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project ambry by linkedin.

the class CopyForcingByteBuf method sizeInHeaderLessThanContentTest.

/**
 * Tests reaction of NettyRequest when content size is more than the size specified in the headers.
 * @throws Exception
 */
private void sizeInHeaderLessThanContentTest() throws Exception {
    List<HttpContent> httpContents = new ArrayList<HttpContent>();
    ByteBuffer content = generateContent(httpContents);
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    int lastHttpContentSize = httpContents.get(httpContents.size() - 1).content().readableBytes();
    httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, content.limit() - lastHttpContentSize - 1);
    doHeaderAndContentSizeMismatchTest(httpHeaders, httpContents);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) ArrayList(java.util.ArrayList) ByteBuffer(java.nio.ByteBuffer) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 25 with HttpHeaders

use of io.netty.handler.codec.http.HttpHeaders in project ambry by linkedin.

the class ChannelWriteCallback method errorResponseTest.

/**
 * Tests that error responses are correctly formed.
 */
@Test
public void errorResponseTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    for (RestServiceErrorCode errorCode : RestServiceErrorCode.values()) {
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, errorCode);
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.HEAD, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders));
        HttpResponse response = channel.readOutbound();
        HttpResponseStatus expectedStatus = getExpectedHttpResponseStatus(errorCode);
        assertEquals("Unexpected response status", expectedStatus, response.status());
        boolean containsFailureReasonHeader = response.headers().contains(NettyResponseChannel.FAILURE_REASON_HEADER);
        if (expectedStatus == HttpResponseStatus.BAD_REQUEST) {
            assertTrue("Could not find failure reason header.", containsFailureReasonHeader);
        } else {
            assertFalse("Should not have found failure reason header.", containsFailureReasonHeader);
        }
        if (HttpStatusClass.CLIENT_ERROR.contains(response.status().code())) {
            assertEquals("Wrong error code", errorCode, RestServiceErrorCode.valueOf(response.headers().get(NettyResponseChannel.ERROR_CODE_HEADER)));
        } else {
            assertFalse("Should not have found error code header", response.headers().contains(NettyResponseChannel.ERROR_CODE_HEADER));
        }
        if (response instanceof FullHttpResponse) {
            // assert that there is no content
            assertEquals("The response should not contain content", 0, ((FullHttpResponse) response).content().readableBytes());
        } else {
            HttpContent content = channel.readOutbound();
            assertTrue("End marker should be received", content instanceof LastHttpContent);
        }
        assertNull("There should be no more data in the channel", channel.readOutbound());
        boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(expectedStatus);
        assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive());
        assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpUtil.isKeepAlive(response));
        if (!shouldBeAlive) {
            channel = createEmbeddedChannel();
        }
    }
    channel.close();
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) UtilsTest(com.github.ambry.utils.UtilsTest) Test(org.junit.Test)

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