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.tesora.dve.db.mysql.portal.MSPCommandHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof MSPMessage)) {
        ctx.fireChannelRead(msg); //not for us, maybe someone further in the stack can handle it.
        return;//  ww w. j  a  va 2s. co  m
    }

    final SSConnection ssCon = ctx.channel().attr(ConnectionHandlerAdapter.SSCON_KEY).get();
    try {

        //we start the timer here, outside the submit/callable, so that we include any delay in submission/execution around the thread pool.
        final Timer frontendRequest = timingService.startSubTimer(TimingDesc.FRONTEND_ROUND_TRIP);

        final MSPMessage mspMessage = (MSPMessage) msg;
        final byte theMessageType = mspMessage.getMysqlMessageType();

        clientExecutorService.submit(new Callable<Void>() {
            public Void call() throws Exception {
                ssCon.executeInContext(new Callable<Void>() {
                    public Void call() {
                        //bind the frontend timer to this thread, so that new sub-timers on this thread (planning, backend, etc ) will be children of the frontend request timer.
                        timingService.attachTimerOnThread(frontendRequest);
                        try {
                            MSPAction mspAction = instanceExecutor[theMessageType];
                            //TODO:need to get load data to play nice, this special casing violates the MSPAction abstraction and the copy/regex runs for every statement, even though 'load data' is uncommon. -sgossard
                            if (mspMessage instanceof MSPComQueryRequestMessage
                                    && (isLoadDataStmt((MSPComQueryRequestMessage) mspMessage))) {
                                MSPComQueryRequestMessage queryMessage = (MSPComQueryRequestMessage) mspMessage;
                                executeLoadDataStatement(clientExecutorService, ctx, ssCon, queryMessage);
                            } else {
                                mspAction.execute(clientExecutorService, ctx, ssCon, mspMessage);
                            }
                        } catch (Throwable t) {
                            ctx.fireExceptionCaught(t);
                        } finally {
                            ReferenceCountUtil.release(mspMessage);//we processed the message, so we are responsible for cleaning it up.
                            frontendRequest.end();
                            timingService.detachTimerOnThread();
                        }
                        return null;
                    }
                });
                return null;
            }
        });
    } finally {
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.InboundMysqlAuthenticationHandlerV10.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    boolean forwarded = false;
    try {//  w ww  .jav  a 2  s.c  om
        switch (currentAuthState) {
        case AUTHENTICATED:
            //already authenticated, pass decoded message through to other handler.
            forwarded = true;
            ctx.fireChannelRead(msg);
            break;
        case FAILED:
            ReferenceCountUtil.release(msg);
            ctx.channel().close();
            break;
        case UNAUTHENTICATED: {
            if (!(msg instanceof MSPAuthenticateV10MessageMessage))
                throw new PECodingException("Expecting authentication message, received, " + msg);

            MSPAuthenticateV10MessageMessage authMessage = (MSPAuthenticateV10MessageMessage) msg;
            authenticateClient(ctx, authMessage);
        }
            break;
        default:
            throw new PECodingException("Unexpected authorization state, " + currentAuthState);
        }
    } finally {
        if (!forwarded)
            ReferenceCountUtil.release(msg);
    }

}

From source file:com.twocater.diamond.core.netty.http.HttpDecoder.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    LoggerConstant.nettyHandlerLog.debug("{}", new Object[] { ctx.channel() });

    FullHttpRequest request = (FullHttpRequest) msg;

    try {//from   www  .  j a va 2s .c om
        if (request.getDecoderResult().isFailure()) {
            debug.debug("decoderfail:{}", request);
            ctx.close();
            return;
        }

        //        LoggingHandler

        HttpHeaders headers = request.headers();
        //        StringBuilder buf = new StringBuilder();
        //        if (!headers.isEmpty()) {
        //            for (Map.Entry<String, String> h : headers) {
        //                String key = h.getKey();
        //                String value = h.getValue();
        //                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
        //            }
        //            buf.append("\r\n");
        //        }
        //        System.out.println(buf.toString());

        // ?
        Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
        for (String name : headers.names()) {
            headersMap.put(name, headers.getAll(name));
        }

        // ??
        byte[] data = null;
        int n = request.content().readableBytes();
        if (n > 0) {
            data = new byte[n];
            request.content().readBytes(data);
        }

        HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.getMethod(),
                request.getProtocolVersion(), request.getUri(), headersMap, data);

        ctx.fireChannelRead(httpRequestMessage);

    } finally {
        // ???netty??
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpEventStreamHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!acceptInboundMessage(msg)) {
        this.resetState();
        // Send to the next handler without changing
        ctx.fireChannelRead(msg);
        return;//from  w  w  w .j  a  v  a 2 s .  com
    }

    switch (this.phase) {
    case NOT_INITIALIZED:
        HttpResponse response = (HttpResponse) msg;
        HttpHeaders headers = response.headers();
        String contentType = headers.get(Operation.CONTENT_TYPE_HEADER);
        if (Operation.MEDIA_TYPE_TEXT_EVENT_STREAM.equals(contentType)
                && response.status().code() == Operation.STATUS_CODE_OK) {
            this.phase = Phase.IN_EVENT_STREAM;
        } else {
            this.resetState();
            ctx.fireChannelRead(msg);
            return;
        }
        EventStreamHeadersMessage transformedMsg = new EventStreamHeadersMessage();
        transformedMsg.originalResponse = response;
        ctx.fireChannelRead(transformedMsg);
        return;
    case IN_EVENT_STREAM:
        ByteBuf content = ((HttpContent) msg).content();
        super.channelRead(ctx, content);
        return;
    default:
        this.resetState();
        ctx.fireChannelRead(msg);
    }
}

