use of io.vertx.mqtt.MqttClient 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
}));
}
use of io.vertx.mqtt.MqttClient in project vertx-examples by vert-x3.
the class Client method start.
@Override
public void start() throws Exception {
MqttClient mqttClient = MqttClient.create(vertx);
mqttClient.connect(BROKER_PORT, BROKER_HOST, ch -> {
if (ch.succeeded()) {
System.out.println("Connected to a server");
mqttClient.publish(MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE), MqttQoS.AT_MOST_ONCE, false, false, s -> mqttClient.disconnect(d -> System.out.println("Disconnected from server")));
} else {
System.out.println("Failed to connect to a server");
System.out.println(ch.cause());
}
});
}
use of io.vertx.mqtt.MqttClient 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());
}
});
}
use of io.vertx.mqtt.MqttClient 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);
}
}
use of io.vertx.mqtt.MqttClient in project vertx-examples by vert-x3.
the class Client method start.
@Override
public void start() throws Exception {
MqttClientOptions options = new MqttClientOptions();
options.setSsl(true);
options.setTrustAll(true);
MqttClient mqttClient = MqttClient.create(vertx, options);
mqttClient.connect(BROKER_PORT, BROKER_HOST, ch -> {
if (ch.succeeded()) {
System.out.println("Connected to a server");
mqttClient.publish(MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE), MqttQoS.AT_MOST_ONCE, false, false, s -> mqttClient.disconnect(d -> System.out.println("Disconnected from server")));
} else {
System.out.println("Failed to connect to a server");
System.out.println(ch.cause());
}
});
}
Aggregations