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);
}
}
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);
}
}
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());
}
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);
}
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();
}
Aggregations