Search in sources :

Example 91 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class AmqpUploadTestBase method testUploadMessagesUsingSaslPlain.

/**
 * Verifies that a number of messages published through the AMQP adapter can be successfully consumed by
 * applications connected to the AMQP messaging network.
 *
 * @param senderQos The delivery semantics to use for the device.
 * @throws InterruptedException if test is interrupted while running.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("senderQoSTypes")
public void testUploadMessagesUsingSaslPlain(final ProtonQoS senderQos) throws InterruptedException {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final Tenant tenantConfig = new Tenant();
    prepareTenantConfig(tenantConfig);
    final VertxTestContext setup = new VertxTestContext();
    setupProtocolAdapter(tenantId, tenantConfig, deviceId, senderQos).onComplete(setup.succeeding(s -> {
        setup.verify(() -> {
            final UnsignedLong maxMessageSize = s.getRemoteMaxMessageSize();
            assertWithMessage("max-message-size included in adapter's attach frame").that(maxMessageSize).isNotNull();
            assertWithMessage("max-message-size").that(maxMessageSize.longValue()).isGreaterThan(0);
        });
        sender = s;
        setup.completeNow();
    }));
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    assertWithMessage("adapter connection failure occurred").that(setup.failed()).isFalse();
    testUploadMessages(tenantId, senderQos);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Symbol(org.apache.qpid.proton.amqp.Symbol) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) Binary(org.apache.qpid.proton.amqp.Binary) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Data(org.apache.qpid.proton.amqp.messaging.Data) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) LinkError(org.apache.qpid.proton.amqp.transport.LinkError) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Buffer(io.vertx.core.buffer.Buffer) Assertions(org.junit.jupiter.api.Assertions) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) Tenant(org.eclipse.hono.service.management.tenant.Tenant) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) VertxTestContext(io.vertx.junit5.VertxTestContext) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 92 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class AmqpUploadTestBase method testAutoProvisioningViaGateway.

/**
 * Verifies that an edge device is auto-provisioned if it connects via a gateway equipped with the corresponding
 * authority.
 *
 * @param ctx The Vert.x test context.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAutoProvisioningViaGateway(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device gateway = new Device().setAuthorities(Collections.singleton(RegistryManagementConstants.AUTHORITY_AUTO_PROVISIONING_ENABLED));
    final String username = IntegrationTestSupport.getUsername(gatewayId, tenantId);
    final String edgeDeviceId = helper.getRandomDeviceId(tenantId);
    final Promise<Void> provisioningNotificationReceived = Promise.promise();
    helper.createAutoProvisioningMessageConsumers(ctx, provisioningNotificationReceived, tenantId, edgeDeviceId).compose(ok -> helper.registry.addDeviceForTenant(tenantId, new Tenant(), gatewayId, gateway, DEVICE_PASSWORD)).compose(ok -> connectToAdapter(username, DEVICE_PASSWORD)).compose(con -> createProducer(null, ProtonQoS.AT_LEAST_ONCE)).compose(sender -> {
        final Message msg = ProtonHelper.message("apFoobar");
        msg.setContentType("text/plain");
        msg.setAddress(String.format("%s/%s/%s", getEndpointName(), tenantId, edgeDeviceId));
        final Promise<Void> result = Promise.promise();
        sender.send(msg, delivery -> {
            ctx.verify(() -> assertThat(delivery.getRemoteState()).isInstanceOf(Accepted.class));
            result.complete();
        });
        return result.future();
    }).compose(ok -> provisioningNotificationReceived.future()).compose(ok -> helper.registry.getRegistrationInfo(tenantId, edgeDeviceId)).onComplete(ctx.succeeding(registrationResult -> {
        ctx.verify(() -> {
            final var info = registrationResult.bodyAsJsonObject();
            IntegrationTestSupport.assertDeviceStatusProperties(info.getJsonObject(RegistryManagementConstants.FIELD_STATUS), true);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Symbol(org.apache.qpid.proton.amqp.Symbol) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) Binary(org.apache.qpid.proton.amqp.Binary) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Data(org.apache.qpid.proton.amqp.messaging.Data) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) LinkError(org.apache.qpid.proton.amqp.transport.LinkError) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Buffer(io.vertx.core.buffer.Buffer) Assertions(org.junit.jupiter.api.Assertions) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) Promise(io.vertx.core.Promise) Tenant(org.eclipse.hono.service.management.tenant.Tenant) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Message(org.apache.qpid.proton.message.Message) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Device(org.eclipse.hono.service.management.device.Device) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Example 93 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class EventAmqpIT method testEventMessageAlreadySentIsDeliveredWhenConsumerConnects.

/**
 * Verifies that an event message from a device has been successfully sent and a north bound application,
 * which connects after the event has been sent, can successfully receive this event message.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if test execution gets interrupted.
 */
