use of io.netty.handler.codec.http.HttpResponseStatus 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();
}
use of io.netty.handler.codec.http.HttpResponseStatus in project turbo-rpc by hank-whu.
the class RestHttResponseEncoder method write.
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (!(msg instanceof RestHttpResponse)) {
ctx.write(msg, promise);
return;
}
RestHttpResponse restHttpResponse = (RestHttpResponse) msg;
HttpResponseStatus status = restHttpResponse.getStatus();
if (status == null) {
status = INTERNAL_SERVER_ERROR;
}
if (restHttpResponse.getResult() == null) {
status = INTERNAL_SERVER_ERROR;
restHttpResponse.setStatus(status);
restHttpResponse.setResult("UNKNOWN");
}
doResponse(ctx, promise, restHttpResponse);
}
use of io.netty.handler.codec.http.HttpResponseStatus in project java by wavefrontHQ.
the class OpenTSDBPortUnificationHandler method handleHttpMessage.
/**
* Handles an incoming HTTP message. The currently supported paths are:
* {@link <ahref="http://opentsdb.net/docs/build/html/api_http/put.html">/api/put</a>}
* {@link <ahref="http://opentsdb.net/docs/build/html/api_http/version.html">/api/version</a>},
*
* @throws IOException when reading contents of HTTP body fails
* @throws URISyntaxException when the request URI cannot be parsed
*/
private void handleHttpMessage(final ChannelHandlerContext ctx, final Object message) {
final FullHttpRequest request = (FullHttpRequest) message;
URI uri;
try {
uri = new URI(request.uri());
} catch (URISyntaxException e) {
String errMsg = createErrMsg(e);
writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, errMsg);
blockMessage("WF-300", "Request URI, '" + request.uri() + "' cannot be parsed", e, ctx);
return;
}
if (uri.getPath().equals("/api/put")) {
final ObjectMapper jsonTree = new ObjectMapper();
HttpResponseStatus status;
String content = "";
// were stored successfully. If one or more data points had an error, the API will return a 400.
try {
if (reportMetrics(jsonTree.readTree(request.content().toString(CharsetUtil.UTF_8)))) {
status = HttpResponseStatus.NO_CONTENT;
} else {
// TODO: improve error message
// http://opentsdb.net/docs/build/html/api_http/put.html#response
// User should understand that successful points are processed and the reason for BAD_REQUEST
// is due to at least one failure point.
status = HttpResponseStatus.BAD_REQUEST;
content = "At least one data point had error.";
}
} catch (Exception e) {
status = HttpResponseStatus.BAD_REQUEST;
if (e != null) {
content = createErrMsg(e);
}
blockMessage("WF-300", "Failed to handle /api/put request", e, ctx);
}
writeHttpResponse(request, ctx, status, content);
} else if (uri.getPath().equals("/api/version")) {
writeHttpResponse(request, ctx, HttpResponseStatus.OK, // TODO: should be a JSON response object (see docs)
"Wavefront OpenTSDB Endpoint");
// http://opentsdb.net/docs/build/html/api_http/version.html
} else {
writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported path");
blockMessage("WF-300", "Unexpected path '" + request.uri() + "'", null, ctx);
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project cdap by caskdata.
the class NettyRouterPipelineTest method testHttpPipelining.
@Test
public void testHttpPipelining() throws Exception {
final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
EventLoopGroup eventGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
responseStatuses.add(((HttpResponse) msg).status());
}
ReferenceCountUtil.release(msg);
}
});
}
});
// Create a connection and make five consecutive HTTP call without waiting for the first to respond
Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
for (int i = 0; i < 5; i++) {
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
channel.writeAndFlush(request);
}
// Should get the first response as normal one
HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpResponseStatus.OK, status);
// The rest four should be failure responses
for (int i = 0; i < 4; i++) {
Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
}
eventGroup.shutdownGracefully();
channel.close();
Assert.assertTrue(responseStatuses.isEmpty());
}
use of io.netty.handler.codec.http.HttpResponseStatus in project xian by happyyangyuan.
the class DefaultExceptionHandler method exceptionCaught.
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.error("Exception caught", cause);
HttpResponseStatus status = (cause instanceof BadRequestException) ? BAD_REQUEST : INTERNAL_SERVER_ERROR;
String content = StringUtil.getExceptionStacktrace(cause);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));
response.headers().set(CONTENT_TYPE, Config.getContentType());
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
/*ctx.writeAndFlush(response); todo 爆了异常之后,这里根本写不进去,直接查日志吧!*/
ctx.close();
LOG.warn("TODO: 16/9/10 目前是出现了异常则直接关闭,这样对长连接稳定性好像不太有利");
MsgIdHolder.clear();
}
Aggregations