Example usage for io.netty.channel ChannelHandlerContext pipeline

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

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:org.traccar.handler.TimeHandler.java

License:Apache License

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

    if (msg instanceof Position && (protocols == null
            || protocols.contains(ctx.pipeline().get(BaseProtocolDecoder.class).getProtocolName()))) {

        Position position = (Position) msg;
        if (useServerTime) {
            position.setDeviceTime(position.getServerTime());
        }//ww  w  .  j a v  a 2  s.  c o  m
        position.setFixTime(position.getDeviceTime());

    }
    ctx.fireChannelRead(msg);
}

From source file:org.traccar.MainEventHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) {
    LOGGER.info(formatChannel(ctx.channel()) + " disconnected");
    closeChannel(ctx.channel());/*from  ww  w .j a  v a  2s .c o  m*/

    if (BasePipelineFactory.getHandler(ctx.pipeline(), HttpRequestDecoder.class) == null
            && !connectionlessProtocols
                    .contains(ctx.pipeline().get(BaseProtocolDecoder.class).getProtocolName())) {
        Context.getConnectionManager().removeActiveDevice(ctx.channel());
    }
}

From source file:org.traccar.protocol.NavisFrameDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {

    if (buf.getByte(buf.readerIndex()) == 0x7F) {
        return buf.readRetainedSlice(1); // keep alive
    }//  w ww  . ja v  a  2  s.  co  m

    if (ctx != null && flexDataSize == 0) {
        NavisProtocolDecoder protocolDecoder = BasePipelineFactory.getHandler(ctx.pipeline(),
                NavisProtocolDecoder.class);
        if (protocolDecoder != null) {
            flexDataSize = protocolDecoder.getFlexDataSize();
        }
    }

    if (flexDataSize > 0) {

        if (buf.readableBytes() > FLEX_HEADER_LENGTH) {
            int length = 0;
            String type = buf.toString(buf.readerIndex(), 2, StandardCharsets.US_ASCII);
            switch (type) {
            // FLEX 1.0
            case "~A":
                length = flexDataSize * buf.getByte(buf.readerIndex() + FLEX_HEADER_LENGTH) + 1 + 1;
                break;
            case "~T":
                length = flexDataSize + 4 + 1;
                break;
            case "~C":
                length = flexDataSize + 1;
                break;
            // FLEX 2.0 (Extra packages)
            case "~E":
                length++;
                for (int i = 0; i < buf.getByte(buf.readerIndex() + FLEX_HEADER_LENGTH); i++) {
                    if (buf.readableBytes() > FLEX_HEADER_LENGTH + length + 1) {
                        length += buf.getUnsignedShort(length + FLEX_HEADER_LENGTH) + 2;
                    } else {
                        return null;
                    }
                }
                length++;
                break;
            case "~X":
                length = buf.getUnsignedShortLE(buf.readerIndex() + FLEX_HEADER_LENGTH) + 4 + 1;
                break;
            default:
                return null;
            }

            if (buf.readableBytes() >= FLEX_HEADER_LENGTH + length) {
                return buf.readRetainedSlice(buf.readableBytes());
            }
        }

    } else {

        if (buf.readableBytes() < NTCB_HEADER_LENGTH) {
            return null;
        }

        int length = NTCB_HEADER_LENGTH + buf.getUnsignedShortLE(buf.readerIndex() + NTCB_LENGTH_OFFSET);
        if (buf.readableBytes() >= length) {
            return buf.readRetainedSlice(length);
        }

    }

    return null;
}

From source file:org.vertx.java.core.http.impl.VertxHttpHandler.java

License:Open Source License

@Override
protected void channelRead(final C connection, final DefaultContext context, final ChannelHandlerContext chctx,
        final Object msg) throws Exception {
    if (connection != null) {
        // we are reading from the channel
        Channel ch = chctx.channel();
        // We need to do this since it's possible the server is being used from a worker context
        if (context.isOnCorrectWorker(ch.eventLoop())) {
            try {
                vertx.setContext(context);
                doMessageReceived(connection, chctx, msg);
            } catch (Throwable t) {
                context.reportException(t);
            }//  w  w  w  .  ja v  a  2s.c  o m
        } else {
            context.execute(new Runnable() {
                public void run() {
                    try {
                        doMessageReceived(connection, chctx, msg);
                    } catch (Throwable t) {
                        context.reportException(t);
                    }
                }
            });
        }
    } else {
        try {
            doMessageReceived(connection, chctx, msg);
        } catch (Throwable t) {
            chctx.pipeline().fireExceptionCaught(t);
        }
    }
}

