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:net.anyflow.menton.http.HttpRequestRouter.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE))
            && HttpHeaderValues.UPGRADE.toString()
                    .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) {

        if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) {
            logger.error("No WebSocket Handler available.");

            ctx.channel()/*from w  ww.  j a va  2s. c  om*/
                    .writeAndFlush(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN))
                    .addListener(ChannelFutureListener.CLOSE);
            return;
        }

        ctx.fireChannelRead(request.retain());
        return;
    }

    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        return;
    }

    HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE));

    String requestPath = new URI(request.uri()).getPath();

    if (isWebResourcePath(requestPath)) {
        handleWebResourceRequest(ctx, request, response, requestPath);
    } else {
        try {
            processRequest(ctx, request, response);
        } catch (URISyntaxException e) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            logger.info("unexcepted URI : {}", request.uri());
        } catch (Exception e) {
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e);
        }
    }
}

From source file:net.bafeimao.umbrella.support.network.netty.handler.ProtocolStatsHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Packet packet) throws Exception {
    try {//from ww w .  j a va2s  . c o m
        MessageType messageType = packet.getType();

        // 
        AtomicLong counter = protocolStatsMap.get(messageType);
        if (counter != null) {
            long n = counter.incrementAndGet();
            LOGGER.info("type:{} -> {}", messageType, n);

            ctx.fireChannelRead(packet);
        } else {
            LOGGER.error("MessageType:{} was not found!", messageType);
        }

    } catch (Exception e) {
        LOGGER.error("{}", e);
        // TODO ??
    }
}

From source file:net.hasor.rsf.protocol.rsf.RsfDecoder.java

License:Apache License

/**???*/
private short doDecode(byte rsfHead, ChannelHandlerContext ctx, ByteBuf frame) {
    CodecAdapter factory = CodecAdapterFactory.getCodecAdapterByVersion(this.rsfEnvironment,
            (byte) (rsfHead & 0x0F));
    // - RSF_InvokerRequest
    if (RSF_InvokerRequest == rsfHead) {
        try {/*from w  ww.  j  a v  a  2 s  .  c om*/
            RequestInfo info = factory.readRequestInfo(frame);//  <-1.??
            info.setReceiveTime(System.currentTimeMillis());//    <-2.
            info.setMessage(false);
            //
            ctx.fireChannelRead(info);
            return ProtocolStatus.OK;/*??*/
        } catch (IOException e) {
            logger.error("decode request error :" + e.getMessage(), e);
            return ProtocolStatus.ProtocolError;
        }
    }
    // - RSF_MessageRequest
    if (RSF_MessageRequest == rsfHead) {
        try {
            RequestInfo info = factory.readRequestInfo(frame);//  <-1.??
            info.setReceiveTime(System.currentTimeMillis());//    <-2.
            info.setMessage(true);
            //
            ctx.fireChannelRead(info);
            return ProtocolStatus.OK;/*??*/
        } catch (IOException e) {
            logger.error("decode request error :" + e.getMessage(), e);
            return ProtocolStatus.ProtocolError;
        }
    }
    // RSF_Response
    if (RSF_Response == rsfHead) {
        try {
            ResponseInfo info = factory.readResponseInfo(frame);//  <-1.??
            info.setReceiveTime(System.currentTimeMillis());//      <-2.
            ctx.fireChannelRead(info);
            return ProtocolStatus.OK;/*??*/
        } catch (IOException e) {
            logger.error("decode response error :" + e.getMessage(), e);
            return ProtocolStatus.ProtocolError;
        }
    }
    return ProtocolStatus.ProtocolUndefined;
}

From source file:net.hasor.rsf.remoting.transport.netty.RSFProtocolDecoder.java

License:Apache License

/**???*/
private short doDecode(byte version, ChannelHandlerContext ctx, ByteBuf frame) throws IOException {
    ProtocolType pType = ProtocolType.valueOf(version);
    if (pType == ProtocolType.Request) {
        //request
        Protocol<RequestSocketBlock> requestProtocol = ProtocolUtils.requestProtocol(version);
        if (requestProtocol != null) {
            RequestSocketBlock block = requestProtocol.decode(frame);
            RequestMsg reqMetaData = TransferUtils.requestToMessage(block);
            ctx.fireChannelRead(reqMetaData);
            return ProtocolStatus.OK;/*??*/
        }//from  w  w w  .ja v a 2  s  .  c o m
    }
    if (pType == ProtocolType.Response) {
        //response
        Protocol<ResponseSocketBlock> responseProtocol = ProtocolUtils.responseProtocol(version);
        if (responseProtocol != null) {
            ResponseSocketBlock block = responseProtocol.decode(frame);
            ResponseMsg resMetaData = TransferUtils.responseToMessage(block);
            ctx.fireChannelRead(resMetaData);
            return ProtocolStatus.OK;/*??*/
        }
    }
    return ProtocolStatus.ProtocolError;
}