From source file:com.whizzosoftware.foscam.camera.discovery.DatagramToByteBufHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    // increment the datagram's byte buffer reference count and pass it along to the next part of the pipeline
    ctx.fireChannelRead(packet.content().retain());
}

From source file:com.whizzosoftware.hobson.hub.websockets.Authorizer.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception {
    logger.trace("channelRead0: {}", message);

    // attempt to get token from header and then from cookie
    String token = null;//from  www.  jav  a 2s . c  om
    String h = HttpHeaders.getHeader(message, "Authorization");
    if (h != null && h.startsWith("Bearer ") && h.length() > 7) {
        token = h.substring(7, h.length()).trim();
    } else {
        h = HttpHeaders.getHeader(message, "Cookie");
        if (h != null) {
            Set<Cookie> cookies = CookieDecoder.decode(h);
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if ("Token".equalsIgnoreCase(c.getName())) {
                        token = c.getValue();
                    }
                }
            }
        }
    }

    // if we found a token, process the message
    if (token != null) {
        try {
            HobsonUser user = accessManager.authenticate(token);
            accessManager.authorize(user, AuthorizationAction.HUB_READ, null);
            if (user != null) {
                logger.trace("Found token, passing message along");
                ctx.fireChannelRead(message.retain());
            }
        } catch (Exception e) {
            logger.debug("Token decryption error", e);
        }
    } else {
        logger.debug("No token found; closing connection");
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.UNAUTHORIZED);
        response.headers().add("Content-Length", 0);
        ctx.writeAndFlush(response);
        ctx.close();
    }
}

From source file:com.whizzosoftware.wzwave.channel.AcknowledgementInboundHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof DataFrame) {
        logger.trace("Sending ACK for received data frame: {}", msg);
        ctx.channel().writeAndFlush(new ACK());
    }/*from   w w w . j a v a 2  s .co  m*/
    ctx.fireChannelRead(msg);
}

From source file:com.whizzosoftware.wzwave.channel.inbound.TransactionInboundHandler.java

License:Open Source License

