Example usage for io.netty.handler.codec.mqtt MqttEncoder INSTANCE

List of usage examples for io.netty.handler.codec.mqtt MqttEncoder INSTANCE

Introduction

In this page you can find the example usage for io.netty.handler.codec.mqtt MqttEncoder INSTANCE.

Prototype

MqttEncoder INSTANCE

To view the source code for io.netty.handler.codec.mqtt MqttEncoder INSTANCE.

Click Source Link

Usage

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

License:Open Source License

public void connect() {
    LOGGER.debug("[mqtt-client] connect");
    handler = new ClientNettyMQTTHandler();
    workerGroup = new NioEventLoopGroup(1);
    try {//ww  w. j a  v a 2s  . c  om
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new MqttDecoder());
                pipeline.addLast("encoder", MqttEncoder.INSTANCE);
                pipeline.addLast("handler", handler);
            }
        });

        // Start the client.
        channel = b.connect(host, port).sync().channel();
    } catch (Exception ex) {
        LOGGER.error("[mqtt-client] Error in client setup: " + ex.getMessage());
        workerGroup.shutdownGracefully();
        Throwables.rethrow(ex);
    }
}

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

@Override
protected void doStart() {
    if (isEnterprise == false || isEnabled == false) {
        return;/*from   ww w  .j  a va  2 s.  co  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.netty.example.mqtt.heartBeat.MqttHeartBeatBroker.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from  w  w w.jav a  2  s . c om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("encoder", MqttEncoder.INSTANCE);
                ch.pipeline().addLast("decoder", new MqttDecoder());
                ch.pipeline().addLast("heartBeatHandler", new IdleStateHandler(45, 0, 0, TimeUnit.SECONDS));
                ch.pipeline().addLast("handler", MqttHeartBeatBrokerHandler.INSTANCE);
            }
        });

        ChannelFuture f = b.bind(1883).sync();
        System.out.println("Broker initiated...");

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:io.netty.example.mqtt.heartBeat.MqttHeartBeatClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {// w  w w.  j a  va  2 s .co m
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("encoder", MqttEncoder.INSTANCE);
                ch.pipeline().addLast("decoder", new MqttDecoder());
                ch.pipeline().addLast("heartBeatHandler", new IdleStateHandler(0, 20, 0, TimeUnit.SECONDS));
                ch.pipeline().addLast("handler",
                        new MqttHeartBeatClientHandler(CLIENT_ID, USER_NAME, PASSWORD));
            }
        });

        ChannelFuture f = b.connect(HOST, PORT).sync();
        System.out.println("Client connected");
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.vertx.mqtt.impl.MqttClientImpl.java

License:Apache License

private void initChannel(ChannelPipeline pipeline) {

    // add into pipeline netty's (en/de)coder
    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);

    if (this.options.getMaxMessageSize() > 0) {
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {//from w w  w. ja va 2 s  .  co m
        // max message size not set, so the default from Netty MQTT codec is used
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    if (this.options.isAutoKeepAlive() && this.options.getKeepAliveTimeSeconds() != 0) {

        pipeline.addBefore("handler", "idle",
                new IdleStateHandler(0, this.options.getKeepAliveTimeSeconds(), 0));
        pipeline.addBefore("handler", "keepAliveHandler", new ChannelDuplexHandler() {

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

                if (evt instanceof IdleStateEvent) {
                    IdleStateEvent e = (IdleStateEvent) evt;
                    if (e.state() == IdleState.WRITER_IDLE) {
                        ping();
                    }
                }
            }
        });
    }
}

From source file:io.vertx.mqtt.impl.MqttServerImpl.java

License:Apache License

private void initChannel(ChannelPipeline pipeline) {

    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);
    if (this.options.getMaxMessageSize() > 0) {
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {/*from  ww w. ja v  a2s .c o m*/
        // max message size not set, so the default from Netty MQTT codec is used
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    // adding the idle state handler for timeout on CONNECT packet
    pipeline.addBefore("handler", "idle", new IdleStateHandler(this.options.timeoutOnConnect(), 0, 0));
    pipeline.addBefore("handler", "timeoutOnConnect", new ChannelDuplexHandler() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.READER_IDLE) {
                    // as MQTT 3.1.1 describes, if no packet is sent after a "reasonable" time (here CONNECT timeout)
                    // the connection is closed
                    ctx.channel().close();
                }
            }
        }
    });
}