From source file:org.virtue.network.protocol.handshake.HandshakeDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    if (buf.isReadable()) {
        HandshakeMessage type = new HandshakeMessage(buf.readUnsignedByte());
        if (type.getType() == null) {
            ctx.close();//Disconnect the player if they have an invalid handshake code.
            return;
        }/*from  w  ww .  ja v a 2 s . c o  m*/
        switch (type.getType()) {
        case HANDSHAKE_LOGIN:
            ensureResponse(ctx);
            ctx.pipeline().replace("decoder", "decoder", new LoginDecoder());
            ctx.pipeline().addBefore("decoder", "encoder", new LoginEncoder());
            break;
        case HANDSHAKE_ONDEMAND:
            ensureResponse(ctx, buf);
            ctx.pipeline().replace("decoder", "decoder", new OnDemandDecoder());
            ctx.pipeline().addAfter("decoder", "xor-encoder", new OnDemandXorEncoder());
            ctx.pipeline().addAfter("xor-encoder", "encoder", new OnDemandEncoder());
            break;
        case HANDHSHAKE_CREATION:
            ctx.pipeline().replace("decoder", "decoder", new CreationDecoder());
            break;
        case HANDSHAKE_SOCIAL_LOGIN:
            ensureResponse(ctx);
            ctx.pipeline().replace("decoder", "decoder", new SocialNetworkDecoder());
            break;
        default:
            break;
        }
        //ctx.pipeline().remove(HandshakeDecoder.class);
        //if (buf.isReadable()) {
        //out.add(new Object[] { type, buf.readBytes(buf.readableBytes()) });
        //} else {
        out.add(type);
        //}
    }
}

From source file:org.waarp.ftp.core.control.NetworkHandler.java

License:Open Source License

/**
 * Execute one command and write the following answer
 *///from   www  . ja v a2 s .  c o m
private void messageRunAnswer(final ChannelHandlerContext ctx) {
    boolean error = false;
    logger.debug("Code: " + session.getCurrentCommand().getCode());
    try {
        businessHandler.beforeRunCommand();
        AbstractCommand command = session.getCurrentCommand();
        logger.debug("Run {}", command.getCommand());
        command.exec();
        businessHandler.afterRunCommandOk();
    } catch (CommandAbstractException e) {
        logger.debug("Command in error", e);
        error = true;
        session.setReplyCode(e);
        businessHandler.afterRunCommandKo(e);
    }
    logger.debug("Code: " + session.getCurrentCommand().getCode() + " [" + session.getReplyCode() + "]");
    if (error) {
        if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
            writeFinalAnswer(ctx);
        }
        // In error so Check that Data is closed
        if (session.getDataConn().isActive()) {
            logger.debug("Closing DataChannel while command is in error");
            try {
                session.getDataConn().getCurrentDataChannel().close();
            } catch (FtpNoConnectionException e) {
                // ignore
            }
        }
        return;
    }
    if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH
            || session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
        controlChannel.config().setAutoRead(false);
        ChannelFuture future = writeIntermediateAnswer(ctx);
        session.setCurrentCommandFinished();
        if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH) {
            logger.debug("SSL to be added to pipeline");
            ChannelHandler sslHandler = ctx.pipeline().first();
            if (sslHandler instanceof SslHandler) {
                logger.debug("Already got a SslHandler");
            } else {
                logger.debug("Add Explicitely SSL support to Command");
                // add the SSL support
                sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true,
                        FtpsInitializer.waarpSslContextFactory.needClientAuthentication());
                session.prepareSsl();
                WaarpSslUtility.addSslHandler(future, ctx.pipeline(), sslHandler,
                        new GenericFutureListener<Future<? super Channel>>() {
                            public void operationComplete(Future<? super Channel> future) throws Exception {
                                logger.debug("Handshake: " + future.isSuccess() + ":"
                                        + ((Channel) future.get()).toString(), future.cause());
                                if (!future.isSuccess()) {
                                    String error2 = future.cause() != null ? future.cause().getMessage()
                                            : "During Handshake";
                                    logger.error("Cannot finalize Ssl Command channel " + error2);
                                    callForSnmp("SSL Connection Error", error2);
                                    session.setSsl(false);
                                    ctx.close();
                                } else {
                                    logger.debug("End of initialization of SSL and command channel: "
                                            + ctx.channel());
                                    session.setSsl(true);
                                }
                            }
                        });
            }
        } else if (session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
            logger.debug("SSL to be removed from pipeline");
            // remove the SSL support
            session.prepareSsl();
            WaarpSslUtility.removingSslHandler(future, controlChannel, false);
        }
    } else if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
        writeFinalAnswer(ctx);
    }
}

From source file:org.waarp.ftp.core.data.handler.DataNetworkHandler.java

License:Open Source License

