Example usage for io.netty.channel ChannelHandlerContext fireUserEventTriggered

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext fireUserEventTriggered(Object evt);

Source Link

Usage

From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof UpgradeEvent) {
        // Generate the initial Http2Settings frame,
        // so that the next handler knows the protocol upgrade occurred as well.
        ctx.fireChannelRead(DEFAULT_HTTP2_SETTINGS);

        // Continue handling the upgrade request after the upgrade is complete.
        final FullHttpRequest nettyReq = ((UpgradeEvent) evt).upgradeRequest();

        // Remove the headers related with the upgrade.
        nettyReq.headers().remove(HttpHeaderNames.CONNECTION);
        nettyReq.headers().remove(HttpHeaderNames.UPGRADE);
        nettyReq.headers().remove(Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER);

        if (logger.isDebugEnabled()) {
            logger.debug("{} Handling the pre-upgrade request ({}): {} {} {} ({}B)", ctx.channel(),
                    ((UpgradeEvent) evt).protocol(), nettyReq.method(), nettyReq.uri(),
                    nettyReq.protocolVersion(), nettyReq.content().readableBytes());
        }//from w  ww.  j  a v  a2 s .c o  m

        channelRead(ctx, nettyReq);
        channelReadComplete(ctx);
        return;
    }

    ctx.fireUserEventTriggered(evt);
}

From source file:com.linkedin.r2.transport.http.client.Http2AlpnHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
        if (handshakeEvent.isSuccess()) {
            LOG.debug("SSL handshake succeeded");
            SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
            if (sslHandler == null) {
                ctx.fireExceptionCaught(
                        new IllegalStateException("cannot find a SslHandler in the pipeline (required for "
                                + "application-level protocol negotiation)"));
                return;
            }/*from   ww w  . j  av  a  2 s.c o m*/
            String protocol = sslHandler.applicationProtocol();
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                LOG.debug("HTTP/2 is negotiated");

                // Add HTTP/2 handler
                ctx.pipeline().addAfter("sslHandler", "http2Handler", _http2Handler);

                // Remove handler from pipeline after negotiation is complete
                ctx.pipeline().remove(this);
                _alpnPromise.setSuccess();
            } else {
                LOG.error("Protocol {}, instead of HTTP/2, is negotiated through ALPN", protocol);
                _alpnPromise.setFailure(new IllegalStateException("HTTP/2 ALPN negotiation failed"));
            }
        } else {
            LOG.error("SSL handshake failed", handshakeEvent.cause());
            _alpnPromise.setFailure(handshakeEvent.cause());
        }
    }

    ctx.fireUserEventTriggered(evt);
}

From source file:com.linkedin.r2.transport.http.client.Http2FrameListener.java

License:Apache License

@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
    LOG.debug("Received HTTP/2 SETTINGS frame, settings={}", settings);
    ctx.fireUserEventTriggered(FrameEvent.SETTINGS_FRAME_RECEIVED);
}

From source file:com.linkedin.r2.transport.http.client.Http2UpgradeHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    LOG.debug("Received user event {}", evt);
    if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_ISSUED) {
        LOG.debug("HTTP/2 clear text upgrade issued");
    } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_SUCCESSFUL) {
        LOG.debug("HTTP/2 clear text upgrade successful");
    } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_REJECTED) {
        LOG.error("HTTP/2 clear text upgrade failed");
        _upgradePromise.setFailure(new IllegalStateException("HTTP/2 clear text upgrade failed"));
    } else if (evt == Http2FrameListener.FrameEvent.SETTINGS_FRAME_RECEIVED) {
        LOG.debug("HTTP/2 settings frame received");
        // Remove handler from pipeline after upgrade is successful
        ctx.pipeline().remove(this);
        _upgradePromise.setSuccess();//from  w ww  . j a  v a  2  s  . c  o  m
    }
    ctx.fireUserEventTriggered(evt);
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPCodec.java

License:Apache License