@Test
public void testEventMessageAlreadySentIsDeliveredWhenConsumerConnects(final VertxTestContext ctx) throws InterruptedException {
    final VertxTestContext setup = new VertxTestContext();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String messagePayload = UUID.randomUUID().toString();
    final Message event = ProtonHelper.message();
    setupProtocolAdapter(tenantId, new Tenant(), deviceId, ProtonQoS.AT_LEAST_ONCE).map(s -> sender = s).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    // WHEN a device that belongs to the tenant publishes an event
    MessageHelper.setPayload(event, "text/plain", Buffer.buffer(messagePayload));
    event.setAddress(getEndpointName());
    sender.send(event, delivery -> {
        if (delivery.getRemoteState() instanceof Accepted) {
            log.debug("event message has been sent");
            // THEN create a consumer once the event message has been successfully sent
            log.debug("opening event consumer for tenant [{}]", tenantId);
            createConsumer(tenantId, msg -> {
                // THEN verify that the event message has been received by the consumer
                log.debug("event message has been received by the consumer");
                ctx.verify(() -> assertThat(msg.getPayload().toString()).isEqualTo(messagePayload));
                ctx.completeNow();
            });
        } else {
            ctx.failNow(AmqpErrorException.from(delivery.getRemoteState()));
        }
    });
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Tenant(org.eclipse.hono.service.management.tenant.Tenant) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Duration(java.time.Duration) Message(org.apache.qpid.proton.message.Message) ResourceLimits(org.eclipse.hono.util.ResourceLimits) MessageContext(org.eclipse.hono.application.client.MessageContext) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) Handler(io.vertx.core.Handler) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) Tenant(org.eclipse.hono.service.management.tenant.Tenant) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Message(org.apache.qpid.proton.message.Message) VertxTestContext(io.vertx.junit5.VertxTestContext) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) Test(org.junit.jupiter.api.Test)

Example 94 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class TelemetryJmsQoS1IT method testTelemetryUpload.

/**
 * Verifies that telemetry messages uploaded to the Hono server are all received
 * by a downstream consumer.
 *
 * @throws Exception if the test fails.
 */
