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.aotorrent.client.OutboundHandshakeHandler.java

License:Apache License

@Override
protected synchronized void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    final ByteBuf buf = (ByteBuf) msg;

    if (handshakeDone) {
        super.channelRead(ctx, msg);
        return;/*from w  w w .ja va  2 s.  c o m*/
    }

    try {

        HandshakeRequest handshakeRequest = new HandshakeRequest(buf);

        if (ArrayUtils.isEquals(handshakeRequest.getInfoHash(), torrentEngine.getInfoHash())) {
            handshakeDone = true;
            PeerConnection peerConnection = new PeerConnection(torrentEngine, ctx);
            torrentEngine.registerConnection(ctx.channel().remoteAddress(), peerConnection);
            final ChannelPipeline pipeline = ctx.pipeline();
            pipeline.addLast("peerConnection", peerConnection);
            pipeline.remove(this);
            ByteBuf out = ((ByteBuf) msg).copy();
            ctx.fireChannelRead(out);
            peerConnection.sendBitField();
        }

    } finally {
        buf.release();
    }
}

From source file:org.apache.activemq.artemis.core.protocol.stomp.WebSocketServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        handleHttpRequest(ctx, (FullHttpRequest) msg);
    } else if (msg instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) msg;
        boolean handle = handleWebSocketFrame(ctx, frame);
        if (handle) {
            ctx.fireChannelRead(frame.content().retain());
        }//www .ja v  a2s  .  co m
    }
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.HttpAcceptorHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    HttpMethod method = request.getMethod();
    // if we are a post then we send upstream, otherwise we are just being prompted for a response.
    if (method.equals(HttpMethod.POST)) {
        ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content()));
        // add a new response
        responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime,
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
        ReferenceCountUtil.release(msg);
        return;//from   ww w .  ja va 2 s.  c  o  m
    }
    super.channelRead(ctx, msg);
}

From source file:org.apache.bookkeeper.proto.BookieProtoEncodingTest.java

License:Apache License

@Test
public void testV3ResponseDecoderNoFallback() throws Exception {
    AddResponse v2Resp = AddResponse.create(BookieProtocol.CURRENT_PROTOCOL_VERSION, BookieProtocol.EOK, 1L,
            2L);//from w  ww. j a va  2 s.com

    BookkeeperProtocol.Response v3Resp = BookkeeperProtocol.Response.newBuilder()
            .setHeader(BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE).setTxnId(1L)
                    .setOperation(OperationType.ADD_ENTRY).build())
            .setStatus(StatusCode.EOK).setAddResponse(BookkeeperProtocol.AddResponse.newBuilder()
                    .setStatus(StatusCode.EOK).setLedgerId(1L).setEntryId(2L).build())
            .build();

    List<Object> outList = Lists.newArrayList();
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.fireChannelRead(any())).thenAnswer((iom) -> {
        outList.add(iom.getArgument(0));
        return null;
    });

    ResponseEnDeCoderPreV3 v2Encoder = new ResponseEnDeCoderPreV3(registry);
    ResponseEnDecoderV3 v3Encoder = new ResponseEnDecoderV3(registry);

    ResponseDecoder v3Decoder = new ResponseDecoder(registry, false);
    try {
        v3Decoder.channelRead(ctx, v2Encoder.encode(v2Resp, UnpooledByteBufAllocator.DEFAULT));
        fail("V3 response decoder should fail on decoding v2 response");
    } catch (InvalidProtocolBufferException e) {
        // expected
    }
    assertEquals(0, outList.size());

    v3Decoder.channelRead(ctx, v3Encoder.encode(v3Resp, UnpooledByteBufAllocator.DEFAULT));
    assertEquals(1, outList.size());
}

From source file:org.apache.bookkeeper.proto.BookieRequestHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof BookkeeperProtocol.Request || msg instanceof BookieProtocol.Request)) {
        ctx.fireChannelRead(msg);
        return;//from  w w  w.j av  a2 s.  c  om
    }
    requestProcessor.processRequest(msg, ctx.channel());
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

