use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testUploadQoS1MessageSendsPubAckOnSuccess.
private void testUploadQoS1MessageSendsPubAckOnSuccess(final Future<ProtonDelivery> outcome, final BiConsumer<AbstractVertxBasedMqttProtocolAdapter<?>, MqttContext> upload) {
// GIVEN an adapter with a downstream event consumer
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
// WHEN a device publishes an event
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final Buffer payload = Buffer.buffer("some payload");
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
when(messageFromDevice.payload()).thenReturn(payload);
final MqttContext context = new MqttContext(messageFromDevice, endpoint);
upload.accept(adapter, context);
// THEN the device does not receive a PUBACK
verify(endpoint, never()).publishAcknowledge(anyInt());
// until the event has been settled and accepted
outcome.complete(mock(ProtonDelivery.class));
verify(endpoint).publishAcknowledge(5555555);
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testOnUnauthenticatedMessageDoesNotSendPubAckOnFailure.
/**
* Verifies that the adapter does not send a PUBACK package to the device if
* an event message has not been accepted by the peer.
*
* @param ctx The vert.x test context.
*/
@Test
public void testOnUnauthenticatedMessageDoesNotSendPubAckOnFailure(final TestContext ctx) {
// GIVEN an adapter with a downstream event consumer
final Future<ProtonDelivery> outcome = Future.future();
givenAnEventSenderForOutcome(outcome);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
// WHEN a device publishes an event
final Buffer payload = Buffer.buffer("some payload");
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
final MqttContext context = new MqttContext(messageFromDevice, endpoint);
adapter.uploadEventMessage(context, "my-tenant", "4712", payload).setHandler(ctx.asyncAssertFailure());
// and the peer rejects the message
outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
// THEN the device has not received a PUBACK
verify(endpoint, never()).publishAcknowledge(anyInt());
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testUploadTelemetryMessageFailsForDisabledTenant.
/**
* Verifies that the adapter does not forward a message published by a device
* if the device belongs to a tenant for which the adapter has been disabled.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadTelemetryMessageFailsForDisabledTenant(final TestContext ctx) {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
// which is disabled for tenant "my-tenant"
final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
myTenantConfig.addAdapterConfiguration(new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, ADAPTER_TYPE).put(TenantConstants.FIELD_ENABLED, false));
when(tenantClient.get("my-tenant")).thenReturn(Future.succeededFuture(myTenantConfig));
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MessageSender sender = mock(MessageSender.class);
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
// WHEN a device of "my-tenant" publishes a telemetry message
adapter.uploadTelemetryMessage(new MqttContext(mock(MqttPublishMessage.class), mock(MqttEndpoint.class)), "my-tenant", "the-device", Buffer.buffer("test")).setHandler(ctx.asyncAssertFailure(t -> {
// THEN the message has not been sent downstream
verify(sender, never()).send(any(Message.class));
// because the tenant is not enabled
ctx.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, ((ClientErrorException) t).getErrorCode());
}));
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testEndpointHandlerRetrievesCredentialsOnRecord.
/**
* Verifies that an adapter retrieves credentials on record for a device connecting to the adapter.
*/
@SuppressWarnings("unchecked")
@Test
public void testEndpointHandlerRetrievesCredentialsOnRecord() {
// GIVEN an adapter requiring devices to authenticate endpoint
final MqttServer server = getMqttServer(false);
config.setAuthenticationRequired(true);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
adapter.handleEndpointConnection(endpoint);
verify(credentialsAuthProvider).authenticate(any(UsernamePasswordCredentials.class), any(Handler.class));
}
use of io.vertx.mqtt.MqttServer in project vertx-examples by vert-x3.
the class Server method start.
@Override
public void start() throws Exception {
MqttServer mqttServer = MqttServer.create(vertx);
mqttServer.endpointHandler(endpoint -> {
// shows main connect info
System.out.println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession());
if (endpoint.auth() != null) {
System.out.println("[username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "]");
}
if (endpoint.will() != null) {
System.out.println("[will flag = " + endpoint.will().isWillFlag() + " topic = " + endpoint.will().willTopic() + " msg = " + endpoint.will().willMessage() + " QoS = " + endpoint.will().willQos() + " isRetain = " + endpoint.will().isWillRetain() + "]");
}
System.out.println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]");
// accept connection from the remote client
endpoint.accept(false);
// handling requests for subscriptions
endpoint.subscribeHandler(subscribe -> {
List<MqttQoS> grantedQosLevels = new ArrayList<>();
for (MqttTopicSubscription s : subscribe.topicSubscriptions()) {
System.out.println("Subscription for " + s.topicName() + " with QoS " + s.qualityOfService());
grantedQosLevels.add(s.qualityOfService());
}
// ack the subscriptions request
endpoint.subscribeAcknowledge(subscribe.messageId(), grantedQosLevels);
// just as example, publish a message on the first topic with requested QoS
endpoint.publish(subscribe.topicSubscriptions().get(0).topicName(), Buffer.buffer("Hello from the Vert.x MQTT server"), subscribe.topicSubscriptions().get(0).qualityOfService(), false, false);
// specifing handlers for handling QoS 1 and 2
endpoint.publishAcknowledgeHandler(messageId -> {
System.out.println("Received ack for message = " + messageId);
}).publishReceivedHandler(messageId -> {
endpoint.publishRelease(messageId);
}).publishCompletionHandler(messageId -> {
System.out.println("Received ack for message = " + messageId);
});
});
// handling requests for unsubscriptions
endpoint.unsubscribeHandler(unsubscribe -> {
for (String t : unsubscribe.topics()) {
System.out.println("Unsubscription for " + t);
}
// ack the subscriptions request
endpoint.unsubscribeAcknowledge(unsubscribe.messageId());
});
// handling ping from client
endpoint.pingHandler(v -> {
System.out.println("Ping received from client");
});
// handling disconnect message
endpoint.disconnectHandler(v -> {
System.out.println("Received disconnect from client");
});
// handling closing connection
endpoint.closeHandler(v -> {
System.out.println("Connection closed");
});
// handling incoming published messages
endpoint.publishHandler(message -> {
System.out.println("Just received message on [" + message.topicName() + "] payload [" + message.payload() + "] with QoS [" + message.qosLevel() + "]");
if (message.qosLevel() == MqttQoS.AT_LEAST_ONCE) {
endpoint.publishAcknowledge(message.messageId());
} else if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
endpoint.publishReceived(message.messageId());
}
}).publishReleaseHandler(messageId -> {
endpoint.publishComplete(messageId);
});
}).listen(1883, "0.0.0.0", ar -> {
if (ar.succeeded()) {
System.out.println("MQTT server is listening on port " + mqttServer.actualPort());
} else {
System.err.println("Error on starting the server" + ar.cause().getMessage());
}
});
}
Aggregations