io.vertx.mqtt.MqttServer Java Examples

The following examples show how to use io.vertx.mqtt.MqttServer. 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: 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 #2
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 #3
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 #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 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 #6
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static MqttServer getMqttServer(final boolean startupShouldFail) {

    final MqttServer server = mock(MqttServer.class);
    when(server.actualPort()).thenReturn(0, 1883);
    when(server.endpointHandler(any(Handler.class))).thenReturn(server);
    when(server.listen(any(Handler.class))).then(invocation -> {
        final Handler<AsyncResult<MqttServer>> handler = invocation.getArgument(0);
        if (startupShouldFail) {
            handler.handle(Future.failedFuture("MQTT server intentionally failed to start"));
        } else {
            handler.handle(Future.succeededFuture(server));
        }
        return server;
    });

    return server;
}
 
Example #7
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
/**
 * Example for scaling (sharing MQTT servers)
 * @param vertx
 */
public void example10(Vertx vertx) {

  for (int i = 0; i < 10; i++) {

    MqttServer mqttServer = MqttServer.create(vertx);
    mqttServer.endpointHandler(endpoint -> {
      // handling endpoint
    })
      .listen(ar -> {

        // handling start listening
      });

  }
}
 
Example #8
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 #9
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 #10
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 #11
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Before
public void before(TestContext ctx) {
  PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
    .setKeyPath("tls/server-key.pem")
    .setCertPath("tls/server-cert.pem");

  MqttServerOptions serverOptions = new MqttServerOptions()
    .setPort(MQTT_SERVER_TLS_PORT)
    .setHost(MQTT_SERVER_HOST)
    .setKeyCertOptions(pemKeyCertOptions)
    .setSsl(true);

  server = MqttServer.create(vertx, serverOptions);
  server.exceptionHandler(t -> context.assertTrue(false));
  server.endpointHandler(e -> {
    log.info("Client connected");
    e.disconnectHandler(d -> log.info("Client disconnected"));
    e.accept(false);
  }).listen(ctx.asyncAssertSuccess());
}
 
Example #12
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 #13
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 #14
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 #15
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 #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 MQTT server is bound to the insecure port during startup and connections to required services
 * have been established.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@SuppressWarnings("unchecked")
@Test
public void testStartup(final VertxTestContext ctx) {

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

    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);
    startupTracker.future().onComplete(ctx.succeeding(s -> {
        ctx.verify(() -> {
            verify(server).listen(any(Handler.class));
            verify(server).endpointHandler(any(Handler.class));
        });
        ctx.completeNow();
    }));
}
 
Example #18
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<MqttServer> bindMqttServer(final MqttServerOptions options, final MqttServer mqttServer) {

        final Promise<MqttServer> result = Promise.promise();
        final MqttServer createdMqttServer = mqttServer == null ? MqttServer.create(this.vertx, options) : mqttServer;

        createdMqttServer
                .endpointHandler(this::handleEndpointConnection)
                .listen(done -> {

                    if (done.succeeded()) {
                        log.info("MQTT server running on {}:{}", getConfig().getBindAddress(),
                                createdMqttServer.actualPort());
                        result.complete(createdMqttServer);
                    } else {
                        log.error("error while starting up MQTT server", done.cause());
                        result.fail(done.cause());
                    }
                });
        return result.future();
    }
 
Example #19
Source File: MqttServerBaseTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
/**
 * Setup the needs for starting the MQTT server
 *
 * @param context TestContext instance
 * @param options MQTT server options
 */
protected void setUp(TestContext context, MqttServerOptions options) {

  this.vertx = Vertx.vertx();
  if (options == null) {
    this.mqttServer = MqttServer.create(this.vertx);
  } else {
    this.mqttServer = MqttServer.create(this.vertx, options);
  }

  this.mqttServer.exceptionHandler(err -> {
    rejection = err;
  });

  Async async = context.async();
  this.mqttServer.endpointHandler(endpoint -> endpointHandler(endpoint, context)).listen(context.asyncAssertSuccess(res -> {
    log.info("MQTT server listening on port " + res.actualPort());
    async.complete();
  }));
  // Synchronous start since the proxy might be triggered in method overrides
  async.awaitSuccess(15000);
}
 
Example #20
Source File: VertxMqttServerProvider.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private void initServer(VertxMqttServer server, VertxMqttServerProperties properties) {
    List<MqttServer> instances = new ArrayList<>(properties.getInstance());
    for (int i = 0; i < properties.getInstance(); i++) {
        MqttServer mqttServer = MqttServer.create(vertx, properties.getOptions());
        instances.add(mqttServer);

    }
    server.setMqttServer(instances);
    for (MqttServer instance : instances) {
        instance.listen(result -> {
            if (result.succeeded()) {
                log.debug("startup mqtt server [{}] on port :{} ", properties.getId(), result.result().actualPort());
            } else {
                log.warn("startup mqtt server [{}] error ", properties.getId(), result.cause());
            }
        });
    }
}
 
Example #21
Source File: MqttClientProviderTest.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Test
void test() {
    MqttServer server = MqttServer.create(vertx);

    server.endpointHandler(endpoint -> {
        endpoint
                .accept()
                .publish("/test", Buffer.buffer("test"), MqttQoS.AT_MOST_ONCE, false, false);
    }).listen(11223);

    MqttClientProvider provider = new MqttClientProvider(id -> Mono.empty(), vertx);

    MqttClientProperties properties = new MqttClientProperties();
    properties.setHost("127.0.0.1");
    properties.setPort(11223);
    properties.setOptions(new MqttClientOptions());

    VertxMqttClient client = provider.createNetwork(properties);

    client.subscribe(Arrays.asList("/test"))
            .map(MqttMessage::getPayload)
            .map(payload -> payload.toString(StandardCharsets.UTF_8))
            .take(1)
            .as(StepVerifier::create)
            .expectNext("test")
            .verifyComplete();


}
 
