Example usage for io.netty.handler.codec.http HttpObject decoderResult

List of usage examples for io.netty.handler.codec.http HttpObject decoderResult

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpObject decoderResult.

Prototype

DecoderResult decoderResult();

Source Link

Document

Returns the result of decoding this object.

Usage

From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response;/*w  ww  .  j  a v  a 2s.co m*/
    if (currentAction.equals("Add"))
        response = new DefaultFullHttpResponse(HTTP_1_1,
                currentObj.decoderResult().isSuccess() ? CREATED : BAD_REQUEST);
    else if (currentAction.equals("Latest")) {
        response = new DefaultFullHttpResponse(HTTP_1_1,
                currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
                Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "application/json; charset=utf-8");
    } else
        response = new DefaultFullHttpResponse(HTTP_1_1,
                currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
                Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    // response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;

}

From source file:ch07.handlers.HttpSnoopServerHandler.java

License:Apache License

private static void appendDecoderResult(StringBuilder buf, HttpObject o) {
    DecoderResult result = o.decoderResult();
    if (result.isSuccess()) {
        return;/*  w  w w .  j  a  v a2 s  .co  m*/
    }

    buf.append(".. WITH DECODER FAILURE: ");
    buf.append(result.cause());
    buf.append("\r\n");
}

From source file:ch07.handlers.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }/*from  w ww  . jav a2s.co  m*/

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }/*from   w w  w.j  av a 2 s  .  c o m*/

    // Encode the cookie.
    String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1"));
        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }//from   w  ww . j  a va 2 s.  c o  m

    // Encode the cookie.
    String cookieString = request.headers().getAndConvert(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (!msg.decoderResult().isSuccess()) {
        failAndClose(new IOException("Failed to parse the HTTP response."), ctx);
        return;//from  www  .j  a  v  a2  s  . co m
    }
    if (!(msg instanceof HttpResponse) && !(msg instanceof HttpContent)) {
        failAndClose(
                new IllegalArgumentException("Unsupported message type: " + StringUtil.simpleClassName(msg)),
                ctx);
        return;
    }
    checkState(userPromise != null, "response before request");

    if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        if (!response.protocolVersion().equals(HttpVersion.HTTP_1_1)) {
            HttpException error = new HttpException(response,
                    "HTTP version 1.1 is required, was: " + response.protocolVersion(), null);
            failAndClose(error, ctx);
            return;
        }
        if (!HttpUtil.isContentLengthSet(response) && !HttpUtil.isTransferEncodingChunked(response)) {
            HttpException error = new HttpException(response,
                    "Missing 'Content-Length' or 'Transfer-Encoding: chunked' header", null);
            failAndClose(error, ctx);
            return;
        }
        downloadSucceeded = response.status().equals(HttpResponseStatus.OK);
        if (!downloadSucceeded) {
            out = new ByteArrayOutputStream();
        }
        keepAlive = HttpUtil.isKeepAlive((HttpResponse) msg);
    }

    if (msg instanceof HttpContent) {
        checkState(response != null, "content before headers");

        ByteBuf content = ((HttpContent) msg).content();
        content.readBytes(out, content.readableBytes());
        if (msg instanceof LastHttpContent) {
            if (downloadSucceeded) {
                succeedAndReset(ctx);
            } else {
                String errorMsg = response.status() + "\n";
                errorMsg += new String(((ByteArrayOutputStream) out).toByteArray(),
                        HttpUtil.getCharset(response));
                out.close();
                HttpException error = new HttpException(response, errorMsg, null);
                failAndReset(error, ctx);
            }
        }
    }
}

From source file:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java

License:Apache License

private boolean writeResponse(HttpObject httpObject, ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            httpObject.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(responseString.toString().toString(), CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    responseString = new StringBuilder();
    // Write the response.
    ctx.write(response);/*  w  w  w  .j  ava  2 s .  co  m*/
    return true;
}

From source file:io.aos.netty5.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }//w  ww.j  av a2 s  .com

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:io.vertx.core.http.impl.ClientHandler.java

License:Open Source License

@Override
protected void doMessageReceived(ClientConnection conn, ChannelHandlerContext ctx, Object msg) {
    if (conn == null) {
        return;//from  w  w w .  j av  a2s .c  o  m
    }
    if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        DecoderResult result = obj.decoderResult();
        if (result.isFailure()) {
            // Close the connection as Netty's HttpResponseDecoder will not try further processing
            // see https://github.com/netty/netty/issues/3362
            conn.handleException(result.cause());
            conn.close();
            return;
        }
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) obj;
            conn.handleResponse(response);
            return;
        }
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) obj;
            if (chunk.content().isReadable()) {
                Buffer buff = Buffer.buffer(chunk.content().slice());
                conn.handleResponseChunk(buff);
            }
            if (chunk instanceof LastHttpContent) {
                conn.handleResponseEnd((LastHttpContent) chunk);
            }
            return;
        }
    } else if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        switch (frame.type()) {
        case BINARY:
        case CONTINUATION:
        case TEXT:
            conn.handleWsFrame(frame);
            break;
        case PING:
            // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2
            ctx.writeAndFlush(new WebSocketFrameImpl(FrameType.PONG, frame.getBinaryData()));
            break;
        case PONG:
            // Just ignore it
            break;
        case CLOSE:
            if (!closeFrameSent) {
                // Echo back close frame and close the connection once it was written.
                // This is specified in the WebSockets RFC 6455 Section  5.4.1
                ctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE);
                closeFrameSent = true;
            }
            break;
        default:
            throw new IllegalStateException("Invalid type: " + frame.type());
        }
        return;
    }
    throw new IllegalStateException("Invalid object " + msg);
}

From source file:io.vertx.core.http.impl.Http1xClientConnection.java

License:Open Source License

private Throwable validateMessage(Object msg) {
    if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        DecoderResult result = obj.decoderResult();
        if (result.isFailure()) {
            return result.cause();
        } else if (obj instanceof HttpResponse) {
            io.netty.handler.codec.http.HttpVersion version = ((HttpResponse) obj).protocolVersion();
            if (version != io.netty.handler.codec.http.HttpVersion.HTTP_1_0
                    && version != io.netty.handler.codec.http.HttpVersion.HTTP_1_1) {
                return new IllegalStateException("Unsupported HTTP version: " + version);
            }// w  w  w.j  av a2 s . c  om
        }
    }
    return null;
}