@Test
@AssumeMessagingSystem(type = MessagingType.amqp)
public void testTelemetryUpload() throws Exception {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String username = IntegrationTestSupport.getUsername(deviceId, tenantId);
    final String pwd = "secret";
    final Tenant tenant = new Tenant();
    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, pwd).compose(ok -> getAmqpAdapterConnection(username, pwd)).onComplete(setup.succeeding(connection -> {
        amqpAdapter = connection;
        setup.completeNow();
    }));
    assertTrue(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS));
    if (setup.failed()) {
        fail(setup.causeOfFailure());
    }
    final CountDownLatch latch = new CountDownLatch(IntegrationTestSupport.MSG_COUNT);
    final LongSummaryStatistics stats = new LongSummaryStatistics();
    givenATelemetryConsumer(tenantId);
    downstreamConsumer.setMessageListener(message -> {
        latch.countDown();
        gatherStatistics(stats, message);
        if (LOG.isInfoEnabled()) {
            final long messagesReceived = IntegrationTestSupport.MSG_COUNT - latch.getCount();
            if (messagesReceived % 100 == 0) {
                LOG.info("Received {} messages.", messagesReceived);
            }
        }
    });
    final MessageProducer messageProducer = amqpAdapter.createAnonymousProducer();
    final Destination telemetryEndpoint = JmsBasedHonoConnection.getDestination(TelemetryConstants.TELEMETRY_ENDPOINT);
    IntStream.range(1, IntegrationTestSupport.MSG_COUNT + 1).forEach(i -> {
        try {
            final Message message = amqpAdapter.newMessage("msg " + i, deviceId);
            messageProducer.send(telemetryEndpoint, message, DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
            if (i % 100 == 0) {
                LOG.info("Sent {} messages", i);
            }
        } catch (final JMSException e) {
            LOG.error("Error occurred while sending message: {}", e.getMessage(), e);
        }
    });
    final long timeToWait = Math.max(DEFAULT_TEST_TIMEOUT, Math.round(IntegrationTestSupport.MSG_COUNT * 1.2));
    // wait for messages to arrive
    assertTrue(latch.await(timeToWait, TimeUnit.MILLISECONDS), () -> "did not receive all " + IntegrationTestSupport.MSG_COUNT + " messages");
    LOG.info("Delivery statistics: {}", stats);
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) IntStream(java.util.stream.IntStream) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) LoggerFactory(org.slf4j.LoggerFactory) NamingException(javax.naming.NamingException) Tenant(org.eclipse.hono.service.management.tenant.Tenant) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) MessagingType(org.eclipse.hono.util.MessagingType) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) MessageProducer(javax.jms.MessageProducer) DeliveryMode(javax.jms.DeliveryMode) Message(javax.jms.Message) LongSummaryStatistics(java.util.LongSummaryStatistics) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) JmsBasedHonoConnection(org.eclipse.hono.tests.jms.JmsBasedHonoConnection) VertxExtension(io.vertx.junit5.VertxExtension) JMSException(javax.jms.JMSException) AssumeMessagingSystem(org.eclipse.hono.tests.AssumeMessagingSystem) Future(io.vertx.core.Future) TestInfo(org.junit.jupiter.api.TestInfo) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) MessageConsumer(javax.jms.MessageConsumer) Destination(javax.jms.Destination) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Checkpoint(io.vertx.junit5.Checkpoint) LongSummaryStatistics(java.util.LongSummaryStatistics) Destination(javax.jms.Destination) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Message(javax.jms.Message) VertxTestContext(io.vertx.junit5.VertxTestContext) JMSException(javax.jms.JMSException) MessageProducer(javax.jms.MessageProducer) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) AssumeMessagingSystem(org.eclipse.hono.tests.AssumeMessagingSystem)

Example 95 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class AmqpConnectionIT method testConnectFailsIfAutoProvisioningIsDisabled.

/**
 * Verifies that the adapter rejects connection attempts from an unknown device for which auto-provisioning is
 * disabled.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsIfAutoProvisioningIsDisabled(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final SelfSignedCertificate deviceCert = SelfSignedCertificate.create(UUID.randomUUID().toString());
    // GIVEN a tenant configured with a trust anchor that does not allow auto-provisioning
    helper.getCertificate(deviceCert.certificatePath()).compose(cert -> {
        final var tenant = Tenants.createTenantForTrustAnchor(cert);
        tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(false);
        return helper.registry.addTenant(tenantId, tenant);
    }).compose(ok -> connectToAdapter(deviceCert)).onComplete(ctx.failing(t -> {
        // THEN the connection is refused
        ctx.verify(() -> assertThat(t).isInstanceOf(SaslException.class));
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) KeyPair(java.security.KeyPair) CsvSource(org.junit.jupiter.params.provider.CsvSource) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ClientErrorException(org.eclipse.hono.client.ClientErrorException) SaslException(javax.security.sasl.SaslException) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) GeneralSecurityException(java.security.GeneralSecurityException) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) ValueSource(org.junit.jupiter.params.provider.ValueSource) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Promise(io.vertx.core.Promise) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Adapter(org.eclipse.hono.util.Adapter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) AuthenticationException(javax.security.sasl.AuthenticationException) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Tenant (org.eclipse.hono.service.management.tenant.Tenant)165 Test (org.junit.jupiter.api.Test)138 VertxTestContext (io.vertx.junit5.VertxTestContext)137 HttpURLConnection (java.net.HttpURLConnection)122 Truth.assertThat (com.google.common.truth.Truth.assertThat)113 TimeUnit (java.util.concurrent.TimeUnit)109 JsonObject (io.vertx.core.json.JsonObject)108 Future (io.vertx.core.Future)107 Timeout (io.vertx.junit5.Timeout)99 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)98 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)97 Constants (org.eclipse.hono.util.Constants)95 Tenants (org.eclipse.hono.tests.Tenants)92 Optional (java.util.Optional)91 Promise (io.vertx.core.Promise)86 Device (org.eclipse.hono.service.management.device.Device)80 Adapter (org.eclipse.hono.util.Adapter)78 VertxExtension (io.vertx.junit5.VertxExtension)77 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)77 Logger (org.slf4j.Logger)74