Search in sources :

Example 1 with MqttServer

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);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) ProtonDelivery(io.vertx.proton.ProtonDelivery) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttServer(io.vertx.mqtt.MqttServer)

Example 2 with MqttServer

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());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) ProtonDelivery(io.vertx.proton.ProtonDelivery) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttServer(io.vertx.mqtt.MqttServer) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Test(org.junit.Test)

Example 3 with MqttServer

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());
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ArgumentMatchers(org.mockito.ArgumentMatchers) ProtonDelivery(io.vertx.proton.ProtonDelivery) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Context(io.vertx.core.Context) MqttServer(io.vertx.mqtt.MqttServer) Assert.assertThat(org.junit.Assert.assertThat) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) TenantClient(org.eclipse.hono.client.TenantClient) MessageSender(org.eclipse.hono.client.MessageSender) BiConsumer(java.util.function.BiConsumer) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) AfterClass(org.junit.AfterClass) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) MqttAuth(io.vertx.mqtt.MqttAuth) Device(org.eclipse.hono.service.auth.device.Device) Handler(io.vertx.core.Handler) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) TenantObject(org.eclipse.hono.util.TenantObject) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MessageSender(org.eclipse.hono.client.MessageSender) MqttServer(io.vertx.mqtt.MqttServer) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Test(org.junit.Test)

Example 4 with MqttServer

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));
}
Also used : ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttServer(io.vertx.mqtt.MqttServer) Handler(io.vertx.core.Handler) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) Test(org.junit.Test)

Example 5 with MqttServer

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());
        }
    });
}
Also used : MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) AbstractVerticle(io.vertx.core.AbstractVerticle) Runner(io.vertx.example.mqtt.util.Runner) MqttServer(io.vertx.mqtt.MqttServer) ArrayList(java.util.ArrayList) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) MqttServer(io.vertx.mqtt.MqttServer) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

MqttServer (io.vertx.mqtt.MqttServer)13 MqttEndpoint (io.vertx.mqtt.MqttEndpoint)8 ProtocolAdapterProperties (org.eclipse.hono.config.ProtocolAdapterProperties)8 Buffer (io.vertx.core.buffer.Buffer)7 Test (org.junit.Test)7 MqttPublishMessage (io.vertx.mqtt.messages.MqttPublishMessage)6 ProtonDelivery (io.vertx.proton.ProtonDelivery)5 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)4 AsyncResult (io.vertx.core.AsyncResult)4 Handler (io.vertx.core.Handler)4 ClientErrorException (org.eclipse.hono.client.ClientErrorException)4 UsernamePasswordCredentials (org.eclipse.hono.service.auth.device.UsernamePasswordCredentials)4 MqttConnectReturnCode (io.netty.handler.codec.mqtt.MqttConnectReturnCode)3 Context (io.vertx.core.Context)3 Future (io.vertx.core.Future)3 Vertx (io.vertx.core.Vertx)3 JsonObject (io.vertx.core.json.JsonObject)3 Async (io.vertx.ext.unit.Async)3 TestContext (io.vertx.ext.unit.TestContext)3 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)3