Search in sources :

Example 36 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project turbo-rpc by hank-whu.

the class RestHttResponseEncoder method doResponse.

private void doResponse(ChannelHandlerContext ctx, ChannelPromise promise, RestHttpResponse restHttpResponse) {
    ByteBuf buffer = ctx.alloc().ioBuffer();
    Object msg = restHttpResponse.getResult();
    HttpResponseStatus status = restHttpResponse.getStatus();
    boolean keepAlive = restHttpResponse.isKeepAlive();
    Throwable throwable = null;
    if (msg == null) {
        buffer.writeBytes(UnsafeStringUtils.getUTF8Bytes(""));
    } else if (msg instanceof Throwable) {
        throwable = (Throwable) msg;
        buffer.writeBytes(UnsafeStringUtils.getUTF8Bytes(throwable.getMessage()));
    } else {
        try {
            jsonMapper.write(buffer, msg);
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, buffer, false);
            response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        } catch (Throwable e) {
            if (logger.isWarnEnabled()) {
                logger.warn("error ", e);
            }
            status = INTERNAL_SERVER_ERROR;
            buffer.clear();
            buffer.writeBytes(UnsafeStringUtils.getUTF8Bytes(e.getMessage()));
        }
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, buffer, false);
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
    doResponseFilter(ctx, restHttpResponse.getRequest(), response, restHttpResponse.getInvoker(), throwable);
    if (keepAlive) {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response, promise);
    } else {
        ctx.write(response, promise).addListener(CLOSE);
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 37 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project ratpack by ratpack.

the class DefaultDevelopmentErrorHandler method error.

/**
 * Prints the string "Client error «statusCode»" to the response as text with the given status code.
 *
 * @param ctx The ctx
 * @param statusCode The 4xx status code that explains the problem
 */
@Override
public void error(Context ctx, int statusCode) throws Exception {
    HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
    Request request = ctx.getRequest();
    LOGGER.error(statusCode + " client error for request to " + request.getRawUri());
    ctx.getResponse().status(statusCode);
    ctx.byContent(s -> s.plainText(() -> ctx.render("Client error " + statusCode)).html(() -> new ErrorPageRenderer() {

        protected void render() {
            render(ctx, status.reasonPhrase(), w -> messages(w, "Client Error", () -> meta(w, m -> m.put("URI:", request.getRawUri()).put("Method:", request.getMethod().getName()).put("Status Code:", status.code()).put("Phrase:", status.reasonPhrase()))));
        }
    }).noMatch("text/plain"));
}
Also used : Request(ratpack.http.Request) Logger(org.slf4j.Logger) Context(ratpack.handling.Context) LoggerFactory(org.slf4j.LoggerFactory) Throwables(com.google.common.base.Throwables) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Request(ratpack.http.Request)

Example 38 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project BRFS by zhangnianli.

the class DefaultNettyHandleResultCallback method completed.

@Override
public void completed(HandleResult result) {
    HttpResponseStatus status = result.isSuccess() ? HttpResponseStatus.OK : HttpResponseStatus.INTERNAL_SERVER_ERROR;
    byte[] errorBytes = result.getCause() != null ? BrStringUtils.toUtf8Bytes(result.getCause().toString()) : new byte[0];
    byte[] dataBytes = result.getData() != null ? result.getData() : new byte[0];
    ByteBuf content = Unpooled.wrappedBuffer(Bytes.concat(errorBytes, dataBytes));
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
    ResponseSender.sendResponse(context, response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 39 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project pinpoint by naver.

the class HttpClientOperationsOnInboundNextInterceptor method doInBeforeTrace.

@Override
public void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
    final HttpResponse httpResponses = (HttpResponse) args[1];
    try {
        final HttpResponseStatus httpResponseStatus = httpResponses.status();
        if (httpResponseStatus != null) {
            recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, httpResponseStatus.code());
        }
        this.responseHeaderRecorder.recordHeader(recorder, httpResponses);
    } catch (Exception ignore) {
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 40 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project netty by netty.

the class WebSocketClientHandshaker00 method verify.

/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    HttpResponseStatus status = response.status();
    if (!HttpResponseStatus.SWITCHING_PROTOCOLS.equals(status)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response getStatus: " + status, response);
    }
    HttpHeaders headers = response.headers();
    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response upgrade: " + upgrade, response);
    }
    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response connection: " + headers.get(HttpHeaderNames.CONNECTION), response);
    }
    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketClientHandshakeException("Invalid challenge", response);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ByteBuf(io.netty.buffer.ByteBuf)

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