io.vertx.mqtt.MqttClientOptions Java Examples

The following examples show how to use io.vertx.mqtt.MqttClientOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MqttClientIdTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void afterConnectClientId(TestContext context) {

  Async async = context.async();

  MqttClientOptions options = new MqttClientOptions();
  options.setClientId("myClient");
  MqttClient client = MqttClient.create(Vertx.vertx(), options);

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());
    assertThat(client.clientId(), notNullValue());
    assertFalse(client.clientId().isEmpty());
    assertEquals(client.clientId(), "myClient");

    log.info("Client connected with requested client id = " + client.clientId());

    async.countDown();
  });
  async.await();
}
 
Example #2
Source File: MqttClientProvider.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Mono<MqttClientProperties> createConfig(@Nonnull NetworkProperties properties) {
    return Mono.defer(() -> {
        MqttClientProperties config = FastBeanCopier.copy(properties.getConfigurations(), new MqttClientProperties());
        config.setId(properties.getId());
        if (config.getOptions() == null) {
            config.setOptions(new MqttClientOptions());
            config.getOptions().setClientId(config.getClientId());
            config.getOptions().setPassword(config.getPassword());
            config.getOptions().setUsername(config.getUsername());
        }
        if (config.isSsl()) {
            config.getOptions().setSsl(true);
            return certificateManager.getCertificate(config.getCertId())
                .map(VertxKeyCertTrustOptions::new)
                .doOnNext(config.getOptions()::setKeyCertOptions)
                .doOnNext(config.getOptions()::setTrustOptions)
                .thenReturn(config);
        }
        return Mono.just(config);
    });
}
 
Example #3
Source File: MqttClientIdTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void afterConnectClientIdGenerated(TestContext context) throws InterruptedException {

  Async async = context.async();

  MqttClientOptions options = new MqttClientOptions();
  MqttClient client = MqttClient.create(Vertx.vertx(), options);

  assertThat(options.getClientId(), nullValue());

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());
    assertTrue(client.clientId().length() == 36);
    assertThat(client.clientId(), notNullValue());
    assertFalse(client.clientId().isEmpty());

    log.info("Client connected with generated client id = " + client.clientId());

    async.countDown();
  });
  async.await();
}
 
Example #4
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void tcpConnectionFails(TestContext context) {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx());

  client.closeHandler(v -> {
    // when TCP connection fails, this handler should not be called, connection not established
    context.fail();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {
    // connection
    assertTrue(c.failed());
    assertFalse(client.isConnected());
    async.complete();
  });

  async.await();
}
 
Example #5
Source File: MqttHelpers.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
static MqttClientOptions createMqttClientOptions(MqttConnectorCommonConfiguration config) {
    MqttClientOptions options = new MqttClientOptions();
    options.setCleanSession(config.getAutoCleanSession());
    options.setAutoGeneratedClientId(config.getAutoGeneratedClientId());
    options.setAutoKeepAlive(config.getAutoKeepAlive());
    options.setClientId(config.getClientId().orElse(null));
    options.setConnectTimeout(config.getConnectTimeoutSeconds());
    options.setKeepAliveTimeSeconds(config.getKeepAliveSeconds());
    options.setMaxInflightQueue(config.getMaxInflightQueue());
    options.setMaxMessageSize(config.getMaxMessageSize());
    options.setPassword(config.getPassword().orElse(null));
    options.setReconnectAttempts(config.getReconnectAttempts());
    options.setReconnectInterval(TimeUnit.SECONDS.toMillis(config.getReconnectIntervalSeconds()));
    options.setSsl(config.getSsl());
    options.setTrustAll(config.getTrustAll());
    options.setUsername(config.getUsername().orElse(null));
    options.setWillQoS(config.getWillQos());
    options.setWillFlag(config.getWillFlag());
    options.setWillRetain(config.getWillRetain());
    return options;
}
 
