io.vertx.mqtt.MqttEndpoint Java Examples

The following examples show how to use io.vertx.mqtt.MqttEndpoint. 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: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * Invoked when a client sends its <em>CONNECT</em> packet.
 * <p>
 * Authenticates the client (if required) and registers handlers for processing messages published by the client.
 *
 * @param endpoint The MQTT endpoint representing the client.
 */
final void handleEndpointConnection(final MqttEndpoint endpoint) {

    log.debug("connection request from client [client-id: {}]", endpoint.clientIdentifier());
    final Span span = tracer.buildSpan("CONNECT")
            .ignoreActiveSpan()
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .withTag(Tags.COMPONENT.getKey(), getTypeName())
            .withTag(TracingHelper.TAG_CLIENT_ID.getKey(), endpoint.clientIdentifier())
            .start();

    if (!endpoint.isCleanSession()) {
        span.log("ignoring client's intent to resume existing session");
    }
    if (endpoint.will() != null) {
        span.log("ignoring client's last will");
    }

    isConnected()
            .compose(v -> handleConnectionRequest(endpoint, span))
            .onComplete(result -> handleConnectionRequestResult(endpoint, span, result));

}
 
Example #2
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Extracts credentials from a client's MQTT <em>CONNECT</em> packet.
 * <p>
 * This default implementation returns a future with {@link UsernamePasswordCredentials} created from the
 * <em>username</em> and <em>password</em> fields of the <em>CONNECT</em> packet.
 * <p>
 * Subclasses should override this method if the device uses credentials that do not comply with the format expected
 * by {@link UsernamePasswordCredentials}.
 *
 * @param endpoint The MQTT endpoint representing the client.
 * @return A future indicating the outcome of the operation.
 *         The future will succeed with the client's credentials extracted from the CONNECT packet
 *         or it will fail with a {@link ServiceInvocationException} indicating the cause of the failure.
 */
protected final Future<UsernamePasswordCredentials> getCredentials(final MqttEndpoint endpoint) {

    if (endpoint.auth() == null) {
        return Future.failedFuture(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "device did not provide credentials in CONNECT packet"));
    }

    if (endpoint.auth().getUsername() == null || endpoint.auth().getPassword() == null) {
        return Future.failedFuture(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "device provided malformed credentials in CONNECT packet"));
    }

    final UsernamePasswordCredentials credentials = UsernamePasswordCredentials
            .create(endpoint.auth().getUsername(), endpoint.auth().getPassword(), getConfig().isSingleTenant());

    if (credentials == null) {
        return Future.failedFuture(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "device provided malformed credentials in CONNECT packet"));
    } else {
        return Future.succeededFuture(credentials);
    }
}
 
Example #3
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection is rejected due to the connection duration limit exceeded.
 */
@Test
public void testConnectionDurationLimitExceeded() {

    // GIVEN an adapter requiring devices to authenticate endpoint
    final MqttServer server = getMqttServer(false);
    config.setAuthenticationRequired(true);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();

    // WHEN a device tries to establish a connection
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("DEFAULT_TENANT", "4711")));
    when(resourceLimitChecks.isConnectionDurationLimitReached(any(TenantObject.class), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    // THEN the adapter has tried to authenticate the device
    verify(authHandler).authenticateDevice(any(MqttContext.class));
    // THEN the connection request is rejected
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
}
 
Example #4
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection is rejected due to the limit exceeded.
 */
@Test
public void testConnectionsLimitExceeded() {

    // GIVEN an adapter requiring devices to authenticate endpoint
    final MqttServer server = getMqttServer(false);
    config.setAuthenticationRequired(true);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();

    // WHEN a device tries to establish a connection
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("DEFAULT_TENANT", "4711")));
    when(resourceLimitChecks.isConnectionLimitReached(any(TenantObject.class), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    // THEN the adapter has tried to authenticate the device
    verify(authHandler).authenticateDevice(any(MqttContext.class));
    // THEN the connection request is rejected
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
}
 
Example #5
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies the connection metrics for unauthenticated connections.
 * <p>
 * This test should check if the metrics receive a call to increment and decrement when a connection is being
 * established and then closed.
 */
@SuppressWarnings("unchecked")
@Test
public void testUnauthenticatedConnectionMetrics() {

    config.setAuthenticationRequired(false);

    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    forceClientMocksToConnected();

    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);

    // THEN the adapter does not try to authenticate the device
    verify(authHandler, never()).authenticateDevice(any(MqttContext.class));
    // and increments the number of unauthenticated connections
    verify(metrics).incrementUnauthenticatedConnections();
    // and when the device closes the connection
    final ArgumentCaptor<Handler<Void>> closeHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(endpoint).closeHandler(closeHandlerCaptor.capture());
    closeHandlerCaptor.getValue().handle(null);
    // the number of unauthenticated connections is decremented again
    verify(metrics).decrementUnauthenticatedConnections();
}
 
