Search in sources :

Example 6 with HttpResponseStatus

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

Example 7 with HttpResponseStatus

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);
}
Also used : RestHttpResponse(rpc.turbo.transport.server.rest.protocol.RestHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 8 with HttpResponseStatus

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);
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 9 with HttpResponseStatus

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());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 10 with HttpResponseStatus

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();
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) BadRequestException(info.xiancloud.nettyhttpserver.http.bean.BadRequestException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Aggregations

HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)53 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)16 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)15 ByteBuf (io.netty.buffer.ByteBuf)14 HttpResponse (io.netty.handler.codec.http.HttpResponse)9 HttpVersion (io.netty.handler.codec.http.HttpVersion)8 IOException (java.io.IOException)8 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)7 HttpMethod (io.netty.handler.codec.http.HttpMethod)7 Test (org.junit.Test)7 Map (java.util.Map)5 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)4 HttpRequest (io.netty.handler.codec.http.HttpRequest)4 NoSuchElementException (java.util.NoSuchElementException)4 ChannelFuture (io.netty.channel.ChannelFuture)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)3 PrintWriter (java.io.PrintWriter)3 List (java.util.List)3 Unpooled (io.netty.buffer.Unpooled)2