Example usage for io.netty.channel ChannelHandlerContext read

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext read();

Source Link

Usage

From source file:NettyInboundHttpTargetHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    //  System.out.println("Activating Chanel");
    ctx.read();
    ctx.write(Unpooled.EMPTY_BUFFER);//w  w w .j  av a2  s .c  o m
}

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    if (decodeWasNull) {
        decodeWasNull = false;//from  w w w . j a  v  a 2s  .  co  m
        if (!ctx.channel().config().isAutoRead()) {
            ctx.read();
        }
    }
    ctx.fireChannelReadComplete();
}

From source file:com.aerofs.baseline.http.HttpRequestHandler.java

License:Apache License

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.trace("{}: set http cleanup handler", Channels.getHexText(ctx));
    ctx.channel().closeFuture().addListener(future -> cleanup(ctx, future.cause()));
    super.channelRegistered(ctx);
    ctx.read();
}

From source file:com.aerofs.baseline.http.HttpRequestHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (ctx.channel().closeFuture().isDone()) {
        LOGGER.warn("{}: drop http message - channel closed", Channels.getHexText(ctx));
        return;//from w w w . ja v  a  2  s . c om
    }

    if (!(msg instanceof HttpObject)) {
        super.channelRead(ctx, msg);
    }

    //
    // netty http decoding:
    //
    // 1. normal case: HttpRequest (headers), HttpContent (0+), LastHttpContent (trailing headers)
    //    NOTE: with chunked transfer encoding or content-length non-zero you get an arbitrary number of HttpContent objects
    // 2. error case (failed to decode an HTTP message): HttpRequest with NETTY_HTTP_DECODING_FAILED_URI
    //

    if (msg instanceof HttpRequest) {
        // this is the first object netty generates:
        // an HttpRequest containing a number of headers

        // we should not have another request pending
        Preconditions.checkState(pendingRequest == null, "previous request pending:%s", pendingRequest);

        // cast it
        HttpRequest nettyRequest = (HttpRequest) msg;

        // get the request id
        String requestId = nettyRequest.headers().get(Headers.REQUEST_TRACING_HEADER);
        Preconditions.checkState(requestId != null, "http request on %s has no request id",
                Channels.getHexText(ctx));

        // check if http decoding failed and if so, abort early
        if (nettyRequest.uri().equals(NETTY_HTTP_DECODING_FAILED_URI)) {
            LOGGER.warn("{}: [{}] fail http decoding", Channels.getHexText(ctx), requestId);
            ctx.read();
            return;
        }

        // get a few headers we really care about
        HttpVersion httpVersion = nettyRequest.protocolVersion();
        boolean keepAlive = HttpHeaders.isKeepAlive(nettyRequest);
        boolean transferEncodingChunked = HttpHeaders.isTransferEncodingChunked(nettyRequest);
        boolean continueExpected = HttpHeaders.is100ContinueExpected(nettyRequest);
        long contentLength = HttpHeaders.getContentLength(nettyRequest, ZERO_CONTENT_LENGTH);
        boolean hasContent = transferEncodingChunked || contentLength > ZERO_CONTENT_LENGTH;
        LOGGER.trace("{}: [{}] rq:{} ka:{} ck:{} ce:{} cl:{}", Channels.getHexText(ctx), requestId,
                nettyRequest, keepAlive, transferEncodingChunked, continueExpected, contentLength);

        // create the input stream used to read content
        ContentInputStream entityInputStream;
        if (hasContent) {
            entityInputStream = new EntityInputStream(httpVersion, continueExpected, ctx);
        } else {
            entityInputStream = EmptyEntityInputStream.EMPTY_ENTITY_INPUT_STREAM;
        }

        // create the object with which to write the response body
        PendingRequest pendingRequest = new PendingRequest(requestId, httpVersion, keepAlive, entityInputStream,
                ctx);

        // create the jersey request object
        final ContainerRequest jerseyRequest = new ContainerRequest(baseUri, URI.create(nettyRequest.uri()),
                nettyRequest.method().name(), DEFAULT_SECURITY_CONTEXT, PROPERTIES_DELEGATE);
        jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_CHANNEL_ID_PROPERTY,
                new ChannelId(Channels.getHexText(ctx)));
        jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_REQUEST_ID_PROPERTY,
                new RequestId(requestId));
        jerseyRequest.header(Headers.REQUEST_TRACING_HEADER, requestId); // add request id to headers
        copyHeaders(nettyRequest.headers(), jerseyRequest); // copy headers from message
        jerseyRequest.setEntityStream(entityInputStream);
        jerseyRequest.setWriter(pendingRequest);

        // now we've got all the initial headers and are waiting for the entity
        this.pendingRequest = pendingRequest;

        // store the runnable that we want jersey to execute
        saveRequestRunnable(() -> {
            // all throwables caught by jersey internally -
            // handled by the ResponseWriter below
            // if, for some reason there's some weird error it'll be handled
            // by the default exception handler, which kills the process
            applicationHandler.handle(jerseyRequest);
        });

        // IMPORTANT:
        // we pass this request up to be processed by
        // jersey before we've read any content. This allows
        // the resource to read from the InputStream
        // directly, OR, to use an @Consumes annotation with an
        // input objectType to invoke the appropriate parser
        //
        // since the request is consumed *before* the content
        // has been received readers may block. to prevent the
        // IO thread from blocking we have to execute all
        // request processing in an application threadpool
        if (hasContent) {
            submitPendingRunnable();
        }

        // indicate that we want to keep reading
        // this is always the case when we receive headers
        // because we want to receive everything until
        // LastHttpContent
        ctx.read();
    } else {
        // after receiving the http headers we get
        // a series of HttpContent objects that represent
        // the entity or a set of chunks

        // we should have received the headers already
        Preconditions.checkState(pendingRequest != null, "no pending request");
        // we're not expecting anything other than content objects right now
        Preconditions.checkArgument(msg instanceof HttpContent, "HttpContent expected, not %s",
                msg.getClass().getSimpleName());

        // handle the content
        HttpContent content = (HttpContent) msg;
        boolean last = msg instanceof LastHttpContent;
        LOGGER.trace("{}: [{}] handling content:{} last:{}", Channels.getHexText(ctx), pendingRequest.requestId,
                content.content().readableBytes(), last);
        pendingRequest.entityInputStream.addBuffer(content.content(), last); // transfers ownership to the HttpContentInputStream

        // FIXME (AG): support trailing headers
        // if it's the last piece of content, then we're done
        if (last) {
            // submit the request to jersey if we haven't yet
            if (savedRequestRunnable != null) {
                submitPendingRunnable();
            }
        }
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyHandler.java

License:Apache License

@Override
public void read(ChannelHandlerContext channelHandlerContext) throws Exception {
    channelHandlerContext.read();
}

From source file:com.andy.grpc.proxy.HexDumpProxyBackendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    ctx.read();
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
        ctx.read();
    }/*from  w ww.  java 2  s.co m*/
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override/*from w w w  .  ja v  a  2s  .co m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
                    ctx.read();
                }
            }
        });
    } else {
        ReferenceCountUtil.release(msg);
    }

}

From source file:com.chenyang.proxy.http.HttpRemoteForwardHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext remoteChannelCtx) throws Exception {
    remoteChannelCtx.read();
}

From source file:com.chenyang.proxy.http.HttpRemoteForwardHandler.java

License:Apache License

public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception {

    remainMsgCount++;/* ww  w. ja v a  2s.  c om*/

    if (remainMsgCount <= 5) {
        remoteChannelCtx.read();
    }

    HttpObject ho = (HttpObject) msg;

    if (ho instanceof HttpResponse) {
        HttpResponse httpResponse = (HttpResponse) ho;

        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE);
    }

    if (uaChannel.isActive()) {
        uaChannel.writeAndFlush(ho).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    remainMsgCount--;
                    remoteChannelCtx.read();
                } else {
                    remoteChannelCtx.close();
                }
            }
        });
    } else {
        remoteChannelCtx.close();
    }
}