Example usage for io.netty.channel ChannelPipeline addFirst

List of usage examples for io.netty.channel ChannelPipeline addFirst

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline addFirst.

Prototype

ChannelPipeline addFirst(EventExecutorGroup group, ChannelHandler... handlers);

Source Link

Document

Inserts ChannelHandler s at the first position of this pipeline.

Usage

From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandler.java

License:Apache License

/**
 * STEP 1: Channel is first created//ww  w .  j  ava2s.  c  o  m
 */
@Override
protected void initChannel(final Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    Class<? extends Channel> channelClass = channel.getClass();
    // because of the way TCP works, we have to have special readers/writers. For UDP, all data must be in a single packet.

    boolean isTcpChannel = ConnectionImpl.isTcpChannel(channelClass);
    boolean isUdpChannel = !isTcpChannel && ConnectionImpl.isUdpChannel(channelClass);

    if (isTcpChannel) {
        ///////////////////////
        // DECODE (or upstream)
        ///////////////////////
        pipeline.addFirst(FRAME_AND_KRYO_DECODER, new KryoDecoder(this.serializationManager)); // cannot be shared because of possible fragmentation.
    } else if (isUdpChannel) {
        // can be shared because there cannot be fragmentation for our UDP packets. If there is, we throw an error and continue...
        pipeline.addFirst(KRYO_DECODER, this.registrationWrapper.kryoUdpDecoder);
    }

    // this makes the proper event get raised in the registrationHandler to kill NEW idle connections. Once "connected" they last a lot longer.
    // we ALWAYS have this initial IDLE handler, so we don't have to worry about a SLOW-LORIS ATTACK against the server.
    // in Seconds -- not shared, because it is per-connection
    pipeline.addFirst(IDLE_HANDLER, new IdleStateHandler(2, 0, 0));

    if (isTcpChannel) {
        /////////////////////////
        // ENCODE (or downstream)
        /////////////////////////
        pipeline.addFirst(FRAME_AND_KRYO_ENCODER, this.registrationWrapper.kryoTcpEncoder); // this is shared
    } else if (isUdpChannel) {
        pipeline.addFirst(KRYO_ENCODER, this.registrationWrapper.kryoUdpEncoder);
    }
}

From source file:io.crate.mqtt.netty.Netty4MqttServerTransport.java

@Override
protected void doStart() {
    if (isEnterprise == false || isEnabled == false) {
        return;//from  w  w w .  j  a v  a  2s  .  c  o m
    }

    mqttIngestService.initialize();
    serverBootstrap = CrateChannelBootstrapFactory.newChannelBootstrap("mqtt", settings);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            final MqttProcessor processor = new MqttProcessor(mqttIngestService);
            final MqttNettyHandler handler = new MqttNettyHandler(processor);
            final MqttNettyIdleTimeoutHandler timeoutHandler = new MqttNettyIdleTimeoutHandler();
            final IdleStateHandler defaultIdleHandler = new IdleStateHandler(0L, 0L,
                    defaultIdleTimeout.seconds(), TimeUnit.SECONDS);

            pipeline.addFirst("idleStateHandler", defaultIdleHandler)
                    .addAfter("idleStateHandler", "idleEventHandler", timeoutHandler)
                    .addLast("decoder", new MqttDecoder()).addLast("encoder", MqttEncoder.INSTANCE)
                    .addLast("messageLogger", mqttMessageLogger).addLast("handler", handler);

            if (isMQTTSslEnabled(settings)) {
                SslHandler sslHandler = sslContextProvider.get().newHandler(pipeline.channel().alloc());
                pipeline.addFirst(sslHandler);
            }
        }
    });
    serverBootstrap.validate();

    boolean success = false;
    try {
        boundAddress = resolveBindAddress();
        logger.info("{}", boundAddress);
        success = true;
    } finally {
        if (!success) {
            doStop(); // stop boss/worker threads to avoid leaks
        }
    }
}

From source file:io.higgs.http.client.ClientIntializer.java

License:Apache License

/**
 * Adds an SSL engine to the given pipeline.
 *
 * @param pipeline     the pipeline to add SSL support to
 * @param forceToFront if true then the SSL handler is added to the front of the pipeline otherwise it is added
 *                     at the end//  w  ww. jav  a  2  s .c om
 */