From source file:net.javaforge.netty.servlet.bridge.ServletBridgeHandler.java

License:Apache License

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

    if (e instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e;

        String uri = request.uri();

        if (uri.startsWith(uriPrefix)) {
            if (HttpHeaders.is100ContinueExpected(request)) {
                ctx.channel().write(new DefaultHttpResponse(HTTP_1_1, CONTINUE));
            }//from  w w  w . jav a  2s  . c o  m

            FilterChainImpl chain = ServletBridgeWebapp.get().initializeChain(uri);

            if (chain.isValid()) {
                handleHttpServletRequest(ctx, request, chain);
            } else if (ServletBridgeWebapp.get().getStaticResourcesFolder() != null) {
                handleStaticResourceRequest(ctx, request);
            } else {
                throw new ServletBridgeRuntimeException("No handler found for uri: " + request.getUri());
            }
        } else {
            ctx.fireChannelRead(e);
        }
    } else {
        ctx.fireChannelRead(e);
    }
}

From source file:net.minecrell.quartz.mixin.network.MixinLegacyPingHandler.java

License:MIT License

@Override
@Overwrite//from   w w w . j a  v  a  2s.  c  o m
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf m = (ByteBuf) msg;
    this.buf.writeBytes(m);
    m.release();

    this.buf.markReaderIndex();
    boolean result = false;

    try {
        result = readLegacy(ctx, this.buf);
    } finally {
        this.buf.resetReaderIndex();
        if (!result) {
            ByteBuf buf = this.buf;
            this.buf = null;

            ctx.pipeline().remove("legacy_query");
            ctx.fireChannelRead(buf);
        }
    }
}

From source file:net.tomp2p.connection.Dispatcher.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Message message) throws Exception {
    LOG.debug("received request {} from channel {}", message, ctx.channel());
    if (message.version() != p2pID) {
        LOG.error("Wrong version. We are looking for {} but we got {}, received: {}", p2pID, message.version(),
                message);/*  w ww. jav  a  2s  . c  o m*/
        ctx.close();
        synchronized (peerBeanMaster.peerStatusListeners()) {
            for (PeerStatusListener peerStatusListener : peerBeanMaster.peerStatusListeners()) {
                peerStatusListener.peerFailed(message.sender(),
                        new PeerException(AbortCause.PEER_ERROR, "wrong P2P version"));
            }
        }
        return;
    }

    if (!message.isRequest()) {
        LOG.debug("handing message to the next handler {}", message);
        ctx.fireChannelRead(message);
        return;
    }

    Responder responder = new DirectResponder(ctx, message);
    final DispatchHandler myHandler = associatedHandler(message);
    if (myHandler != null) {
        boolean isUdp = ctx.channel() instanceof DatagramChannel;
        LOG.debug("about to respond to {}", message);
        PeerConnection peerConnection = new PeerConnection(message.sender(),
                new DefaultChannelPromise(ctx.channel()).setSuccess(), heartBeatMillis);
        myHandler.forwardMessage(message, isUdp ? null : peerConnection, responder);
    } else {
        if (LOG.isWarnEnabled()) {
            printWarnMessage(message);
        }

        Message responseMessage = DispatchHandler.createResponseMessage(message, Type.UNKNOWN_ID,
                peerBeanMaster.serverPeerAddress());
        response(ctx, responseMessage);
    }
}