Example #6
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Device> handleConnectionRequest(final MqttEndpoint endpoint, final Span currentSpan) {

        // the ConnectionLimitManager is null in some unit tests
        if (getConnectionLimitManager() != null && getConnectionLimitManager().isLimitExceeded()) {
            currentSpan.log("connection limit exceeded, reject connection request");
            metrics.reportConnectionAttempt(ConnectionAttemptOutcome.ADAPTER_CONNECTION_LIMIT_EXCEEDED);
            return Future.failedFuture(new MqttConnectionException(
                    MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE));
        }

        if (getConfig().isAuthenticationRequired()) {
            return handleEndpointConnectionWithAuthentication(endpoint, currentSpan);
        } else {
            return handleEndpointConnectionWithoutAuthentication(endpoint);
        }
    }
 
Example #7
Source File: MqttServerSubscribeTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Override
protected void endpointHandler(MqttEndpoint endpoint, TestContext context) {

  endpoint.subscribeHandler(subscribe -> {

    List<MqttQoS> qos = new ArrayList<>();

    MqttQoS grantedQos =
      subscribe.topicSubscriptions().get(0).topicName().equals(MQTT_TOPIC_FAILURE) ?
        MqttQoS.FAILURE :
        subscribe.topicSubscriptions().get(0).qualityOfService();

    qos.add(grantedQos);
    endpoint.subscribeAcknowledge(subscribe.messageId(), qos);

    this.async.complete();
  });

  endpoint.accept(false);
}
 
Example #8
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies the connection metrics for authenticated connections.
 * <p>
 * This test should check if the metrics receive a call to increment and decrement when a connection is being
 * established and then closed.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectionMetrics() {

    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    forceClientMocksToConnected();
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("DEFAULT_TENANT", "4711")));

    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    verify(metrics).incrementConnections("DEFAULT_TENANT");
    final ArgumentCaptor<Handler<Void>> closeHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(endpoint).closeHandler(closeHandlerCaptor.capture());
    closeHandlerCaptor.getValue().handle(null);
    verify(metrics).decrementConnections("DEFAULT_TENANT");
}
 
Example #9
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
/**
 * Example for handling client subscription request
 * @param endpoint
 */
public void example4(MqttEndpoint endpoint) {

  // 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);

  });
}
 
Example #10
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
/**
 * Example for handling publish message to the client
 * @param endpoint
 */
public void example7(MqttEndpoint endpoint) {

  // just as example, publish a message with QoS level 2
  endpoint.publish("my_topic",
    Buffer.buffer("Hello from the Vert.x MQTT server"),
    MqttQoS.EXACTLY_ONCE,
    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);
  });
}
 
Example #11
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
/**
 * Example for handling client published message
 * @param endpoint
 */