Example #6
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void closeHandler(TestContext context) throws InterruptedException {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx(),
    new MqttClientOptions()
      .setKeepAliveTimeSeconds(5)
      .setAutoKeepAlive(false)
  );

  client.closeHandler((v) -> {
    async.countDown();
  });

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
  });

  async.await();
}
 
Example #7
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void connectDisconnectWithIdleOption(TestContext context) {
  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setKeepAliveTimeSeconds(100);
  MqttClient client = MqttClient.create(Vertx.vertx(),options);

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());

    client
      .disconnect(ar -> {
        assertTrue(ar.succeeded());
        async.countDown();
      });
  });

  async.await();
}
 
Example #8
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSslClientTruststoreTest(TestContext context) {

  this.context = context;
  JksOptions jksOptions = new JksOptions().setPath("/tls/client-truststore.jks");

  MqttClientOptions clientOptions = new MqttClientOptions()
    .setSsl(true)
    .setTrustStoreOptions(jksOptions);

  MqttClient client = MqttClient.create(vertx, clientOptions);
  client.exceptionHandler(t -> context.assertTrue(false));

  Async async = context.async();
  client.connect(MQTT_SERVER_TLS_PORT, MQTT_SERVER_HOST, s -> client.disconnect(d -> async.countDown()));
  async.await();
}
 
Example #9
Source File: MqttTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a connection to the MQTT adapter using given credentials.
 *
 * @param username The username to use for authentication.
 * @param password The password to use for authentication.
 * @return A future that will be completed with the CONNACK packet received
 *         from the adapter or failed with a {@link MqttConnectionException}
 *         if the connection could not be established.
 */
protected final Future<MqttConnAckMessage> connectToAdapter(
        final String username,
        final String password) {

    final Promise<MqttConnAckMessage> result = Promise.promise();
    VERTX.runOnContext(connect -> {
        final MqttClientOptions options = new MqttClientOptions()
                .setUsername(username)
                .setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result);
    });
    return result.future().map(conAck -> {
        LOGGER.debug(
                "MQTT connection to adapter [host: {}, port: {}] established",
                IntegrationTestSupport.MQTT_HOST, IntegrationTestSupport.MQTT_PORT);
        this.context = Vertx.currentContext();
        return conAck;
    });
}
 
Example #10
Source File: MqttTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a connection to the MQTT adapter using an X.509 client certificate.
 *
 * @param cert The client certificate to use for authentication.
 * @return A future that will be completed with the CONNACK packet received
 *         from the adapter or failed with a {@link MqttConnectionException}
 *         if the connection could not be established.
 */
protected final Future<MqttConnAckMessage> connectToAdapter(
        final SelfSignedCertificate cert) {

    final Promise<MqttConnAckMessage> result = Promise.promise();
    VERTX.runOnContext(connect -> {
        final MqttClientOptions options = new MqttClientOptions()
                .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
                .setKeyCertOptions(cert.keyCertOptions())
                .setSsl(true);
        options.setHostnameVerificationAlgorithm("");
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTTS_PORT, IntegrationTestSupport.MQTT_HOST, result);
    });
    return result.future().map(conAck -> {
        LOGGER.debug(
                "MQTTS connection to adapter [host: {}, port: {}] established",
                IntegrationTestSupport.MQTT_HOST, IntegrationTestSupport.MQTTS_PORT);
        this.context = Vertx.currentContext();
        return conAck;
    });
}
 
Example #11
Source File: MqttClientMaxMessageSizeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void decoderMaxMessageSize(TestContext context) throws InterruptedException {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx(),
    new MqttClientOptions()
      .setMaxMessageSize(MQTT_MAX_MESSAGE_SIZE)
  );

  client.subscribeCompletionHandler(sc -> {
    log.info("SUBACK <---");
    byte[] message = new byte[MQTT_BIG_MESSAGE_SIZE];
    client.publish(MQTT_TOPIC, Buffer.buffer(message), AT_MOST_ONCE, false, false);
    log.info("PUBLISH ---> ... with big message size which should cause decoder exception");
  });

  client.exceptionHandler(t->{
    log.error("Exception raised", t);

    if (t instanceof DecoderException) {
      log.info("PUBLISH <--- message with big size");
      async.countDown();
    }
  });

  log.info("CONNECT --->");
  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    log.info("CONNACK <---");
    client.subscribe(MQTT_TOPIC, 0);
    log.info("SUBSCRIBE --->");
  });

  async.await();
}
 
