Search in sources :

Example 61 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class CommandAndControlMqttIT method testSendCommandSucceeds.

private void testSendCommandSucceeds(final VertxTestContext ctx, final String commandTargetDeviceId, final Handler<MqttPublishMessage> commandConsumer, final Function<Buffer, Future<Void>> commandSender, final MqttCommandEndpointConfiguration endpointConfig, final int totalNoOfCommandsToSend, final MqttQoS subscribeQos) throws InterruptedException {
    final VertxTestContext setup = new VertxTestContext();
    final Checkpoint ready = setup.checkpoint(2);
    helper.registry.addDeviceToTenant(tenantId, deviceId, password).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).compose(ok -> createConsumer(tenantId, msg -> {
        // expect empty notification with TTD -1
        setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
        final TimeUntilDisconnectNotification notification = msg.getTimeUntilDisconnectNotification().orElse(null);
        LOGGER.info("received notification [{}]", notification);
        setup.verify(() -> assertThat(notification).isNotNull());
        if (notification.getTtd() == -1) {
            ready.flag();
        }
    })).compose(conAck -> subscribeToCommands(commandTargetDeviceId, commandConsumer, endpointConfig, subscribeQos)).onComplete(setup.succeeding(ok -> ready.flag()));
    assertWithMessage("setup of adapter finished within %s seconds", IntegrationTestSupport.getTestSetupTimeout()).that(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    final Checkpoint sendCommandsSucceeded = ctx.checkpoint();
    final CountDownLatch commandsSucceeded = new CountDownLatch(totalNoOfCommandsToSend);
    final AtomicInteger commandsSent = new AtomicInteger(0);
    final AtomicLong lastReceivedTimestamp = new AtomicLong(0);
    final long start = System.currentTimeMillis();
    while (commandsSent.get() < totalNoOfCommandsToSend) {
        final CountDownLatch commandSent = new CountDownLatch(1);
        context.runOnContext(go -> {
            commandsSent.getAndIncrement();
            final Buffer msg = commandsSent.get() % 2 == 0 ? Buffer.buffer("value: " + commandsSent.get()) : // use 'null' payload for half the commands, ensuring such commands also get forwarded
            null;
            commandSender.apply(msg).onComplete(sendAttempt -> {
                if (sendAttempt.failed()) {
                    LOGGER.info("error sending command {}", commandsSent.get(), sendAttempt.cause());
                } else {
                    lastReceivedTimestamp.set(System.currentTimeMillis());
                    commandsSucceeded.countDown();
                    if (commandsSucceeded.getCount() % 20 == 0) {
                        LOGGER.info("commands succeeded: {}", totalNoOfCommandsToSend - commandsSucceeded.getCount());
                    }
                }
                if (commandsSent.get() % 20 == 0) {
                    LOGGER.info("commands sent: " + commandsSent.get());
                }
                commandSent.countDown();
            });
        });
        commandSent.await();
    }
    final long timeToWait = totalNoOfCommandsToSend * 200;
    if (!commandsSucceeded.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("Timeout of {} milliseconds reached, stop waiting for commands to succeed", timeToWait);
    }
    if (lastReceivedTimestamp.get() == 0L) {
        // no message has been received at all
        lastReceivedTimestamp.set(System.currentTimeMillis());
    }
    final long commandsCompleted = totalNoOfCommandsToSend - commandsSucceeded.getCount();
    LOGGER.info("commands sent: {}, commands succeeded: {} after {} milliseconds", commandsSent.get(), commandsCompleted, lastReceivedTimestamp.get() - start);
    if (commandsCompleted == commandsSent.get()) {
        sendCommandsSucceeded.flag();
    } else {
        ctx.failNow(new IllegalStateException("did not complete all commands sent"));
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Timeout(io.vertx.junit5.Timeout) MessagingType(org.eclipse.hono.util.MessagingType) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ChannelPromise(io.netty.channel.ChannelPromise) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) MqttClientImpl(io.vertx.mqtt.impl.MqttClientImpl) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Method(java.lang.reflect.Method) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) MessageContext(org.eclipse.hono.application.client.MessageContext) SubscriberRole(org.eclipse.hono.tests.CommandEndpointConfiguration.SubscriberRole) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) IllegalStateException(javax.jms.IllegalStateException) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) Checkpoint(io.vertx.junit5.Checkpoint) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) VertxTestContext(io.vertx.junit5.VertxTestContext) GenericKafkaSender(org.eclipse.hono.tests.GenericKafkaSender) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) TimeUntilDisconnectNotification(org.eclipse.hono.util.TimeUntilDisconnectNotification) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Message(org.apache.qpid.proton.message.Message) MqttPubAckMessage(io.netty.handler.codec.mqtt.MqttPubAckMessage) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) Truth.assertThat(com.google.common.truth.Truth.assertThat) AssumeMessagingSystem(org.eclipse.hono.tests.AssumeMessagingSystem) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) NoopSpan(io.opentracing.noop.NoopSpan) GenericSenderLink(org.eclipse.hono.client.amqp.GenericSenderLink) Handler(io.vertx.core.Handler) Buffer(io.vertx.core.buffer.Buffer) IllegalStateException(javax.jms.IllegalStateException) Checkpoint(io.vertx.junit5.Checkpoint) AtomicLong(java.util.concurrent.atomic.AtomicLong) VertxTestContext(io.vertx.junit5.VertxTestContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TimeUntilDisconnectNotification(org.eclipse.hono.util.TimeUntilDisconnectNotification) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 62 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class CommandAndControlMqttIT method testSendOneWayCommandSucceeds.

/**
 * Verifies that the adapter forwards on-way commands from
 * an application to a device.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testSendOneWayCommandSucceeds(final MqttCommandEndpointConfiguration endpointConfig, final VertxTestContext ctx) throws InterruptedException {
    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway() ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5) : deviceId;
    final Checkpoint commandsReceived = ctx.checkpoint(COMMANDS_TO_SEND);
    final AtomicInteger counter = new AtomicInteger();
    testSendCommandSucceeds(ctx, commandTargetDeviceId, msg -> {
        LOGGER.trace("received one-way command [topic: {}]", msg.topicName());
        final ResourceIdentifier topic = ResourceIdentifier.fromString(msg.topicName());
        ctx.verify(() -> {
            endpointConfig.assertCommandPublishTopicStructure(topic, commandTargetDeviceId, true, "setValue");
        });
        commandsReceived.flag();
    }, payload -> {
        counter.incrementAndGet();
        return helper.sendOneWayCommand(tenantId, commandTargetDeviceId, "setValue", "text/plain", payload, helper.getSendCommandTimeout(counter.get() == 1));
    }, endpointConfig, COMMANDS_TO_SEND, MqttQoS.AT_MOST_ONCE);
}
Also used : ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Checkpoint(io.vertx.junit5.Checkpoint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Timeout(io.vertx.junit5.Timeout) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 63 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class CredentialsJmsIT method testRequestFailsForMissingSubject.

/**
 * Verifies that the service responds with a 400 status to a request that
 * has no subject.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRequestFailsForMissingSubject(final VertxTestContext ctx) {
    final JsonObject searchCriteria = CredentialsConstants.getSearchCriteria(CredentialsConstants.SECRETS_TYPE_PRESHARED_KEY, "device");
    getJmsBasedClient().sendRequest(tenantId, null, null, searchCriteria.toBuffer()).onComplete(ctx.failing(t -> {
        assertErrorCode(t, HttpURLConnection.HTTP_BAD_REQUEST);
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) JmsBasedCredentialsClient(org.eclipse.hono.tests.jms.JmsBasedCredentialsClient) JmsBasedHonoConnection(org.eclipse.hono.tests.jms.JmsBasedHonoConnection) VertxExtension(io.vertx.junit5.VertxExtension) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Timeout(io.vertx.junit5.Timeout) TimeUnit(java.util.concurrent.TimeUnit) AfterAll(org.junit.jupiter.api.AfterAll) Test(org.junit.jupiter.api.Test) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Buffer(io.vertx.core.buffer.Buffer) BeforeAll(org.junit.jupiter.api.BeforeAll) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) JsonObject(io.vertx.core.json.JsonObject) Checkpoint(io.vertx.junit5.Checkpoint) CredentialsAction(org.eclipse.hono.util.CredentialsConstants.CredentialsAction) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 64 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class CredentialsApiTests method testGetCredentialsWithGatewayAutoProvisioning.

/**
 * Verifies when no credentials are found, the properties related to auto-provisioning of gateways are enabled
 * in the corresponding tenant's CA entry and the client context contains a serialized X.509 certificate then
 * a gateway is auto-provisioned. (i.e A gateway is registered and it's corresponding credentials are stored).
 * <p>
 * It also verifies that an auto-provisioning event is successfully sent and the device registration
 * is updated accordingly.
 *
 * @param ctx The vert.x test context.
 * @throws CertificateException if the self signed certificate cannot be created.
 * @throws FileNotFoundException if the self signed certificate cannot be read.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsWithGatewayAutoProvisioning(final VertxTestContext ctx) throws CertificateException, FileNotFoundException {
    // GIVEN a tenant's trusted CA entry with auto-provisioning and auto-provision as gateway enabled
    // while device has not been registered and no credentials are stored yet
    final X509Certificate cert = createCertificate();
    final var tenant = Tenants.createTenantForTrustAnchor(cert);
    tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(true).setAutoProvisioningAsGatewayEnabled(true);
    testAutoProvisioningSucceeds(ctx, tenant, cert, true, null);
}
Also used : X509Certificate(java.security.cert.X509Certificate) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 65 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class CredentialsApiTests method testGetCredentialsWithDeviceAutoProvisioningUsingDeviceIdTemplate.

/**
 * Verifies when no credentials are found and if the properties related to auto-provisioning of devices are
 * enabled, the device id template is configured in the corresponding tenant's CA entry and the client context
 * contains a serialized X.509 certificate then a device is auto-provisioned.
 * (i.e A device is registered and it's corresponding credentials are stored).
 * <p>
 * Also verify that the device is auto-provisioned with a device id generated in accordance
 * with the configured device id template.
 * <p>
 * It also verifies that an auto-provisioning event is successfully sent and the device registration
 * is updated accordingly.
 *
 * @param ctx The vert.x test context.
 * @throws CertificateException if the self signed certificate cannot be created.
 * @throws FileNotFoundException if the self signed certificate cannot be read.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsWithDeviceAutoProvisioningUsingDeviceIdTemplate(final VertxTestContext ctx) throws CertificateException, FileNotFoundException {
    // GIVEN a tenant's trusted CA entry with auto-provisioning enabled
    // while device has not been registered and no credentials are stored yet
    final X509Certificate cert = createCertificate();
    final var tenant = Tenants.createTenantForTrustAnchor(cert);
    tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(true).setAutoProvisioningDeviceIdTemplate("test-device-{{subject-dn}}");
    final String expectedDeviceId = "test-device-" + cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    testAutoProvisioningSucceeds(ctx, tenant, cert, false, expectedDeviceId);
}
Also used : X509Certificate(java.security.cert.X509Certificate) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Aggregations

Timeout (io.vertx.junit5.Timeout)75 VertxTestContext (io.vertx.junit5.VertxTestContext)70 Test (org.junit.jupiter.api.Test)69 TimeUnit (java.util.concurrent.TimeUnit)64 Truth.assertThat (com.google.common.truth.Truth.assertThat)62 Future (io.vertx.core.Future)53 HttpURLConnection (java.net.HttpURLConnection)50 Handler (io.vertx.core.Handler)47 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)47 BeforeEach (org.junit.jupiter.api.BeforeEach)45 Buffer (io.vertx.core.buffer.Buffer)44 Promise (io.vertx.core.Promise)43 Vertx (io.vertx.core.Vertx)38 JsonObject (io.vertx.core.json.JsonObject)37 VertxExtension (io.vertx.junit5.VertxExtension)37 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)37 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)36 MethodSource (org.junit.jupiter.params.provider.MethodSource)34 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)33 Tenant (org.eclipse.hono.service.management.tenant.Tenant)33