public void example6(MqttEndpoint endpoint) {

  // handling incoming published messages
  endpoint.publishHandler(message -> {

    System.out.println("Just received message [" + message.payload().toString(Charset.defaultCharset()) + "] 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);
  });
}
 
Example #12
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Device> registerHandlers(final MqttEndpoint endpoint, final Device authenticatedDevice,
        final OptionalInt traceSamplingPriority) {
    final CommandSubscriptionsManager<T> cmdSubscriptionsManager = new CommandSubscriptionsManager<>(vertx, getConfig());
    endpoint.closeHandler(v -> close(endpoint, authenticatedDevice, cmdSubscriptionsManager, traceSamplingPriority));
    endpoint.publishHandler(
            message -> handlePublishedMessage(MqttContext.fromPublishPacket(message, endpoint, authenticatedDevice)));
    endpoint.publishAcknowledgeHandler(cmdSubscriptionsManager::handlePubAck);
    endpoint.subscribeHandler(subscribeMsg -> onSubscribe(endpoint, authenticatedDevice, subscribeMsg, cmdSubscriptionsManager,
            traceSamplingPriority));
    endpoint.unsubscribeHandler(unsubscribeMsg -> onUnsubscribe(endpoint, authenticatedDevice, unsubscribeMsg,
            cmdSubscriptionsManager, traceSamplingPriority));
    if (authenticatedDevice == null) {
        metrics.incrementUnauthenticatedConnections();
    } else {
        metrics.incrementConnections(authenticatedDevice.getTenantId());
    }
    return Future.succeededFuture(authenticatedDevice);
}
 
Example #13
Source File: MqttServerImpl.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Override
public Future<MqttServer> listen(int port, String host) {
  Handler<MqttEndpoint> h1 = endpointHandler;
  Handler<Throwable> h2 = exceptionHandler;
  server.connectHandler(so -> {
    NetSocketInternal soi = (NetSocketInternal) so;
    ChannelPipeline pipeline = soi.channelHandlerContext().pipeline();

    initChannel(pipeline);
    MqttServerConnection conn = new MqttServerConnection(soi, options);

    soi.messageHandler(msg -> {
      synchronized (conn) {
        conn.handleMessage(msg);
      }
    });

    conn.init(h1, h2);

  });
  return server.listen(port, host).map(this);
}
 
Example #14
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter registers message handlers on client connections when device authentication is
 * disabled.
 */
@SuppressWarnings("unchecked")
@Test
public void testUnauthenticatedMqttAdapterCreatesMessageHandlersForAllDevices() {

    // GIVEN an adapter that does not require devices to authenticate
    config.setAuthenticationRequired(false);
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    forceClientMocksToConnected();

    // WHEN a device connects that does not provide any credentials
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);

    // THEN the connection is established and handlers are registered
    verify(authHandler, never()).authenticateDevice(any(MqttContext.class));
    verify(endpoint).publishHandler(any(Handler.class));
    verify(endpoint).closeHandler(any(Handler.class));
    verify(endpoint).accept(false);
}
 
Example #15
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that unregistered devices with valid credentials cannot establish connection.
 */
@Test
public void testAuthenticatedMqttAdapterRejectsConnectionForNonExistingDevice() {

    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();
    // which is connected to a Credentials service that has credentials on record for device 9999
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("DEFAULT_TENANT", "9999")));
    // but for which no registration information is available
    when(regClient.assertRegistration(eq("9999"), (String) any(), (SpanContext) any()))
            .thenReturn(Future.failedFuture(new ClientErrorException(
                    HttpURLConnection.HTTP_NOT_FOUND, "device unknown or disabled")));

    // WHEN a device tries to connect with valid credentials
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    // THEN the device's credentials are verified successfully
    verify(authHandler).authenticateDevice(any(MqttContext.class));
    // but the connection is refused
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
}
 
Example #16
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a connection attempt from a device is refused if the adapter is not connected to all of the
 * services it depends on.
 */
@Test
public void testEndpointHandlerFailsWithoutDownstreamConnections() {

    // GIVEN an adapter that is not connected to
    // all of its required services
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    // WHEN a client tries to connect
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);

    // THEN the connection request is rejected
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
}
 
Example #17
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an adapter that is configured to not require devices to authenticate, accepts connections from
 * devices not providing any credentials.
 */
