Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext fireChannelRead.

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

From source file:com.lampard.netty4.protocol.netty.server.HeartBeatRespHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?//www . j  a  v a 2  s. c  o m
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
        LOG.info("Receive client heart beat message : ---> " + message);
        NettyMessage heartBeat = buildHeatBeat();
        LOG.info("Send heart beat response message to client : ---> " + heartBeat);
        ctx.writeAndFlush(heartBeat);
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.lampard.netty4.protocol.netty.server.LoginAuthRespHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * /*from   w  ww.j  av a2  s . c o  m*/
 * Sub-classes may override this method to change behavior.
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
        String nodeIndex = ctx.channel().remoteAddress().toString();
        NettyMessage loginResp = null;
        // ???
        if (nodeCheck.containsKey(nodeIndex)) {
            loginResp = buildResponse((byte) -1);
        } else {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            String ip = address.getAddress().getHostAddress();
            boolean isOK = false;
            for (String WIP : whitekList) {
                if (WIP.equals(ip)) {
                    isOK = true;
                    break;
                }
            }
            loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
            if (isOK)
                nodeCheck.put(nodeIndex, true);
        }
        LOG.info("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
    } else {
        ctx.fireChannelRead(msg);
    }
}

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);
        return;//  www .  java 2 s. c om
    }

    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.http.Http2ResponseDecoder.java

License:Apache License

@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
    ctx.fireChannelRead(settings);
}

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);
        return;/*from w w w.j a v  a2  s .c o m*/
    }

    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.internal.FlushConsolidationHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    readInprogess = true;/*from  ww w .j a va 2  s  . c o  m*/
    ctx.fireChannelRead(msg);
}

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

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (isRequestStart(msg)) {
        pendingResCount++;//w w  w.j a va  2  s  .  c o  m
    }
    ctx.fireChannelRead(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);
        return;//  w  ww  . j  a  v a 2  s  . com
    }

    // 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.http.Http1RequestDecoder.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof UpgradeEvent) {
        // Generate the initial Http2Settings frame,
        // so that the next handler knows the protocol upgrade occurred as well.
        ctx.fireChannelRead(DEFAULT_HTTP2_SETTINGS);

        // Continue handling the upgrade request after the upgrade is complete.
        final FullHttpRequest nettyReq = ((UpgradeEvent) evt).upgradeRequest();

        // Remove the headers related with the upgrade.
        nettyReq.headers().remove(HttpHeaderNames.CONNECTION);
        nettyReq.headers().remove(HttpHeaderNames.UPGRADE);
        nettyReq.headers().remove(Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER);

        if (logger.isDebugEnabled()) {
            logger.debug("{} Handling the pre-upgrade request ({}): {} {} {} ({}B)", ctx.channel(),
                    ((UpgradeEvent) evt).protocol(), nettyReq.method(), nettyReq.uri(),
                    nettyReq.protocolVersion(), nettyReq.content().readableBytes());
        }//from ww w .j a  v  a  2  s .  com

        channelRead(ctx, nettyReq);
        channelReadComplete(ctx);
        return;
    }

    ctx.fireUserEventTriggered(evt);
}

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

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) throws Http2Exception {
    final HttpHeaders convertedHeaders = ArmeriaHttpUtil.toArmeria(headers);
    DecodedHttpRequest req = requests.get(streamId);
    if (req == null) {
        // Validate the 'content-length' header if exists.
        if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            final long contentLength = headers.getLong(HttpHeaderNames.CONTENT_LENGTH, -1L);
            if (contentLength < 0) {
                writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST);
                return;
            }//w  w w. java2 s .  c o  m
        }

        req = new DecodedHttpRequest(ctx.channel().eventLoop(), ++nextId, streamId, convertedHeaders, true,
                inboundTrafficController);

        requests.put(streamId, req);
        ctx.fireChannelRead(req);
    } else {
        try {
            req.write(convertedHeaders);
        } catch (Throwable t) {
            req.close(t);
            throw connectionError(INTERNAL_ERROR, t, "failed to consume a HEADERS frame");
        }
    }

    if (endOfStream) {
        req.close();
    }
}