Example #12
Source File: MqttClientPingTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void autoPing(TestContext context) throws InterruptedException {

  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setKeepAliveTimeSeconds(KEEPALIVE_TIMEOUT);

  log.info("Auto ping ... " + PING_NUMBER + " times timeout " + KEEPALIVE_TIMEOUT);

  count = 0;
  MqttClient client = MqttClient.create(Vertx.vertx(), options);
  client.connect(TestUtil.BROKER_PORT,  TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    client.pingResponseHandler(v -> {

      log.info("Pingresp <-- ");
      count++;
      if (count == PING_NUMBER) {
        client.disconnect();
        async.countDown();
      }
    });

  });

  async.await();
}
 
Example #13
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void clientSslTrustAllTest(TestContext context) {
  MqttClientOptions clientOptions = new MqttClientOptions()
    .setSsl(true)
    .setTrustAll(true);

  MqttClient client = MqttClient.create(vertx, clientOptions);
  client.exceptionHandler(t -> context.assertTrue(false));

  this.context = context;
  Async async = context.async();
  client.connect(MQTT_SERVER_TLS_PORT, MQTT_SERVER_HOST, s -> client.disconnect(d -> async.countDown()));
  async.await();
}
 
Example #14
Source File: MqttClientOutOfOrderAcksTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void clientSendThreePublishMessages(MqttQoS mqttQoS, TestContext context) {
  Async async = context.async(3);
  MqttClient client = MqttClient.create(vertx);

  Queue<Integer> expectOrder = new LinkedList<>();
  // order we expect to receive acknowledgment for published message
  expectOrder.add(2);
  expectOrder.add(1);
  expectOrder.add(3);

  client.publishCompletionHandler(h -> {
    context.assertEquals(h.intValue(), expectOrder.poll());
    log.info("[CLIENT] Publish completed for message with id: " + h);
    async.countDown();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {

    // publish QoS = 1 message three times
    for (int i = 0; i < 3; i++)
      client.publish(MQTT_TOPIC,
        Buffer.buffer(MQTT_MESSAGE.getBytes()),
        mqttQoS,
        false,
        false, h -> log.info("[CLIENT] publishing message id = " + h.result()));
  });

  async.await();
  client.disconnect();
}
 
Example #15
Source File: MqttClientImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param vertx Vert.x instance
 * @param options MQTT client options
 */
public MqttClientImpl(Vertx vertx, MqttClientOptions options) {

  // copy given options
  NetClientOptions netClientOptions = new NetClientOptions(options);
  netClientOptions.setIdleTimeout(DEFAULT_IDLE_TIMEOUT);

  this.vertx = (VertxInternal) vertx;
  this.client = vertx.createNetClient(netClientOptions);
  this.options = options;
}
 
Example #16
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connackNotOk(TestContext context) {
  Async async = context.async();
  Async asyncServer = context.async();
  Vertx vertx = Vertx.vertx();

  MqttServer server = MqttServer.create(vertx);
  server.endpointHandler(endpoint -> {
    endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
  });
  server.listen(MqttServerOptions.DEFAULT_PORT, context.asyncAssertSuccess(v -> asyncServer.complete()));
  asyncServer.await();

  MqttClient client = MqttClient.create(vertx);
  client.closeHandler(v -> {
    // when server replies with "negative" CONNACK, this handler should not be called
    // the failure is just part of the connectHandler
    context.fail();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {
    assertTrue(c.failed());
    assertTrue(c.cause() instanceof MqttConnectionException);
    MqttConnectionException connEx = (MqttConnectionException) c.cause();
    assertEquals(connEx.code(), MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
    assertFalse(client.isConnected());
    async.complete();
  });

  async.await();
}
 
Example #17
Source File: MqttServerBadClientTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private MqttMessage createConnectPacket(MqttClientOptions options) {
  MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT,
    false,
    MqttQoS.AT_MOST_ONCE,
    false,
    0);

  MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader(
    PROTOCOL_NAME,
    PROTOCOL_VERSION,
    options.hasUsername(),
    options.hasPassword(),
    options.isWillRetain(),
    options.getWillQoS(),
    options.isWillFlag(),
    options.isCleanSession(),
    options.getKeepAliveTimeSeconds()
  );

  MqttConnectPayload payload = new MqttConnectPayload(
    options.getClientId() == null ? "" : options.getClientId(),
    options.getWillTopic(),
    options.getWillMessage() != null ? options.getWillMessage().getBytes(StandardCharsets.UTF_8) : null,
    options.hasUsername() ? options.getUsername() : null,
    options.hasPassword() ? options.getPassword().getBytes(StandardCharsets.UTF_8) : null
  );

  return MqttMessageFactory.newMessage(fixedHeader, variableHeader, payload);
}
 
Example #18
Source File: MqttClientPingTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void manualPing(TestContext context) throws InterruptedException {

  Vertx vertx = Vertx.vertx();

  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setAutoKeepAlive(false);

  log.info("Manual ping ... " + PING_NUMBER + " times timeout " + KEEPALIVE_TIMEOUT);

  count = 0;
  MqttClient client = MqttClient.create(vertx, options);
  client.connect(TestUtil.BROKER_PORT,  TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    client.pingResponseHandler(v ->{

      log.info("Pingresp <-- ");
      count++;
      if (count == PING_NUMBER) {
        vertx.cancelTimer(timerId);
        client.disconnect();
        async.countDown();
      }
    });

    vertx.setPeriodic(KEEPALIVE_TIMEOUT * 1000, t -> {
      timerId = t;
      log.info("Pingreq --> ");
      client.ping();
    });

  });

  async.await();
}
 
Example #19
Source File: MqttConsumerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));

            client.connect(PORT,HOST,s -> {
                client.publishHandler(response -> {
                    String message = new String(response.payload().getBytes());
                    logger.info("接收到消息: {} from topic {}", message, response.topicName());
                });

                client.subscribe("#", MqttQoS.AT_LEAST_ONCE.value(), resp -> {
                    logger.info("subscribe {}", resp);
                });
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #20
Source File: MqttProducerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));


            client.connect(PORT,HOST, asyncResult -> {
                Runnable publishTask = () -> {
                    Buffer buffer = Buffer.buffer("发布数据" + PUBLISH_COUNT.incrementAndGet());
                    client.publish("/hello",buffer,
                            MqttQoS.EXACTLY_ONCE, true, true,
                            asyncResult1 -> {
                                if (asyncResult1.succeeded()) {
                                    logger.info("publish {}", asyncResult1);
                                }
                            }
                    );
                };
                Executors.newScheduledThreadPool(1)
                        .scheduleAtFixedRate(publishTask, 0, 15, TimeUnit.MILLISECONDS);
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #21
Source File: Clients.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static ClientHolder getHolder(Vertx vertx, String host, int port, String server,
        MqttClientOptions options) {

    String id = host + port + "<" + (server == null ? "" : server)
            + ">-[" + (options.getClientId() != null ? options.getClientId() : "") + "]";
    return clients.computeIfAbsent(id, key -> {
        MqttClient client = MqttClient.create(vertx, options);
        return new ClientHolder(client, host, port, server);
    });
}
 
Example #22
Source File: Clients.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static Uni<MqttClient> getConnectedClient(Vertx vertx, String host, int port, String server,
        MqttClientOptions options) {
    String id = host + port + "<" + (server == null ? "" : server)
            + ">-[" + (options.getClientId() != null ? options.getClientId() : "") + "]";
    ClientHolder holder = clients.computeIfAbsent(id, key -> {
        MqttClient client = MqttClient.create(vertx, options);
        return new ClientHolder(client, host, port, server);
    });
    return holder.connect();
}
 
Example #23
Source File: MqttClientProviderTest.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Test
void test() {
    MqttServer server = MqttServer.create(vertx);

    server.endpointHandler(endpoint -> {
        endpoint
                .accept()
                .publish("/test", Buffer.buffer("test"), MqttQoS.AT_MOST_ONCE, false, false);
    }).listen(11223);

    MqttClientProvider provider = new MqttClientProvider(id -> Mono.empty(), vertx);

    MqttClientProperties properties = new MqttClientProperties();
    properties.setHost("127.0.0.1");
    properties.setPort(11223);
    properties.setOptions(new MqttClientOptions());

    VertxMqttClient client = provider.createNetwork(properties);

    client.subscribe(Arrays.asList("/test"))
            .map(MqttMessage::getPayload)
            .map(payload -> payload.toString(StandardCharsets.UTF_8))
            .take(1)
            .as(StepVerifier::create)
            .expectNext("test")
            .verifyComplete();


}
 
Example #24
Source File: VertxMqttDeviceClient.java    From device-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<? extends ClientSession> connect(MqttClientConfiguration configuration) {
    return Flux.create(sink -> {
        for (int i = 0; i < configuration.getNumber(); i++) {
            MqttClientOptions options = new MqttClientOptions(configuration.getOptions());
            options.setReconnectAttempts(2);
            options.setReconnectInterval(Duration.ofSeconds(5).toMillis());
            doConnect(sink, i, configuration, options, null);
        }
    });
}
 
Example #25
Source File: VertxMqttDeviceClient.java    From device-simulator with Apache License 2.0 4 votes vote down vote up
private void doConnect(FluxSink<ClientSession> sink,
                       int index,
                       MqttClientConfiguration configuration,
                       MqttClientOptions options, MqttClientSession session) {
    MqttAuthInfo authInfo = configuration.getAuthGenerator().generate(index);
    options.setClientId(authInfo.getClientId());
    options.setUsername(authInfo.getUsername());
    options.setPassword(authInfo.getPassword());

    MqttClient client = MqttClient.create(vertx, options);
    client.connect(configuration.getPort(), configuration.getHost(), result -> {
        if (result.succeeded()) {
            MqttClientSession mqttClientSession = session == null ? new MqttClientSession() : session;

            mqttClientSession.client = client;
            client.closeHandler((r) -> {
                if (!mqttClientSession.manualClose) {
                    if (mqttClientSession.retryTimes.incrementAndGet() >= configuration.getOptions().getReconnectAttempts()) {
                        return;
                    }
                    Mono.delay(Duration.ofMillis(Math.max(options.getReconnectInterval(), 1000)))
                            .subscribe(ignore -> doConnect(sink, index, configuration, options, mqttClientSession));
                }
            });

            client.publishHandler(message -> {
                mqttClientSession.processor.onNext(
                        SimpleMqttMessage.builder()
                                .messageId(message.messageId())
                                .payload(message.payload().getByteBuf())
                                .qosLevel(message.qosLevel().value())
                                .topic(message.topicName())
                                .dup(message.isDup())
                                .retain(message.isRetain())
                                .build()
                );
            });
            if (session == null) {
                sink.next(mqttClientSession);
            }
        } else {
            sink.error(result.cause());
        }
    });
}
 
Example #26
Source File: MqttSource.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public MqttSource(Vertx vertx, MqttConnectorIncomingConfiguration config) {
    MqttClientOptions options = MqttHelpers.createMqttClientOptions(config);

    String host = config.getHost();
    int def = options.isSsl() ? 8883 : 1883;
    int port = config.getPort().orElse(def);
    String server = config.getServerName().orElse(null);
    String topic = config.getTopic().orElseGet(config::getChannel);
    int qos = config.getQos();
    boolean broadcast = config.getBroadcast();
    MqttFailureHandler.Strategy strategy = MqttFailureHandler.Strategy.from(config.getFailureStrategy());
    MqttFailureHandler onNack = createFailureHandler(strategy, config.getChannel());

    if (topic.contains("#") || topic.contains("+")) {
        String replace = topic.replace("+", "[^/]+")
                .replace("#", ".+");
        pattern = Pattern.compile(replace);
    } else {
        pattern = null;
    }

    Clients.ClientHolder holder = Clients.getHolder(vertx, host, port, server, options);
    this.source = ReactiveStreams.fromPublisher(
            holder.connect()
                    .onItem().produceMulti(client -> {
                        return client.subscribe(topic, qos)
                                .onItem().produceMulti(x -> {
                                    subscribed.set(true);
                                    return holder.stream()
                                            .transform().byFilteringItemsWith(m -> matches(topic, m))
                                            .onItem().apply(m -> new ReceivingMqttMessage(m, onNack));
                                });
                    })
                    .then(multi -> {
                        if (broadcast) {
                            return multi.broadcast().toAllSubscribers();
                        }
                        return multi;
                    })
                    .on().cancellation(() -> subscribed.set(false))
                    .onFailure().invoke(t -> log.unableToConnectToBroker(t)));
}
 
Example #27
Source File: VertxMqttSslProviderTest.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
@Test
@SneakyThrows
public void test() {
    VertxMqttServerProvider mqttServerManager = new VertxMqttServerProvider(id -> Mono.empty(), vertx);

    DefaultCertificate serverCert = new DefaultCertificate("server", "test");
    DefaultCertificate clientCert = new DefaultCertificate("client", "test");

    byte[] serverKs = StreamUtils.copyToByteArray(new ClassPathResource("server.p12").getInputStream());

    byte[] clientKs = StreamUtils.copyToByteArray(new ClassPathResource("client.p12").getInputStream());

    byte[] trust = StreamUtils.copyToByteArray(new ClassPathResource("trustStore.p12").getInputStream());

    serverCert.initPfxKey(serverKs, "endPass").initPfxTrust(trust, "rootPass");
    clientCert.initPfxKey(clientKs, "endPass").initPfxTrust(trust, "rootPass");

    VertxMqttServerProperties properties = new VertxMqttServerProperties();
    properties.setId("test");
    properties.setInstance(4);
    properties.setSsl(true);
    properties.setOptions(new MqttServerOptions()
            .setSsl(true)
            .setKeyCertOptions(new VertxKeyCertTrustOptions(serverCert))
            .setTrustOptions(new VertxKeyCertTrustOptions(serverCert))
            .setPort(1888));

    mqttServer = mqttServerManager.createNetwork(properties);

    MqttClientProperties propertiesClient = new MqttClientProperties();
    propertiesClient.setHost("127.0.0.1");
    propertiesClient.setPort(1888);
    propertiesClient.setOptions(new MqttClientOptions()
            .setSsl(true)
            .setKeyCertOptions(new VertxKeyCertTrustOptions(clientCert))
            .setTrustOptions(new VertxKeyCertTrustOptions(clientCert)));

    MqttClientProvider provider = new MqttClientProvider(id -> Mono.empty(), vertx);
    VertxMqttClient client = provider.createNetwork(propertiesClient);
    mqttServer.handleConnection()
            .map(MqttConnection::getClientId)
            .doOnNext(System.out::println)
            .take(1)
            .as(StepVerifier::create)
            .expectNextCount(1)
            .verifyComplete();
}
 
Example #28
Source File: MqttServerBadClientTest.java    From vertx-mqtt with Apache License 2.0 4 votes vote down vote up
@Test
public void multipleConnect(TestContext context) throws InterruptedException {

  // There are should not be any exceptions during the test
  mqttServer.exceptionHandler(t -> {
    context.assertTrue(false);
  });

  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();
  }
}
 
Example #29
Source File: VertxMqttClientExamples.java    From vertx-mqtt with Apache License 2.0 2 votes vote down vote up
/**
 * Example for disabling keepAlive feature
 *
 * @param options
 */
public void example4(MqttClientOptions options) {
  options.setAutoKeepAlive(false);
}