Example usage for io.netty.handler.codec DecoderResult cause

List of usage examples for io.netty.handler.codec DecoderResult cause

Introduction

In this page you can find the example usage for io.netty.handler.codec DecoderResult cause.

Prototype

Throwable cause

To view the source code for io.netty.handler.codec DecoderResult cause.

Click Source Link

Usage

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 a2s.c  o m*/
    }

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

From source file:com.bala.learning.learning.netty.HttpServerHandler.java

License:Apache License

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

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

From source file:com.linecorp.armeria.client.http.Http1ResponseDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);/*from w  w w  .  j  ava  2 s. c o  m*/
        return;
    }

    try {
        switch (state) {
        case NEED_HEADERS:
            if (msg instanceof HttpResponse) {
                final HttpResponse nettyRes = (HttpResponse) msg;
                final DecoderResult decoderResult = nettyRes.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                if (!HttpUtil.isKeepAlive(nettyRes)) {
                    disconnectWhenFinished();
                }

                final HttpResponseWrapper res = getResponse(resId);
                assert res != null;
                this.res = res;

                if (nettyRes.status().codeClass() == HttpStatusClass.INFORMATIONAL) {
                    state = State.NEED_INFORMATIONAL_DATA;
                } else {
                    state = State.NEED_DATA_OR_TRAILING_HEADERS;
                    res.scheduleTimeout(ctx);
                }

                res.write(ArmeriaHttpUtil.toArmeria(nettyRes));
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_INFORMATIONAL_DATA:
            if (msg instanceof LastHttpContent) {
                state = State.NEED_HEADERS;
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_DATA_OR_TRAILING_HEADERS:
            if (msg instanceof HttpContent) {
                final HttpContent content = (HttpContent) msg;
                final DecoderResult decoderResult = content.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                final ByteBuf data = content.content();
                final int dataLength = data.readableBytes();
                if (dataLength > 0) {
                    final long maxContentLength = res.maxContentLength();
                    if (maxContentLength > 0 && res.writtenBytes() > maxContentLength - dataLength) {
                        fail(ctx, ContentTooLargeException.get());
                        return;
                    } else {
                        res.write(HttpData.of(data));
                    }
                }

                if (msg instanceof LastHttpContent) {
                    final HttpResponseWriter res = removeResponse(resId++);
                    assert this.res == res;
                    this.res = null;

                    state = State.NEED_HEADERS;

                    final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                    if (!trailingHeaders.isEmpty()) {
                        res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                    }

                    res.close();

                    if (needsToDisconnect()) {
                        ctx.close();
                    }
                }
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case DISCARD:
            break;
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.client.Http1ResponseDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);/*from ww  w .j  a va2  s  .  co  m*/
        return;
    }

    try {
        switch (state) {
        case NEED_HEADERS:
            if (msg instanceof HttpResponse) {
                final HttpResponse nettyRes = (HttpResponse) msg;
                final DecoderResult decoderResult = nettyRes.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                if (!HttpUtil.isKeepAlive(nettyRes)) {
                    disconnectWhenFinished();
                }

                final HttpResponseWrapper res = getResponse(resId);
                assert res != null;
                this.res = res;

                if (nettyRes.status().codeClass() == HttpStatusClass.INFORMATIONAL) {
                    state = State.NEED_INFORMATIONAL_DATA;
                } else {
                    state = State.NEED_DATA_OR_TRAILING_HEADERS;
                }

                res.scheduleTimeout(ctx);
                res.write(ArmeriaHttpUtil.toArmeria(nettyRes));
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_INFORMATIONAL_DATA:
            if (msg instanceof LastHttpContent) {
                state = State.NEED_HEADERS;
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_DATA_OR_TRAILING_HEADERS:
            if (msg instanceof HttpContent) {
                final HttpContent content = (HttpContent) msg;
                final DecoderResult decoderResult = content.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                final ByteBuf data = content.content();
                final int dataLength = data.readableBytes();
                if (dataLength > 0) {
                    assert res != null;
                    final long maxContentLength = res.maxContentLength();
                    if (maxContentLength > 0 && res.writtenBytes() > maxContentLength - dataLength) {
                        fail(ctx, ContentTooLargeException.get());
                        return;
                    } else {
                        res.write(HttpData.of(data));
                    }
                }

                if (msg instanceof LastHttpContent) {
                    final HttpResponseWrapper res = removeResponse(resId++);
                    assert res != null;
                    assert this.res == res;
                    this.res = null;

                    state = State.NEED_HEADERS;

                    final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                    if (!trailingHeaders.isEmpty()) {
                        res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                    }

                    res.close();

                    if (needsToDisconnect()) {
                        ctx.close();
                    }
                }
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case DISCARD:
            break;
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//from  www.java2s. co m
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController);

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.writtenBytes() > maxContentLength - dataLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                req.write(HttpData.of(data));
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.server.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);/*w  w w  .j  ava 2s.  co  m*/
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the method.
                if (!HttpMethod.isSupported(nettyReq.method().name())) {
                    fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                    return;
                }

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                final boolean contentEmpty;
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }

                    contentEmpty = contentLength == 0;
                } else {
                    contentEmpty = true;
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController, cfg.defaultMaxRequestLength());

                // Close the request early when it is sure that there will be
                // neither content nor trailing headers.
                if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) {
                    req.close();
                }

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                req.increaseTransferredBytes(dataLength);
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                if (req.isOpen()) {
                    req.write(new ByteBufHttpData(data.retain(), false));
                }
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (URISyntaxException e) {
        fail(ctx, HttpResponseStatus.BAD_REQUEST);
        if (req != null) {
            req.close(e);
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.topsec.bdc.platform.api.test.http.snoop.HttpSnoopServerHandler.java

License:Apache License

private static void appendDecoderResult(StringBuilder buf, HttpObject o) {

    DecoderResult result = o.getDecoderResult();
    if (result.isSuccess()) {
        return;//from   www . j ava  2s. c o m
    }

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

From source file:io.advantageous.conekt.http.impl.ServerConnection.java

License:Open Source License

private void processMessage(Object msg) {

    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        DecoderResult result = ((HttpObject) msg).getDecoderResult();
        if (result.isFailure()) {
            channel.pipeline().fireExceptionCaught(result.cause());
            return;
        }// w  w  w  . j  a  v a  2 s . c o m
        if (server.options().isHandle100ContinueAutomatically()) {
            if (HttpHeaders.is100ContinueExpected(request)) {
                write100Continue();
            }
        }
        HttpServerResponseImpl resp = new HttpServerResponseImpl(vertx, this, request);
        HttpServerRequestImpl req = new HttpServerRequestImpl(this, request, resp);
        handleRequest(req, resp);
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        if (chunk.content().isReadable()) {
            Buffer buff = Buffer.buffer(chunk.content());
            handleChunk(buff);
        }

        //TODO chunk trailers
        if (msg instanceof LastHttpContent) {
            if (!paused) {
                handleEnd();
            } else {
                // Requeue
                pending.add(LastHttpContent.EMPTY_LAST_CONTENT);
            }
        }
    } else if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        handleWsFrame(frame);
    }

    checkNextTick();
}

From source file:io.jsync.http.impl.AsyncHttpHandler.java

License:Open Source License

@Override
protected void channelRead(final C connection, final DefaultContext context, final ChannelHandlerContext chctx,
        final Object msg) throws Exception {
    if (msg instanceof HttpObject) {
        DecoderResult result = ((HttpObject) msg).decoderResult();
        if (result.isFailure()) {
            chctx.pipeline().fireExceptionCaught(result.cause());
            return;
        }/*from   w w w . j  a  v  a 2s.com*/
    }
    if (connection != null) {
        // we are reading from the channel
        Channel ch = chctx.channel();
        // We need to do this since it's possible the server is being used from a worker context
        if (context.isOnCorrectWorker(ch.eventLoop())) {
            try {
                async.setContext(context);
                doMessageReceived(connection, chctx, msg);
            } catch (Throwable t) {
                context.reportException(t);
            }
        } else {
            context.execute(new Runnable() {
                public void run() {
                    try {
                        doMessageReceived(connection, chctx, msg);
                    } catch (Throwable t) {
                        context.reportException(t);
                    }
                }
            });
        }
    } else {
        try {
            doMessageReceived(connection, chctx, msg);
        } catch (Throwable t) {
            chctx.pipeline().fireExceptionCaught(t);
        }
    }
}

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;// www. j a va  2  s . co  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);
}