/**
 * Called by netty when a message is received on a channel.
 *///  ww  w .  j  a va 2  s  .c om
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    if (msg instanceof BookieProtocol.Response) {
        BookieProtocol.Response response = (BookieProtocol.Response) msg;
        readV2Response(response);
    } else if (msg instanceof Response) {
        Response response = (Response) msg;
        readV3Response(response);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:org.apache.flink.runtime.webmonitor.HttpRequestHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    try {/*from w  w  w  . ja va 2 s .c o  m*/
        if (msg instanceof HttpRequest) {
            currentRequest = (HttpRequest) msg;
            currentRequestPath = null;

            if (currentDecoder != null) {
                currentDecoder.destroy();
                currentDecoder = null;
            }

            if (currentRequest.getMethod() == HttpMethod.GET
                    || currentRequest.getMethod() == HttpMethod.DELETE) {
                // directly delegate to the router
                ctx.fireChannelRead(currentRequest);
            } else if (currentRequest.getMethod() == HttpMethod.POST) {
                // POST comes in multiple objects. First the request, then the contents
                // keep the request and path for the remaining objects of the POST request
                currentRequestPath = new QueryStringDecoder(currentRequest.getUri()).path();
                currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest);
            } else {
                throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name());
            }
        } else if (currentDecoder != null && msg instanceof HttpContent) {
            // received new chunk, give it to the current decoder
            HttpContent chunk = (HttpContent) msg;
            currentDecoder.offer(chunk);

            try {
                while (currentDecoder.hasNext()) {
                    InterfaceHttpData data = currentDecoder.next();

                    // IF SOMETHING EVER NEEDS POST PARAMETERS, THIS WILL BE THE PLACE TO HANDLE IT
                    // all fields values will be passed with type Attribute.

                    if (data.getHttpDataType() == HttpDataType.FileUpload) {
                        DiskFileUpload file = (DiskFileUpload) data;
                        if (file.isCompleted()) {
                            String name = file.getFilename();

                            File target = new File(tmpDir, UUID.randomUUID() + "_" + name);
                            file.renameTo(target);

                            QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath);
                            encoder.addParam("filepath", target.getAbsolutePath());
                            encoder.addParam("filename", name);

                            currentRequest.setUri(encoder.toString());
                        }
                    }

                    data.release();
                }
            } catch (EndOfDataDecoderException ignored) {
            }

            if (chunk instanceof LastHttpContent) {
                HttpRequest request = currentRequest;
                currentRequest = null;
                currentRequestPath = null;

                currentDecoder.destroy();
                currentDecoder = null;

                // fire next channel handler
                ctx.fireChannelRead(request);
            }
        }
    } catch (Throwable t) {
        currentRequest = null;
        currentRequestPath = null;

        if (currentDecoder != null) {
            currentDecoder.destroy();
            currentDecoder = null;
        }

        if (ctx.channel().isActive()) {
            byte[] bytes = ExceptionUtils.stringifyException(t).getBytes(ENCODING);

            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes));

            response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8");
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

            ctx.writeAndFlush(response);
        }
    }
}

From source file:org.apache.giraph.comm.netty.handler.AuthorizeServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("messageReceived: Got " + msg.getClass());
    }/* w  w  w .j  a v  a 2  s . co  m*/
    // Authorize: client is allowed to doRequest() if and only if the client
    // has successfully authenticated with this server.
    SaslNettyServer saslNettyServer = ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).get();
    if (saslNettyServer == null) {
        LOG.warn("messageReceived: This client is *NOT* authorized to perform "
                + "this action since there's no saslNettyServer to " + "authenticate the client: "
                + "refusing to perform requested action: " + msg);
        return;
    }

    if (!saslNettyServer.isComplete()) {
        LOG.warn("messageReceived: This client is *NOT* authorized to perform "
                + "this action because SASL authentication did not complete: "
                + "refusing to perform requested action: " + msg);
        // Return now *WITHOUT* sending upstream here, since client
        // not authorized.
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("messageReceived: authenticated client: " + saslNettyServer.getUserName()
                + " is authorized to do request " + "on server.");
    }
    // We call fireChannelRead since the client is allowed to perform this
    // request. The client's request will now proceed to the next
    // pipeline component, namely, RequestServerHandler.
    ctx.fireChannelRead(msg);
}

