Search in sources :

Example 11 with TenantObject

use of org.eclipse.hono.util.TenantObject in project hono by eclipse.

the class HttpTestBase method testUploadMessages.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessages(final TestContext ctx) throws InterruptedException {
    final int messagesToSend = 100;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addTenant(JsonObject.mapFrom(tenant)).compose(ok -> helper.registry.registerDevice(tenantId, deviceId)).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 20 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    while (messageCount.get() < messagesToSend) {
        final Async sending = ctx.async();
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement())).setHandler(attempt -> {
            if (attempt.succeeded()) {
                LOGGER.debug("sent message {} [status code: 202]", messageCount.get());
            } else {
                LOGGER.debug("sent message {} [status code: {}]", messageCount.get(), ((ServiceInvocationException) attempt.cause()).getErrorCode());
            }
            sending.complete();
        });
        if (messageCount.get() % 20 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sending.await();
    }
    long timeToWait = Math.max(TEST_TIMEOUT - 1000, Math.round(messagesToSend * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 12 with TenantObject

use of org.eclipse.hono.util.TenantObject in project hono by eclipse.

the class MqttTestBase method doTestUploadMessages.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @param useShortTopicName Whether to use standard or short topic names
 * @throws InterruptedException if the test fails.
 */
public void doTestUploadMessages(final TestContext ctx, boolean useShortTopicName) throws InterruptedException {
    final int messagesToSend = 200;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addDeviceForTenant(tenant, deviceId, password).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 40 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).compose(ok -> {
        final Future<MqttConnAckMessage> result = Future.future();
        final MqttClientOptions options = new MqttClientOptions().setMaxInflightQueue(200).setUsername(IntegrationTestSupport.getUsername(deviceId, tenantId)).setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result.completer());
        return result;
    }).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    final AtomicReference<Async> sendResult = new AtomicReference<>();
    mqttClient.publishCompletionHandler(packetId -> {
        if (pendingMessages.remove(packetId)) {
            sendResult.get().complete();
        } else {
            LOGGER.info("received PUBACK for unexpected message [id: {}]", packetId);
        }
    });
    while (messageCount.get() < messagesToSend) {
        sendResult.set(ctx.async());
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement()), useShortTopicName, sendAttempt -> {
            if (sendAttempt.failed()) {
                LOGGER.debug("error sending message {}", messageCount.get(), sendAttempt.cause());
            } else {
                pendingMessages.add(sendAttempt.result());
            }
        });
        if (messageCount.get() % 40 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sendResult.get().await();
    }
    long timeToWait = Math.max(TEST_TIMEOUT - 1000, Math.round(messagesToSend * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) MqttClient(io.vertx.mqtt.MqttClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) AsyncResult(io.vertx.core.AsyncResult) MqttConnAckMessage(io.vertx.mqtt.messages.MqttConnAckMessage) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 13 with TenantObject

use of org.eclipse.hono.util.TenantObject in project hono by eclipse.

the class TenantClientImplTest method testGetTenantReturnsValueFromCache.

/**
 * Verifies that tenant information is taken from cache if cache is configured and the cache has this tenant
 * information cached.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetTenantReturnsValueFromCache(final TestContext ctx) {
    // GIVEN an adapter with a cache containing a tenant
    client.setResponseCache(cache);
    final JsonObject tenantJsonObject = newTenantResult("tenant");
    final TenantResult<TenantObject> tenantResult = client.getResult(HttpURLConnection.HTTP_OK, tenantJsonObject.toString(), null);
    when(cache.get(any(TriTuple.class))).thenReturn(tenantResult);
    // WHEN getting tenant information
    client.get("tenant").setHandler(ctx.asyncAssertSuccess(result -> {
        // THEN the tenant information is read from the cache
        ctx.assertEquals(tenantResult.getPayload(), result);
        verify(sender, never()).send(any(Message.class));
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) TestContext(io.vertx.ext.unit.TestContext) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) ExpiringValueCache(org.eclipse.hono.cache.ExpiringValueCache) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) ArgumentCaptor(org.mockito.ArgumentCaptor) TenantAction(org.eclipse.hono.util.TenantConstants.TenantAction) Duration(java.time.Duration) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) TenantResult(org.eclipse.hono.util.TenantResult) TriTuple(org.eclipse.hono.util.TriTuple) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) TenantObject(org.eclipse.hono.util.TenantObject) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) TriTuple(org.eclipse.hono.util.TriTuple) TenantObject(org.eclipse.hono.util.TenantObject) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Aggregations

TenantObject (org.eclipse.hono.util.TenantObject)13 JsonObject (io.vertx.core.json.JsonObject)9 Message (org.apache.qpid.proton.message.Message)8 Test (org.junit.Test)8 Buffer (io.vertx.core.buffer.Buffer)7 Future (io.vertx.core.Future)6 TestContext (io.vertx.ext.unit.TestContext)6 Vertx (io.vertx.core.Vertx)5 Async (io.vertx.ext.unit.Async)5 HttpURLConnection (java.net.HttpURLConnection)5 TenantConstants (org.eclipse.hono.util.TenantConstants)5 Rule (org.junit.Rule)5 Timeout (org.junit.rules.Timeout)5 Handler (io.vertx.core.Handler)4 TimeUnit (java.util.concurrent.TimeUnit)4 Consumer (java.util.function.Consumer)4 MessageConsumer (org.eclipse.hono.client.MessageConsumer)4 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)4 AfterClass (org.junit.AfterClass)4 Logger (org.slf4j.Logger)4