Search in sources :

Example 1 with MqttClientOptions

use of io.vertx.mqtt.MqttClientOptions in project hono by eclipse.

the class TelemetryMqttIT method testConnectFailsForDisabledTenant.

/**
 * Verifies that the adapter rejects connection attempts from devices
 * that belong to a tenant for which the adapter has been disabled.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsForDisabledTenant(final TestContext ctx) {
    // GIVEN a tenant for which the HTTP adapter is disabled
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final JsonObject adapterDetailsHttp = new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, Constants.PROTOCOL_ADAPTER_TYPE_MQTT).put(TenantConstants.FIELD_ENABLED, Boolean.FALSE);
    final TenantObject tenant = TenantObject.from(tenantId, true);
    tenant.addAdapterConfiguration(adapterDetailsHttp);
    helper.registry.addDeviceForTenant(tenant, deviceId, password).compose(ok -> {
        final Future<MqttConnAckMessage> result = Future.future();
        final MqttClientOptions options = new MqttClientOptions().setUsername(IntegrationTestSupport.getUsername(deviceId, tenantId)).setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        // WHEN a device that belongs to the tenant tries to connect to the adapter
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result.completer());
        return result;
    }).setHandler(ctx.asyncAssertFailure(t -> {
    // THEN the connection attempt gets rejected
    }));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) MqttConnAckMessage(io.vertx.mqtt.messages.MqttConnAckMessage) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) MessageConsumer(org.eclipse.hono.client.MessageConsumer) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Constants(org.eclipse.hono.util.Constants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) Consumer(java.util.function.Consumer) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) Buffer(io.vertx.core.buffer.Buffer) MqttClient(io.vertx.mqtt.MqttClient) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future) Test(org.junit.Test)

Example 2 with MqttClientOptions

use of io.vertx.mqtt.MqttClientOptions in project vertx-examples by vert-x3.

the class Client method start.

@Override
public void start() throws Exception {
    MqttClientOptions options = new MqttClientOptions().setKeepAliveTimeSeconds(2);
    MqttClient client = MqttClient.create(Vertx.vertx(), options);
    // handler will be called when we have a message in topic we subscribing for
    client.publishHandler(publish -> {
        System.out.println("Just received message on [" + publish.topicName() + "] payload [" + publish.payload().toString(Charset.defaultCharset()) + "] with QoS [" + publish.qosLevel() + "]");
    });
    // handle response on subscribe request
    client.subscribeCompletionHandler(h -> {
        System.out.println("Receive SUBACK from server with granted QoS : " + h.grantedQoSLevels());
        // let's publish a message to the subscribed topic
        client.publish(MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE), MqttQoS.AT_MOST_ONCE, false, false, s -> System.out.println("Publish sent to a server"));
        // unsubscribe from receiving messages for earlier subscribed topic
        vertx.setTimer(5000, l -> client.unsubscribe(MQTT_TOPIC));
    });
    // handle response on unsubscribe request
    client.unsubscribeCompletionHandler(h -> {
        System.out.println("Receive UNSUBACK from server");
        vertx.setTimer(5000, l -> client.disconnect(d -> System.out.println("Disconnected form server")));
    });
    // connect to a server
    client.connect(BROKER_PORT, BROKER_HOST, ch -> {
        if (ch.succeeded()) {
            System.out.println("Connected to a server");
            client.subscribe(MQTT_TOPIC, 0);
        } else {
            System.out.println("Failed to connect to a server");
            System.out.println(ch.cause());
        }
    });
}
Also used : MqttClient(io.vertx.mqtt.MqttClient) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) Buffer(io.vertx.core.buffer.Buffer) MqttClient(io.vertx.mqtt.MqttClient) Charset(java.nio.charset.Charset) AbstractVerticle(io.vertx.core.AbstractVerticle) Vertx(io.vertx.core.Vertx) Runner(io.vertx.example.mqtt.util.Runner) MqttClientOptions(io.vertx.mqtt.MqttClientOptions)

Example 3 with MqttClientOptions

use of io.vertx.mqtt.MqttClientOptions in project enmasse-workshop by EnMasseProject.

the class MqttClient method connect.

@Override
public void connect(String username, String password, Handler<AsyncResult<Client>> connectHandler) {
    MqttClientOptions options = new MqttClientOptions().setUsername(username).setPassword(password);
    if (this.serverCert != null && !this.serverCert.isEmpty()) {
        options.setSsl(true).setHostnameVerificationAlgorithm("").setPemTrustOptions(new PemTrustOptions().addCertPath(this.serverCert));
    }
    this.client = io.vertx.mqtt.MqttClient.create(vertx, options);
    this.client.connect(this.port, this.hostname, done -> {
        if (done.succeeded()) {
            log.info("Connected to {}:{}", this.hostname, this.port);
            this.client.publishHandler(m -> {
                MessageDelivery messageDelivery = new MessageDelivery(m.topicName(), m.payload().getBytes());
                this.receivedHandler.handle(messageDelivery);
            });
            this.client.subscribeCompletionHandler(suback -> {
                log.info("Subscription [{}], granted QoS levels {}", suback.messageId(), suback.grantedQoSLevels());
            });
            connectHandler.handle(Future.succeededFuture(this));
        } else {
            log.error("Error connecting to the service", done.cause());
            connectHandler.handle(Future.failedFuture(done.cause()));
        }
    });
}
Also used : MqttClientOptions(io.vertx.mqtt.MqttClientOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions)

Example 4 with MqttClientOptions

use of io.vertx.mqtt.MqttClientOptions in project hono by eclipse.

the class MqttTestBase method init.

/**
 * Creates default AMQP client options.
 */