@Test
public void testEndpointHandlerAcceptsUnauthenticatedDevices() {

    // GIVEN an adapter that does not require devices to authenticate
    config.setAuthenticationRequired(false);
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();

    // WHEN a device connects without providing credentials
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);

    // THEN the connection is established
    verify(endpoint).accept(false);
}
 
Example #18
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an adapter rejects a connection attempt from a device that belongs to a tenant for which the
 * adapter is disabled.
 */
@Test
public void testEndpointHandlerRejectsDeviceOfDisabledTenant() {

    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("my-tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(myTenantConfig));
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("my-tenant", "4711")));
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();

    // WHEN a device of "my-tenant" tries to connect
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);

    // THEN the connection is not established
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
}
 
Example #19
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an adapter that is configured to require devices to authenticate rejects connections from devices
 * which do not provide proper credentials.
 */
@Test
public void testEndpointHandlerRejectsUnauthenticatedDevices() {

    // GIVEN an adapter that does require devices to authenticate
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    when(authHandler.authenticateDevice(any(MqttContext.class))).thenReturn(
            Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED)));
    forceClientMocksToConnected();

    // WHEN a device connects without providing proper credentials
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);
    adapter.handleEndpointConnection(endpoint);
    adapter.handleEndpointConnection(endpoint);

    // THEN the connection is refused
    verify(authHandler, times(3)).authenticateDevice(any(MqttContext.class));
}
 
Example #20
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an adapter retrieves credentials on record for a device connecting to the adapter.
 */
@Test
public void testEndpointHandlerTriesToAuthenticateDevice() {

    // GIVEN an adapter requiring devices to authenticate endpoint
    final MqttServer server = getMqttServer(false);
    config.setAuthenticationRequired(true);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();

    // WHEN a device tries to establish a connection
    when(authHandler.authenticateDevice(any(MqttContext.class))).thenReturn(
            Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED)));
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    // THEN the adapter has tried to authenticate the device
    verify(authHandler).authenticateDevice(any(MqttContext.class));
}
 
Example #21
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that on successful authentication the adapter sets appropriate message and close handlers on the client
 * endpoint.
 */
@SuppressWarnings({ "unchecked" })
@Test
public void testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices() {

    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();
    when(authHandler.authenticateDevice(any(MqttContext.class)))
            .thenReturn(Future.succeededFuture(new DeviceUser("DEFAULT_TENANT", "4711")));

    // WHEN a device tries to connect with valid credentials
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);

    // THEN the device's logical ID is successfully established and corresponding handlers
    // are registered
    verify(authHandler).authenticateDevice(any(MqttContext.class));
    verify(endpoint).accept(false);
    verify(endpoint).publishHandler(any(Handler.class));
    verify(endpoint).closeHandler(any(Handler.class));
}
 
Example #22
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter does not forward a message published by a device if the topic is empty and closes the
 * connection to the device.
 */
@Test
public void testUploadTelemetryMessageFailsForEmptyTopic() {

    // GIVEN an adapter
    config.setAuthenticationRequired(false);
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();
    final DownstreamSender sender = givenAQoS0TelemetrySender();

    final MqttEndpoint endpoint = mockEndpoint();
    when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
    adapter.handleEndpointConnection(endpoint);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<MqttPublishMessage>> messageHandler = ArgumentCaptor.forClass(Handler.class);
    verify(endpoint).publishHandler(messageHandler.capture());

    // WHEN a device publishes a message that has no topic
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn(null);
    when(msg.qosLevel()).thenReturn(MqttQoS.AT_MOST_ONCE);

    messageHandler.getValue().handle(msg);

    // THEN the device gets disconnected
    verify(endpoint).close();
    // and the message is not forwarded downstream
    verify(sender, never()).send(any(Message.class), any());
    // and the message has not been reported as processed
    verify(metrics, never()).reportTelemetry(
            any(MetricsTags.EndpointType.class),
            anyString(),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            any(MetricsTags.QoS.class),
            anyInt(),
            any());
}
 
Example #23
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter discards messages that contain a malformed topic.
 */