public static void addSSL(ChannelPipeline pipeline, boolean forceToFront, String[] sslProtocols) {
    SSLEngine engine = SSLContextFactory.getSSLSocket(SSLConfigFactory.sslConfiguration).createSSLEngine();
    engine.setUseClientMode(true);
    if (sslProtocols != null && sslProtocols.length > 0) {
        engine.setEnabledProtocols(sslProtocols);
    }
    if (forceToFront) {
        pipeline.addFirst("ssl", new SslHandler(engine));
    } else {
        pipeline.addLast("ssl", new SslHandler(engine));
    }
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initializePlainTCPTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    int port = Integer.parseInt(props.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
    initFactory(host, port, new PipelineInitializer() {
        @Override/*  ww w .  j a v a 2  s. c om*/
        void init(ChannelPipeline pipeline) {
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            //pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR));
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initializeWebSocketTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
    String webSocketPortProp = props.getProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME);
    if (webSocketPortProp == null) {
        //Do nothing no WebSocket configured
        LOG.info("WebSocket is disabled");
        return;//from  w w w . ja  v a 2s  .  c  om
    }
    int port = Integer.parseInt(webSocketPortProp);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();

    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    initFactory(host, port, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) {
            pipeline.addLast("httpEncoder", new HttpResponseEncoder());
            pipeline.addLast("httpDecoder", new HttpRequestDecoder());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", "mqtt, mqttv3.1, mqttv3.1.1"));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props,
        final SSLContext sslContext) throws IOException {
    String sslPortProp = props.getProperty(BrokerConstants.SSL_PORT_PROPERTY_NAME);
    if (sslPortProp == null) {
        //Do nothing no SSL configured
        LOG.info("SSL is disabled");
        return;//from www  .  ja v a 2  s. c o m
    }

    int sslPort = Integer.parseInt(sslPortProp);
    LOG.info("Starting SSL on port {}", sslPort);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
    final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
    initFactory(host, sslPort, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) throws Exception {
            pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            //pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR));
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
        throws IOException {
    String sslPortProp = props.getProperty(BrokerConstants.WSS_PORT_PROPERTY_NAME);
    if (sslPortProp == null) {
        //Do nothing no SSL configured
        LOG.info("SSL is disabled");
        return;/*from  w w w  .  j  ava  2s .co  m*/
    }
    int sslPort = Integer.parseInt(sslPortProp);
    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
    final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
    initFactory(host, sslPort, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) throws Exception {
            pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
            pipeline.addLast("httpEncoder", new HttpResponseEncoder());
            pipeline.addLast("httpDecoder", new HttpRequestDecoder());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", "mqtt mqttv3.1, mqttv3.1.1"));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor__.java

License:Open Source License

private void initializePlainTCPTransport(final NettyMQTTHandler__ handler, IConfig props) throws IOException {
    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
    if (DISABLED_PORT_BIND.equals(tcpPortProp)) {
        LOG.info("tcp MQTT is disabled because the value for the property with key {}",
                BrokerConstants.PORT_PROPERTY_NAME);
        return;//from   w w  w.  ja v  a 2  s.  c  om
    }
    int port = Integer.parseInt(tcpPortProp);
    initFactory(host, port, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) {
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("messageLogger", new MQTTMessageLogger());
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor__.java

License:Open Source License

private void initializeWebSocketTransport(final NettyMQTTHandler__ handler, IConfig props) throws IOException {
    String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
    if (DISABLED_PORT_BIND.equals(webSocketPortProp)) {
        //Do nothing no WebSocket configured
        LOG.info("WebSocket is disabled");
        return;//  w  ww. j  a  va  2  s .  c  o  m
    }
    int port = Integer.parseInt(webSocketPortProp);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();

    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    initFactory(host, port, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) {
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("messageLogger", new MQTTMessageLogger());
            pipeline.addLast("handler", handler);
        }
    });
}

From source file:io.moquette.server.netty.NettyAcceptor__.java

License:Open Source License

private void initializeSSLTCPTransport(final NettyMQTTHandler__ handler, IConfig props,
        final SSLContext sslContext) throws IOException {
    String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
    if (DISABLED_PORT_BIND.equals(sslPortProp)) {
        //Do nothing no SSL configured
        LOG.info("SSL MQTT is disabled because there is no value in properties for key {}",
                BrokerConstants.SSL_PORT_PROPERTY_NAME);
        return;/*from   w  w  w .  j av  a  2 s .co  m*/
    }

    int sslPort = Integer.parseInt(sslPortProp);
    LOG.info("Starting SSL on port {}", sslPort);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
    String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
    final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
    initFactory(host, sslPort, new PipelineInitializer() {
        @Override
        void init(ChannelPipeline pipeline) throws Exception {
            pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
            pipeline.addFirst("idleStateHandler",
                    new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
            pipeline.addAfter("idleStateHandler", "idleEventHandler", timeoutHandler);
            //pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR));
            pipeline.addFirst("bytemetrics", new BytesMetricsHandler(m_bytesMetricsCollector));
            pipeline.addLast("decoder", new MQTTDecoder());
            pipeline.addLast("encoder", new MQTTEncoder());
            pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
            pipeline.addLast("messageLogger", new MQTTMessageLogger());
            pipeline.addLast("handler", handler);
        }
    });
}