Example #22
Source File: MqttServerImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Override
public MqttServer listen(int port, String host, Handler<AsyncResult<MqttServer>> listenHandler) {

  Future<MqttServer> fut = listen(port, host);
  if (listenHandler != null) {
    fut.onComplete(listenHandler);
  }
  return this;
}
 
Example #23
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for closing the server
 * @param mqttServer
 */
public void example9(MqttServer mqttServer) {

  mqttServer.close(v -> {

    System.out.println("MQTT server closed");
  });
}
 
Example #24
Source File: VertxMqttServerExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for handling client connection
 * @param vertx
 */
public void example1(Vertx vertx) {

  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().getUsername() + ", password = " + endpoint.auth().getPassword() + "]");
    }
    if (endpoint.will() != null) {
      System.out.println("[will topic = " + endpoint.will().getWillTopic() + " msg = " + new String(endpoint.will().getWillMessageBytes()) +
        " QoS = " + endpoint.will().getWillQos() + " isRetain = " + endpoint.will().isWillRetain() + "]");
    }

    System.out.println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]");

    // accept connection from the remote client
    endpoint.accept(false);

  })
    .listen(ar -> {

      if (ar.succeeded()) {

        System.out.println("MQTT server is listening on port " + ar.result().actualPort());
      } else {

        System.out.println("Error on starting the server");
        ar.cause().printStackTrace();
      }
    });
}
 
Example #25
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> getAdapter(final MqttServer server) {

        final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = new AbstractVertxBasedMqttProtocolAdapter<>() {

            @Override
            protected String getTypeName() {
                return ADAPTER_TYPE;
            }

            @Override
            protected Future<Void> onPublishedMessage(final MqttContext ctx) {
                final ResourceIdentifier topic = ResourceIdentifier.fromString(ctx.message().topicName());
                return uploadTelemetryMessage(ctx, topic.getTenantId(), topic.getResourceId(), ctx.message().payload());
            }
        };
        adapter.setConfig(config);
        adapter.setMetrics(metrics);
        adapter.setTenantClientFactory(tenantClientFactory);
        adapter.setDownstreamSenderFactory(downstreamSenderFactory);
        adapter.setRegistrationClientFactory(registrationClientFactory);
        adapter.setCredentialsClientFactory(credentialsClientFactory);
        adapter.setCommandConsumerFactory(commandConsumerFactory);
        adapter.setDeviceConnectionClientFactory(deviceConnectionClientFactory);
        adapter.setCommandTargetMapper(commandTargetMapper);
        adapter.setAuthHandler(authHandler);
        adapter.setResourceLimitChecks(resourceLimitChecks);
        adapter.setTenantObjectWithAuthIdProvider(tenantObjectWithAuthIdProvider);

        if (server != null) {
            adapter.setMqttInsecureServer(server);
            adapter.init(vertx, context);
        }

        return adapter;
    }
 
Example #26
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connackNotOk(TestContext context) {
  Async async = context.async();
  Async asyncServer = context.async();
  Vertx vertx = Vertx.vertx();

  MqttServer server = MqttServer.create(vertx);
  server.endpointHandler(endpoint -> {
    endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
  });
  server.listen(MqttServerOptions.DEFAULT_PORT, context.asyncAssertSuccess(v -> asyncServer.complete()));
  asyncServer.await();

  MqttClient client = MqttClient.create(vertx);
  client.closeHandler(v -> {
    // when server replies with "negative" CONNACK, this handler should not be called
    // the failure is just part of the connectHandler
    context.fail();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {
    assertTrue(c.failed());
    assertTrue(c.cause() instanceof MqttConnectionException);
    MqttConnectionException connEx = (MqttConnectionException) c.cause();
    assertEquals(connEx.code(), MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
    assertFalse(client.isConnected());
    async.complete();
  });

  async.await();
}
 
Example #27
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 #28
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the MQTT server to use for handling secure MQTT connections.
 *
 * @param server The server.
 * @throws NullPointerException if the server is {@code null}.
 */
public void setMqttSecureServer(final MqttServer server) {
    Objects.requireNonNull(server);
    if (server.actualPort() > 0) {
        throw new IllegalArgumentException("MQTT server must not be started already");
    } else {
        this.server = server;
    }
}
 
Example #29
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the MQTT server to use for handling non-secure MQTT connections.
 *
 * @param server The server.
 * @throws NullPointerException if the server is {@code null}.
 */
public void setMqttInsecureServer(final MqttServer server) {
    Objects.requireNonNull(server);
    if (server.actualPort() > 0) {
        throw new IllegalArgumentException("MQTT server must not be started already");
    } else {
        this.insecureServer = server;
    }
}
 
Example #30
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that an adapter rejects connections when the connection limit is exceeded.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testEndpointHandlerRejectsConnectionsAboveLimit(final VertxTestContext ctx) {

    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    // with a connection limit of 1
    config.setMaxConnections(1);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);
    startupTracker.future().onComplete(ctx.succeeding(s -> {
        forceClientMocksToConnected();
        // which already has 1 connection open
        when(metrics.getNumberOfConnections()).thenReturn(1);

        // WHEN a device tries to establish a connection
        final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
        adapter.handleEndpointConnection(endpoint);

        // THEN the connection is not established
        ctx.verify(() -> verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE));
        ctx.verify(() -> verify(metrics).reportConnectionAttempt(
                ConnectionAttemptOutcome.ADAPTER_CONNECTION_LIMIT_EXCEEDED));
        ctx.completeNow();
    }));
}