@Test
public void testHandlePublishedMessageFailsForMalformedTopic() {

    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    // WHEN a device publishes a message with a malformed topic
    final MqttEndpoint device = mockEndpoint();
    final Buffer payload = Buffer.buffer("hello");
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
    when(msg.topicName()).thenReturn(null);
    when(msg.payload()).thenReturn(payload);
    adapter.handlePublishedMessage(newMqttContext(msg, device));

    // THEN the message is not processed
    verify(metrics, never()).reportTelemetry(
            any(MetricsTags.EndpointType.class),
            anyString(),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            any(MetricsTags.QoS.class),
            anyInt(),
            any());
    // and no PUBACK is sent to the device
    verify(device, never()).publishAcknowledge(anyInt());
}
 
Example #24
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for being notified by client keep alive
 * @param endpoint
 */
public void example8(MqttEndpoint endpoint) {

  // handling ping from client
  endpoint.pingHandler(v -> {

    System.out.println("Ping received from client");
  });
}
 
Example #25
Source File: MqttContextTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies the values retrieved from the <em>property-bag</em> of a message's topic.
 */
@Test
public void verifyPropertyBagRetrievedFromTopic() {
    final Device device = new Device("tenant", "device");
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("event/tenant/device/?param1=value1&param2=value2");
    final MqttContext context = MqttContext.fromPublishPacket(msg, mock(MqttEndpoint.class), device);

    assertNotNull(context.propertyBag());
    assertEquals("value1", context.propertyBag().getProperty("param1"));
    assertEquals("value2", context.propertyBag().getProperty("param2"));
    assertEquals("event/tenant/device", context.topic().toString());
}
 
Example #26
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for handling client disconnection
 * @param endpoint
 */
public void example2(MqttEndpoint endpoint) {

  // handling disconnect message
  endpoint.disconnectHandler(v -> {

    System.out.println("Received disconnect from client");
  });
}
 
Example #27
Source File: MqttServerPublishTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Override
protected void endpointHandler(MqttEndpoint endpoint, TestContext context) {

  endpoint.subscribeHandler(subscribe -> {

    endpoint.subscribeAcknowledge(subscribe.messageId(),
      subscribe.topicSubscriptions()
        .stream()
        .map(MqttTopicSubscription::qualityOfService)
        .collect(Collectors.toList()));

    endpoint.publish(this.topic, Buffer.buffer(this.message), subscribe.topicSubscriptions().get(0).qualityOfService(), false, false, publishSent -> {
      context.assertTrue(publishSent.succeeded());
      this.async.complete();
    });
  }).publishAcknowledgeHandler(messageId -> {

    log.info("Message [" + messageId + "] acknowledged");
    this.async.complete();
  }).publishReceivedHandler(messageId -> {

    endpoint.publishRelease(messageId);
  }).publishCompletionHandler(messageId -> {

    log.info("Message [" + messageId + "] acknowledged");
    this.async.complete();
  });

  endpoint.accept(false);
}
 
Example #28
Source File: MqttContextTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the tenant is determined from the authenticated device.
 */
@Test
public void testTenantIsRetrievedFromAuthenticatedDevice() {
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("t");
    final Device device = new Device("tenant", "device");
    final MqttContext context = MqttContext.fromPublishPacket(msg, mock(MqttEndpoint.class), device);
    assertEquals("tenant", context.tenant());
}
 
Example #29
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for handling client unsubscription request
 * @param endpoint
 */
public void example5(MqttEndpoint endpoint) {

  // 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());
  });
}
 
Example #30
Source File: MqttContextTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the tenant is determined from the published message's topic if
 * the device has not been authenticated.
 */
@Test
public void testTenantIsRetrievedFromTopic() {
    final MqttPublishMessage msg = newMessage(TelemetryConstants.TELEMETRY_ENDPOINT_SHORT, "tenant", "device");
    final MqttContext context = MqttContext.fromPublishPacket(msg, mock(MqttEndpoint.class));
    assertEquals("tenant", context.tenant());
}