@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    if (!session.handshakeFuture().isDone()) {
        session.handshakeFailure(new ClosedChannelException());
        ctx.fireUserEventTriggered(new ZMTPHandshakeFailure(session));
    }/*from  ww  w  . ja  va2 s.  c o m*/
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPCodec.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {

    // Discard input if handshake failed. It is expected that the user will close the channel.
    if (session.handshakeFuture().isDone()) {
        assert !session.handshakeFuture().isSuccess();
        in.skipBytes(in.readableBytes());
    }//from  ww  w.ja va 2s . co  m

    // Shake hands
    final ZMTPHandshake handshake;
    try {
        handshake = handshaker.handshake(in, ctx);
        if (handshake == null) {
            // Handshake is not yet done. Await more input.
            return;
        }
    } catch (Exception e) {
        session.handshakeFailure(e);
        ctx.fireUserEventTriggered(new ZMTPHandshakeFailure(session));
        throw e;
    }

    // Handshake is done.
    session.handshakeSuccess(handshake);

    // Replace this handler with the framing encoder and decoder
    if (actualReadableBytes() > 0) {
        out.add(in.readBytes(actualReadableBytes()));
    }
    final ZMTPDecoder decoder = config.decoder().decoder(session);
    final ZMTPEncoder encoder = config.encoder().encoder(session);
    final ZMTPWireFormat wireFormat = ZMTPWireFormats.wireFormat(session.negotiatedVersion());
    final ChannelHandler handler = new CombinedChannelDuplexHandler<ZMTPFramingDecoder, ZMTPFramingEncoder>(
            new ZMTPFramingDecoder(wireFormat, decoder), new ZMTPFramingEncoder(wireFormat, encoder));
    ctx.pipeline().replace(this, ctx.name(), handler);

    // Tell the user that the handshake is complete
    ctx.fireUserEventTriggered(new ZMTPHandshakeSuccess(session, handshake));
}

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/*from  w ww.  j a  va2s  .c  o 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.inbound.TransactionInboundHandler.java

License:Open Source License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    logger.trace("User event received: {}", evt);
    if (evt instanceof DataFrameSentEvent) {
        DataFrameSentEvent dfse = (DataFrameSentEvent) evt;
        logger.trace("Detected data frame write event: {}", dfse.getDataFrame());
        if (!hasCurrentTransaction()) {
            currentDataFrameTransaction = dfse.getDataFrame().createWrapperTransaction(dfse.isListeningNode());
            if (currentDataFrameTransaction != null) {
                logger.trace("*** Data frame transaction started for {} with ID {}", dfse.getDataFrame(),
                        currentDataFrameTransaction.getId());
                // start timeout timer
                if (currentDataFrameTransaction.getTimeout() > 0 && handlerContext != null
                        && handlerContext.executor() != null) {
                    timeoutFuture = handlerContext.executor()
                            .schedule(//ww  w .ja v  a2s .c om
                                    new TransactionTimeoutHandler(currentDataFrameTransaction.getId(),
                                            handlerContext, this),
                                    currentDataFrameTransaction.getTimeout(), TimeUnit.MILLISECONDS);
                } else {
                    logger.warn("Unable to schedule transaction timeout callback");
                }
                ctx.fireUserEventTriggered(new TransactionStartedEvent(currentDataFrameTransaction.getId()));
            }
        } else {
            logger.trace("Wrote a data frame with a current transaction: {}", dfse.getDataFrame());
        }
    } else if (evt instanceof TransactionTimeoutEvent) {
        TransactionTimeoutEvent tte = (TransactionTimeoutEvent) evt;
        if (tte.getId().equals(currentDataFrameTransaction.getId())) {
            logger.trace("Detected transaction timeout");
            if (currentDataFrameTransaction.shouldRetry()) {
                attemptResend(ctx);
            } else {
                clearTransaction();
                ctx.fireUserEventTriggered(new TransactionFailedEvent(tte.getId()));
            }
        } else {
            logger.error("Received timeout event for unknown transaction: {}", tte.getId());
        }
    } else {
        ctx.fireUserEventTriggered(evt);
    }
}

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

License:Open Source License

private void attemptResend(ChannelHandlerContext ctx) {
    DataFrame startFrame = currentDataFrameTransaction.getStartFrame();
    if (startFrame.getSendCount() < MAX_SEND_COUNT) {
        logger.debug("Transaction has failed - will reset and resend initial request");
        currentDataFrameTransaction.reset();
        // if a CAN was received, then we decrement the send count by one so this attempt doesn't count
        // towards the maximum resend count
        ctx.channel().writeAndFlush(//  ww w .  j a  v a2 s  . co m
                new OutboundDataFrame(startFrame, currentDataFrameTransaction.isListeningNode()));
    } else {
        logger.debug("Transaction has failed and has exceeded max resends");
        String id = currentDataFrameTransaction.getId();
        clearTransaction();
        ctx.fireUserEventTriggered(new TransactionFailedEvent(id));
    }
}

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

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    logger.trace("write: " + msg);
    if (msg instanceof OutboundDataFrame) {
        OutboundDataFrame odf = (OutboundDataFrame) msg;
        if (currentTransactionId == null || odf.matchesTransaction(currentTransactionId)) {
            ctx.writeAndFlush(odf.getDataFrame(), promise);
            odf.getDataFrame().incremenentSendCount();
            ctx.fireUserEventTriggered(new DataFrameSentEvent(odf.getDataFrame(), odf.isListeningNode()));
        } else {//w w  w.j av  a  2  s  . co  m
            logger.trace("Queueing data frame: {}", msg);
            pendingQueue.add(new FrameWrite(odf.getDataFrame(), odf.isListeningNode(), promise));
        }
    } else if (msg instanceof TransactionStartedEvent) {
        currentTransactionId = ((TransactionStartedEvent) msg).getId();
        logger.trace("Detected data frame transaction start: {}", currentTransactionId);
    } else if (msg instanceof TransactionCompletedEvent) {
        logger.trace("Detected data frame transaction completion: {}", currentTransactionId);
        currentTransactionId = null;
        sendNextFrame(ctx);
    } else if (msg instanceof TransactionFailedEvent) {
        logger.trace("Detected data frame transaction failure: {}", currentTransactionId);
        currentTransactionId = null;
        sendNextFrame(ctx);
    } else if (msg instanceof ACK) {
        ctx.writeAndFlush(msg, promise);
    } else {
        logger.error("Direct DataFrame write attempt detected");
    }
}