/**
 * Initialize the Handler./*from w ww  .j  a  v  a2s  .  co m*/
 * 
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    if (session == null) {
        setSession(channel);
    }
    if (session == null) {
        return;
    }
    channelPipeline = ctx.pipeline();
    dataChannel = channel;
    dataBusinessHandler.setFtpSession(getFtpSession());
    FtpChannelUtils.addDataChannel(channel, session.getConfiguration());
    logger.debug("DataChannel connected: " + session.getReplyCode());
    if (session.getReplyCode().getCode() >= 400) {
        // shall not be except if an error early occurs
        switch (session.getCurrentCommand().getCode()) {
        case RETR:
        case APPE:
        case STOR:
        case STOU:
            // close the data channel immediately
            logger.debug("DataChannel immediately closed since " + session.getCurrentCommand().getCode()
                    + " is not ok at startup");
            ctx.close();
            return;
        default:
            break;
        }
    }
    if (isStillAlive()) {
        setCorrectCodec();
        unlockModeCodec();
        session.getDataConn().getFtpTransferControl().setOpenedDataChannel(channel, this);
    } else {
        // Cannot continue
        logger.debug("Connected but no more alive so will disconnect");
        session.getDataConn().getFtpTransferControl().setOpenedDataChannel(null, this);
        return;
    }
    isReady = true;
}

From source file:org.waarp.ftp.core.data.handler.ftps.FtpsTemporaryFirstHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // Get the SslHandler in the current pipeline.
    Channel channel = ctx.channel();

    if (session == null) {
        setSession(channel);/* w  ww. j av a 2s.co  m*/
    }
    if (session == null) {
        logger.error("Cannot find session for SSL");
        return;
    }
    // Server: no renegotiation still, but possible clientAuthent
    // Mode is always as SSL Server mode.
    SslHandler sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true,
            FtpsInitializer.waarpSslContextFactory.needClientAuthentication(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getAddress()
                    .getHostAddress(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getPort());
    WaarpSslUtility.addSslOpenedChannel(channel);
    // Get the SslHandler and begin handshake ASAP.
    logger.debug("SSL found but need handshake: " + ctx.channel().toString());
    final FtpsTemporaryFirstHandler myself = this;
    WaarpSslUtility.addSslHandler(null, ctx.pipeline(), sslHandler,
            new GenericFutureListener<Future<? super Channel>>() {
                public void operationComplete(Future<? super Channel> future) throws Exception {
                    logger.debug("Handshake: " + future.isSuccess() + ":" + ((Channel) future.get()).toString(),
                            future.cause());
                    if (future.isSuccess()) {
                        logger.debug("End of initialization of SSL and data channel");
                        myself.superChannelActive(ctx);
                        ctx.pipeline().remove(myself);
                    } else {
                        ctx.close();
                    }
                }
            });
}

From source file:org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    // Make sure if the length field was received.
    if (buf.readableBytes() < 4) {
        // The length field was not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return;/*from  ww  w . j  a v a2 s  .  c  o m*/
    }
    // Mark the current buffer position
    buf.markReaderIndex();
    // Read the length field
    final int length = buf.readInt();
    if (length < 9) {
        throw new OpenR66ProtocolPacketException(
                "Incorrect decode first field in Network Packet: " + length + " < 9");
    }
    if (buf.readableBytes() < length) {
        buf.resetReaderIndex();
        return;
    }
    // Now we can read the two Ids
    final int localId = buf.readInt();
    final int remoteId = buf.readInt();
    final byte code = buf.readByte();
    int readerInder = buf.readerIndex();
    ByteBuf buffer = buf.slice(readerInder, length - 9);
    buffer.retain();
    buf.skipBytes(length - 9);
    NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer);
    if (code == LocalPacketFactory.KEEPALIVEPACKET) {
        KeepAlivePacket keepAlivePacket = (KeepAlivePacket) LocalPacketCodec
                .decodeNetworkPacket(networkPacket.getBuffer());
        if (keepAlivePacket.isToValidate()) {
            keepAlivePacket.validate();
            NetworkPacket response = new NetworkPacket(ChannelUtils.NOCHANNEL, ChannelUtils.NOCHANNEL,
                    keepAlivePacket, null);
            NetworkChannelReference nc = NetworkTransaction.getImmediateNetworkChannel(ctx.channel());
            if (nc != null) {
                nc.useIfUsed();
            }
            ctx.writeAndFlush(response.getNetworkPacket());
            buffer.release();
        }
        // Replaced by a NoOp packet
        networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket(), null);
        NetworkServerHandler nsh = (NetworkServerHandler) ctx.pipeline().last();
        nsh.setKeepAlivedSent();
    }
    out.add(networkPacket);
}

From source file:org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel networkChannel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(networkChannel);
    isSSL = true;//from   www .j  a  va2 s.  c  o m
    // Check first if allowed
    if (NetworkTransaction.isBlacklisted(networkChannel)) {
        logger.warn("Connection refused since Partner is in BlackListed from "
                + networkChannel.remoteAddress().toString());
        isBlackListed = true;
        if (Configuration.configuration.getR66Mib() != null) {
            Configuration.configuration.getR66Mib().notifyError("Black Listed connection temptative",
                    "During Handshake");
        }
        // close immediately the connection
        WaarpSslUtility.closingSslChannel(networkChannel);
        return;
    }
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}