@BeforeAll
public static void init() {
    defaultOptions = new MqttClientOptions();
    defaultOptions.setSsl(true).setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH)).setHostnameVerificationAlgorithm("").setEnabledSecureTransportProtocols(Set.of(IntegrationTestSupport.TLS_VERSION_1_2));
}
Also used : MqttClientOptions(io.vertx.mqtt.MqttClientOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 5 with MqttClientOptions

use of io.vertx.mqtt.MqttClientOptions in project hono by eclipse.

the class MqttTestBase method doTestUploadMessages.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @param useShortTopicName Whether to use standard or short topic names
 * @throws InterruptedException if the test fails.
 */
public void doTestUploadMessages(final TestContext ctx, boolean useShortTopicName) throws InterruptedException {
    final int messagesToSend = 200;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addDeviceForTenant(tenant, deviceId, password).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 40 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).compose(ok -> {
        final Future<MqttConnAckMessage> result = Future.future();
        final MqttClientOptions options = new MqttClientOptions().setMaxInflightQueue(200).setUsername(IntegrationTestSupport.getUsername(deviceId, tenantId)).setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result.completer());
        return result;
    }).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    final AtomicReference<Async> sendResult = new AtomicReference<>();
    mqttClient.publishCompletionHandler(packetId -> {
        if (pendingMessages.remove(packetId)) {
            sendResult.get().complete();
        } else {
            LOGGER.info("received PUBACK for unexpected message [id: {}]", packetId);
        }
    });
    while (messageCount.get() < messagesToSend) {
        sendResult.set(ctx.async());
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement()), useShortTopicName, sendAttempt -> {
            if (sendAttempt.failed()) {
                LOGGER.debug("error sending message {}", messageCount.get(), sendAttempt.cause());
            } else {
                pendingMessages.add(sendAttempt.result());
            }
        });
        if (messageCount.get() % 40 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sendResult.get().await();
    }
    long timeToWait = Math.max(TEST_TIMEOUT - 1000, Math.round(messagesToSend * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) MqttClient(io.vertx.mqtt.MqttClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) AsyncResult(io.vertx.core.AsyncResult) MqttConnAckMessage(io.vertx.mqtt.messages.MqttConnAckMessage) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

MqttClientOptions (io.vertx.mqtt.MqttClientOptions)8 Buffer (io.vertx.core.buffer.Buffer)4 MqttClient (io.vertx.mqtt.MqttClient)4 MqttConnAckMessage (io.vertx.mqtt.messages.MqttConnAckMessage)4 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)3 AbstractVerticle (io.vertx.core.AbstractVerticle)2 AsyncResult (io.vertx.core.AsyncResult)2 Future (io.vertx.core.Future)2 Handler (io.vertx.core.Handler)2 Vertx (io.vertx.core.Vertx)2 PemTrustOptions (io.vertx.core.net.PemTrustOptions)2 Runner (io.vertx.example.mqtt.util.Runner)2 TestContext (io.vertx.ext.unit.TestContext)2 Consumer (java.util.function.Consumer)2 Message (org.apache.qpid.proton.message.Message)2 MessageConsumer (org.eclipse.hono.client.MessageConsumer)2 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)2 TenantObject (org.eclipse.hono.util.TenantObject)2 Test (org.junit.Test)2 JsonObject (io.vertx.core.json.JsonObject)1