/**
 * Called when data is read from the Z-Wave network.
 *
 * @param ctx the handler context/*w  ww . j  av  a  2  s.co m*/
 * @param msg the message that was read
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof Frame) {
        Frame frame = (Frame) msg;
        if (hasCurrentTransaction()) {
            String tid = currentDataFrameTransaction.getId();
            logger.trace("Received frame within transaction ({}) context: {}", tid, frame);

            // give new frame to current transaction
            if (currentDataFrameTransaction.addFrame(frame)) {
                if (currentDataFrameTransaction.isComplete()) {
                    // cancel the timeout callback
                    if (timeoutFuture != null) {
                        timeoutFuture.cancel(true);
                        timeoutFuture = null;
                    }

                    if (!currentDataFrameTransaction.hasError()) {
                        DataFrame finalFrame = currentDataFrameTransaction.getFinalFrame();
                        logger.trace("*** Data frame transaction ({}) completed with final frame: {}", tid,
                                finalFrame);
                        logger.trace("");

                        // if there's an ApplicationUpdate with no node ID (e.g. when there's a app update failure), attempt
                        // to set the node ID based on the request frame that triggered it
                        if (finalFrame instanceof ApplicationUpdate) {
                            ApplicationUpdate update = (ApplicationUpdate) finalFrame;
                            if ((update.getNodeId() == null || update.getNodeId() == 0)
                                    && currentDataFrameTransaction.getStartFrame() instanceof RequestNodeInfo) {
                                update.setNodeId(((RequestNodeInfo) currentDataFrameTransaction.getStartFrame())
                                        .getNodeId());
                            }
                        }

                        clearTransaction();
                        ctx.fireUserEventTriggered(new TransactionCompletedEvent(tid, finalFrame));
                    } else if (currentDataFrameTransaction.shouldRetry()) {
                        attemptResend(ctx);
                    } else {
                        logger.trace("*** Data frame transaction ({}) failed", tid);
                        logger.trace("");
                        clearTransaction();
                        ctx.fireUserEventTriggered(new TransactionFailedEvent(tid));
                    }
                }
                // if transaction didn't consume frame, then pass it down the pipeline
            } else {
                logger.trace("Transaction ignored frame so passing it along");
                ctx.fireChannelRead(msg);
            }
        } else if (msg instanceof AddNodeToNetwork) {
            logger.trace("Received ADD_NODE_STATUS_NODE_FOUND; starting transaction");
            currentDataFrameTransaction = new NodeInclusionTransaction((DataFrame) msg);
        } else {
            logger.trace("Received frame outside of transaction context so passing it along: {}", frame);
            ctx.fireChannelRead(msg);
        }
    }
}

From source file:com.whizzosoftware.wzwave.channel.outbound.FrameQueueHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ctx.fireChannelRead(msg);
}

From source file:com.whizzosoftware.wzwave.channel.ZWaveDataFrameTransactionInboundHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof Frame) {
        Frame frame = (Frame) msg;
        if (hasCurrentRequestTransaction()) {
            logger.trace("Received frame within transaction context: {}", frame);

            if (currentDataFrameTransaction.addFrame(frame)) {
                if (currentDataFrameTransaction.isComplete()) {
                    // cancel the timeout callback
                    if (timeoutFuture != null) {
                        timeoutFuture.cancel(true);
                        timeoutFuture = null;
                    }//from   w ww .  ja  v  a2s .  c  om

                    // flag that we're in the process of completing a frame transaction so that any code that checks
                    // will know that the transaction isn't quite done yet
                    processingTransactionCompletion = true;

                    if (!currentDataFrameTransaction.hasError()) {
                        DataFrame finalFrame = currentDataFrameTransaction.getFinalFrame();
                        logger.trace("*** Data frame transaction completed with final frame: {}", finalFrame);
                        logger.trace("");

                        // if there's an ApplicationUpdate with no node ID (e.g. when there's a app update failure), attempt
                        // to set the node ID based on the request frame that triggered it
                        if (finalFrame instanceof ApplicationUpdate) {
                            ApplicationUpdate update = (ApplicationUpdate) finalFrame;
                            if ((update.getNodeId() == null || update.getNodeId() == 0)
                                    && currentDataFrameTransaction.getStartFrame() instanceof RequestNodeInfo) {
                                update.setNodeId(((RequestNodeInfo) currentDataFrameTransaction.getStartFrame())
                                        .getNodeId());
                            }
                        }

                        // pass the final frame down the pipeline
                        if (finalFrame != null) {
                            ctx.fireChannelRead(finalFrame);
                        }

                    } else {
                        attemptResend(ctx);
                    }

                    // clear the current transaction
                    currentDataFrameTransaction = null;

                    // now the frame transaction is truly done
                    processingTransactionCompletion = false;

                    // alert the outbound pipeline that a frame transaction has been completed
                    ChannelPipeline pipeline = ctx.pipeline();
                    if (pipeline != null) {
                        ZWaveQueuedOutboundHandler writeHandler = (ZWaveQueuedOutboundHandler) ctx.pipeline()
                                .get("writeQueue");
                        if (writeHandler != null) {
                            writeHandler.onDataFrameTransactionComplete();
                        }
                    }
                }
            } else {
                logger.trace("Transaction didn't consume frame so passing it along");
                ctx.fireChannelRead(msg);
            }
        } else {
            logger.trace("Received frame outside of transaction context: {}", frame);
            ctx.fireChannelRead(msg);
        }
    } else if (msg instanceof TransactionTimeout) {
        // if a timeout is received for the current transaction, attempt to resend; otherwise ignore it
        TransactionTimeout tt = (TransactionTimeout) msg;
        if (tt.getId().equals(currentDataFrameTransaction.getId())) {
            logger.trace("Transaction timed out");
            attemptResend(ctx);
        }
    }
}