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:org.elasticsearch.hadoop.http.netty4.cors.Netty4CorsHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (config.isCorsSupportEnabled() && msg instanceof HttpRequest) {
        request = (HttpRequest) msg;//  w  w  w .  ja  va 2  s  .c  o m
        if (isPreflightRequest(request)) {
            handlePreflight(ctx, request);
            return;
        }
        if (config.isShortCircuit() && !validateOrigin()) {
            forbidden(ctx, request);
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:org.elasticsearch.hadoop.http.netty4.pipelining.HttpPipeliningHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof LastHttpContent) {
        ctx.fireChannelRead(new HttpPipelinedRequest(((LastHttpContent) msg).retain(), readSequence++));
    } else {// w w  w . j  av  a2  s.  c  om
        ctx.fireChannelRead(msg);
    }
}

From source file:org.elasticsearch.hadoop.transport.netty4.Netty4MessageChannelHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Transports.assertTransportThread();//from  w ww.  j  a v  a  2s .  co  m
    if (!(msg instanceof ByteBuf)) {
        ctx.fireChannelRead(msg);
        return;
    }
    final ByteBuf buffer = (ByteBuf) msg;
    final int remainingMessageSize = buffer.getInt(buffer.readerIndex() - TcpHeader.MESSAGE_LENGTH_SIZE);
    final int expectedReaderIndex = buffer.readerIndex() + remainingMessageSize;
    InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
    try {
        // netty always copies a buffer, either in NioWorker in its read handler, where it copies to a fresh
        // buffer, or in the cumulation buffer, which is cleaned each time so it could be bigger than the actual size
        BytesReference reference = Netty4Utils.toBytesReference(buffer, remainingMessageSize);
        transport.messageReceived(reference, ctx.channel(), profileName, remoteAddress, remainingMessageSize);
    } finally {
        // Set the expected position of the buffer, no matter what happened
        buffer.readerIndex(expectedReaderIndex);
    }
}

From source file:org.elasticsearch.http.netty4.Netty4HttpPipeliningHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    assert msg instanceof FullHttpRequest : "Invalid message type: " + msg.getClass();
    HttpPipelinedRequest<FullHttpRequest> pipelinedRequest = aggregator.read(((FullHttpRequest) msg));
    ctx.fireChannelRead(pipelinedRequest);
}

From source file:org.elasticsearch.http.nio.cors.NioCorsHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    assert msg instanceof FullHttpRequest : "Invalid message type: " + msg.getClass();
    if (config.isCorsSupportEnabled()) {
        request = (FullHttpRequest) msg;
        if (isPreflightRequest(request)) {
            try {
                handlePreflight(ctx, request);
                return;
            } finally {
                releaseRequest();/* w w w.  j ava 2 s  . c o m*/
            }
        }
        if (config.isShortCircuit() && !validateOrigin()) {
            try {
                forbidden(ctx, request);
                return;
            } finally {
                releaseRequest();
            }
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:org.gamejam.gc.fartroulette.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);// w  w  w.  j av a2  s.  c o  m
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();

    if (filter.run(uri)) { //pass to the next handler
        ctx.fireChannelRead(request);
        return;
    }

    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    s_logger.info(path);

    /*if (path.contains("wow")) {
       FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    ctx.writeAndFlush(response);
    return;
               
    } else {
    ctx.fireChannelRead(request);
    }*/

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.glassfish.jersey.netty.httpserver.JerseyServerInitializer.java

License:Open Source License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
 *//*from ww w. ja v  a  2s . co m*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, new HttpServerUpgradeHandler.UpgradeCodecFactory() {
        @Override
        public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                return new Http2ServerUpgradeCodec(
                        new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container)));
            } else {
                return null;
            }
        }
    }));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            // "Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");

            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new JerseyServerHandler(baseUri, container));
            pipeline.replace(this, null, new ChunkedWriteHandler());
            ctx.fireChannelRead(msg);
        }
    });
}

From source file:org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    if (msg.isReadable()) {
        // "Dynamically manipulating a pipeline is relatively an expensive operation."
        // https://stackoverflow.com/a/28846565
        if (handler == null) {
            if (usesOctetCountFraming(msg)) {
                handler = new SyslogOctetCountFrameDecoder();
            } else {
                handler = new DelimiterBasedFrameDecoder(maxFrameLength, delimiter);
            }/* w ww. jav  a  2s  .c  o m*/
        }

        handler.channelRead(ctx, ReferenceCountUtil.retain(msg));
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:org.graylog2.inputs.transports.netty.HttpHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    final Channel channel = ctx.channel();
    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final HttpVersion httpRequestVersion = request.protocolVersion();
    final String origin = request.headers().get(HttpHeaderNames.ORIGIN);

    // to allow for future changes, let's be at least a little strict in what we accept here.
    if (HttpMethod.OPTIONS.equals(request.method())) {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.OK, origin);
        return;/*from   www  .  j a  v a2  s.c  o m*/
    } else if (!HttpMethod.POST.equals(request.method())) {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.METHOD_NOT_ALLOWED, origin);
        return;
    }

    final boolean correctPath = "/gelf".equals(request.uri());
    if (correctPath && request instanceof FullHttpRequest) {
        final FullHttpRequest fullHttpRequest = (FullHttpRequest) request;
        final ByteBuf buffer = fullHttpRequest.content();

        // send on to raw message handler
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.ACCEPTED, origin);
        ctx.fireChannelRead(buffer);
    } else {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.NOT_FOUND, origin);
    }
}

From source file:org.graylog2.inputs.transports.netty.MessageAggregationHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    final CodecAggregator.Result result;
    try (Timer.Context ignored = aggregationTimer.time()) {
        result = aggregator.addChunk(msg);
    }// w ww .  jav  a  2  s.  c  o  m
    final ByteBuf completeMessage = result.getMessage();
    if (completeMessage != null) {
        LOG.debug("Message aggregation completion, forwarding {}", completeMessage);
        ctx.fireChannelRead(completeMessage);
    } else if (result.isValid()) {
        LOG.debug("More chunks necessary to complete this message");
    } else {
        invalidChunksMeter.mark();
        LOG.debug("Message chunk was not valid and discarded.");
    }
}