From source file:io.vertx.mqtt.test.MqttBadClientTest.java

License:Apache License

@Test
public void noConnectTest(TestContext context) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {/* ww  w  . j  a  v a  2s  . c o m*/

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("mqttEncoder", MqttEncoder.INSTANCE);
            }
        });

        // Start the client.
        ChannelFuture f = bootstrap.connect(MQTT_SERVER_HOST, MQTT_SERVER_PORT).sync();

        f.channel().writeAndFlush(createPublishMessage());

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();

        context.assertTrue(true);

    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:io.vertx.mqtt.test.server.MqttServerBadClientTest.java

License:Apache License

@Test
public void multipleConnect(TestContext context) throws InterruptedException {

    // There are should not be any exceptions during the test
    mqttServer.exceptionHandler(t -> {
        context.assertTrue(false);/* w w  w.  java 2s  .co m*/
    });

    EventLoopGroup group = new NioEventLoopGroup();
    try {

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("mqttEncoder", MqttEncoder.INSTANCE);
            }
        });

        // Start the client.
        ChannelFuture f = bootstrap.connect(MQTT_SERVER_HOST, MQTT_SERVER_PORT).sync();
        long tick = System.currentTimeMillis();

        MqttClientOptions options = new MqttClientOptions();
        f.channel().writeAndFlush(createConnectPacket(options)).sync();
        f.channel().writeAndFlush(createConnectPacket(options)).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        long tock = System.currentTimeMillis();

        // Default timeout is 90 seconds
        // If connection was closed earlier that means that it was a server
        context.assertTrue((tock - tick) / 1000 < 90);

    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:net.anyflow.lannister.client.MqttClient.java

License:Apache License

public MqttConnectReturnCode connect() throws InterruptedException {
    group = new NioEventLoopGroup(1, new DefaultThreadFactory("lannister/client"));

    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from ww  w .  j  ava  2  s . co  m*/
        protected void initChannel(SocketChannel ch) throws Exception {
            if ("mqtts".equalsIgnoreCase(uri.getScheme())) {
                SslContext sslCtx = SslContextBuilder.forClient().trustManager(trustManagerFactory).build();

                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }

            ch.pipeline().addLast(MqttDecoder.class.getName(), new MqttDecoder());
            ch.pipeline().addLast(MqttEncoder.class.getName(), MqttEncoder.INSTANCE);
            ch.pipeline().addLast(MqttPacketReceiver.class.getName(),
                    new MqttPacketReceiver(MqttClient.this, receiver, sharedObject));
        }
    });

    channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();

    normalizeMessage(options.will());
    send(MessageFactory.connect(options));

    synchronized (sharedObject.locker()) {
        int timeout = Settings.SELF.getInt("lannister.client.responseTimeoutSeconds", 15);

        sharedObject.locker().wait(timeout * 1000);
    }
    if (sharedObject.receivedMessage() == null) {
        return null;
    }

    return ((MqttConnAckMessage) sharedObject.receivedMessage()).variableHeader().connectReturnCode();
}

From source file:org.apache.activemq.artemis.core.protocol.mqtt.MQTTProtocolManager.java

License:Apache License

@Override
public void addChannelHandlers(ChannelPipeline pipeline) {
    pipeline.addLast(MqttEncoder.INSTANCE);
    pipeline.addLast(new MqttDecoder(MQTTUtil.MAX_MESSAGE_SIZE));

    pipeline.addLast(new MQTTProtocolHandler(server, this));
}