From source file:org.apache.giraph.comm.netty.handler.RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        throw new IllegalStateException("decode: Got illegal message " + msg);
    }//from www  . j  a  v  a  2  s. co  m
    // Output metrics every 1/2 minute
    String metrics = byteCounter.getMetricsWindow(30000);
    if (metrics != null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("decode: Server window metrics " + metrics);
        }
    }

    if (LOG.isDebugEnabled()) {
        startDecodingNanoseconds = TIME.getNanoseconds();
    }

    // Decode the request
    ByteBuf buf = (ByteBuf) msg;
    int enumValue = buf.readByte();
    RequestType type = RequestType.values()[enumValue];
    Class<? extends WritableRequest> requestClass = type.getRequestClass();
    WritableRequest request = ReflectionUtils.newInstance(requestClass, conf);
    request = RequestUtils.decodeWritableRequest(buf, request);

    if (LOG.isDebugEnabled()) {
        LOG.debug("decode: Client " + request.getClientId() + ", requestId " + request.getRequestId() + ", "
                + request.getType() + ", with size " + buf.writerIndex() + " took "
                + Times.getNanosSince(TIME, startDecodingNanoseconds) + " ns");
    }
    ReferenceCountUtil.release(buf);
    // fire writableRequest object to upstream handlers
    ctx.fireChannelRead(request);
}

From source file:org.apache.giraph.comm.netty.handler.SaslServerHandler.java

License:Apache License

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("messageReceived: Got " + msg.getClass());
    }//from w w w  .j  a v  a  2 s .c o  m

    WritableRequest writableRequest = (WritableRequest) msg;
    // Simulate a closed connection on the first request (if desired)
    // TODO: Move out into a separate, dedicated handler.
    if (closeFirstRequest && !ALREADY_CLOSED_FIRST_REQUEST) {
        LOG.info("messageReceived: Simulating closing channel on first " + "request "
                + writableRequest.getRequestId() + " from " + writableRequest.getClientId());
        setAlreadyClosedFirstRequest();
        ctx.close();
        return;
    }

    if (writableRequest.getType() == RequestType.SASL_TOKEN_MESSAGE_REQUEST) {
        // initialize server-side SASL functionality, if we haven't yet
        // (in which case we are looking at the first SASL message from the
        // client).
        SaslNettyServer saslNettyServer = ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).get();
        if (saslNettyServer == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No saslNettyServer for " + ctx.channel()
                        + " yet; creating now, with secret manager: " + secretManager);
            }
            try {
                saslNettyServer = new SaslNettyServer(secretManager, AuthMethod.SIMPLE);
            } catch (IOException ioe) { //TODO:
                throw new RuntimeException(ioe);
            }
            ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).set(saslNettyServer);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found existing saslNettyServer on server:" + ctx.channel().localAddress()
                        + " for client " + ctx.channel().remoteAddress());
            }
        }

        ((SaslTokenMessageRequest) writableRequest).processToken(saslNettyServer);
        // Send response to client.
        ctx.write(writableRequest);
        if (saslNettyServer.isComplete()) {
            // If authentication of client is complete, we will also send a
            // SASL-Complete message to the client.
            if (LOG.isDebugEnabled()) {
                LOG.debug("SASL authentication is complete for client with " + "username: "
                        + saslNettyServer.getUserName());
            }
            SaslCompleteRequest saslComplete = new SaslCompleteRequest();
            ctx.write(saslComplete);
            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "Removing SaslServerHandler from pipeline since SASL " + "authentication is complete.");
            }
            ctx.pipeline().remove(this);
        }
        ctx.flush();
        // do not send upstream to other handlers: no further action needs to be
        // done for SASL_TOKEN_MESSAGE_REQUEST requests.
        return;
    } else {
        // Client should not be sending other-than-SASL messages before
        // SaslServerHandler has removed itself from the pipeline. Such non-SASL
        // requests will be denied by the Authorize channel handler (the next
        // handler upstream in the server pipeline) if SASL authentication has
        // not completed.
        LOG.warn("Sending upstream an unexpected non-SASL message :  " + writableRequest);
        ctx.fireChannelRead(msg);
    }
}