From source file:net.tomp2p.connection.RequestHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Message responseMessage) throws Exception {
    MessageID recvMessageID = new MessageID(responseMessage);
    // Error handling
    if (responseMessage.type() == Message.Type.UNKNOWN_ID) {
        String msg = "Message was not delivered successfully, unknow id (peer may be offline or unknown RPC handler): "
                + this.message;
        exceptionCaught(ctx, new PeerException(PeerException.AbortCause.PEER_ABORT, msg));
        return;//from   w  ww  . j  a  va 2 s .  com
    } else if (responseMessage.type() == Message.Type.EXCEPTION) {
        String msg = "Message caused an exception on the other side, handle as peer_abort: " + this.message;
        exceptionCaught(ctx, new PeerException(PeerException.AbortCause.PEER_ABORT, msg));
        return;
    } else if (responseMessage.isRequest()) {
        ctx.fireChannelRead(responseMessage);
        return;
    } else if (!sendMessageID.equals(recvMessageID)) {
        String msg = "Message [" + responseMessage
                + "] sent to the node is not the same as we expect. We sent [" + this.message + "]";
        exceptionCaught(ctx, new PeerException(PeerException.AbortCause.PEER_ABORT, msg));
        return;
    } else if (responseMessage.command() != RPC.Commands.RCON.getNr()
            && message.recipient().isRelayed() != responseMessage.sender().isRelayed()) {
        String msg = "Message [" + responseMessage + "] sent has a different relay flag than we sent ["
                + this.message + "]. Recipient (" + message.recipient().isRelayed() + ") / Sender ("
                + responseMessage.sender().isRelayed() + ")";
        exceptionCaught(ctx, new PeerException(PeerException.AbortCause.PEER_ABORT, msg));
        return;
    }

    //NAT reflection, reverse lookup
    PeerAddress realAddress = peerBean.localMap().translateReverse(responseMessage.sender());
    if (realAddress != null) {
        responseMessage.sender(realAddress);
    }

    // Stop time measurement of RTT
    futureResponse.stopRTTMeasurement();

    // We got a good answer, let's mark the sender as alive
    //if its an announce, the peer status will be handled in the RPC
    if (responseMessage.command() != RPC.Commands.LOCAL_ANNOUNCE.getNr()
            && (responseMessage.isOk() || responseMessage.isNotOk())) {
        peerBean.notifyPeerFound(responseMessage.sender(), null, null, futureResponse.getRoundTripTime());
    }

    // call this for streaming support
    if (!responseMessage.isDone()) {
        LOG.debug("good message is streaming {}", responseMessage);
        return;
    }

    // support slow, unreachable devices which cannot respond instantly
    if (this.message.recipient().isRelayed() && this.message.recipient().isSlow()
            && responseMessage.type() == Message.Type.PARTIALLY_OK) {
        LOG.debug("Received partially ok by the relay peer. Wait for answer of the unreachable peer.");
        // wait for the (real) answer of the unreachable peer.
        connectionBean.dispatcher().addPendingRequest(message.messageId(), futureResponse,
                slowResponseTimeoutSeconds, connectionBean.timer());
        // close the channel to the relay peer
        ctx.close();
        return;
    }

    if (!message.isKeepAlive()) {
        LOG.debug("good message, we can close {}, {}", responseMessage, ctx.channel());
        //set the success now, but trigger the notify when we closed the channel.
        futureResponse.responseLater(responseMessage);
        //the channel creater adds a listener that sets futureResponse.setResponseNow, when the channel is closed
        ctx.close();
    } else {
        LOG.debug("good message, leave open {}", responseMessage);
        futureResponse.response(responseMessage);
    }
}

From source file:net.tomp2p.message.TestMessage.java

License:Apache License

/**
 * Mock Nettys ChannelHandlerContext with the minimal functions.
 * /*from   w ww .  ja va2  s. c  o  m*/
 * @param buf
 *            The buffer to use for decoding
 * @param m2
 *            The message reference to store the result
 * @return The mocked ChannelHandlerContext
 */
@SuppressWarnings("unchecked")
private ChannelHandlerContext mockChannelHandlerContext(final AlternativeCompositeByteBuf buf,
        final AtomicReference<Message> m2) {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    ByteBufAllocator alloc = mock(ByteBufAllocator.class);
    when(ctx.alloc()).thenReturn(alloc);
    when(alloc.ioBuffer()).thenReturn(buf);

    DatagramChannel dc = mock(DatagramChannel.class);
    when(ctx.channel()).thenReturn(dc);
    when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(null);

    Attribute<InetSocketAddress> attr = mock(Attribute.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(attr);

    when(ctx.fireChannelRead(any())).then(new Answer<Void>() {
        @Override
        public Void answer(final InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            m2.set((Message) args[0]);
            return null;
        }
    });

    when(ctx.fireExceptionCaught(any(Throwable.class))).then(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            for (Object obj : args) {
                if (obj instanceof Throwable) {
                    ((Throwable) obj).printStackTrace();
                } else {
                    System.err.println("Err: " + obj);
                }
            }
            return null;
        }

    });

    return ctx;
}

From source file:netty.protocol.netty.client.LoginAuthReqHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * <p>/* w  w  w.j  a  v a2  s.  com*/
 * Sub-classes may override this method to change behavior.
 */
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ??????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        byte loginResult = (byte) message.getBody();
        if (loginResult != (byte) 0) {
            // ?
            ctx.close();
        } else {
            System.out.println("Login is ok : " + message);
            ctx.fireChannelRead(msg);
        }
    } else
        ctx.fireChannelRead(msg);
}