Search in sources :

Example 1 with DeviceDto

use of org.eclipse.hono.service.management.device.DeviceDto in project hono by eclipse.

the class MongoDbBasedDeviceDaoTest method testCreateSetsCreationDate.

/**
 * Verifies that the DAO sets the initial version and creation date when creating a device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateSetsCreationDate(final VertxTestContext ctx) {
    when(mongoClient.insert(anyString(), any(JsonObject.class))).thenReturn(Future.succeededFuture("initial-version"));
    final var dto = DeviceDto.forCreation(DeviceDto::new, "tenantId", "deviceId", new Device(), "initial-version");
    dao.create(dto, NoopSpan.INSTANCE.context()).onComplete(ctx.succeeding(version -> {
        ctx.verify(() -> {
            assertThat(version).isEqualTo("initial-version");
            final var document = ArgumentCaptor.forClass(JsonObject.class);
            verify(mongoClient).insert(eq("devices"), document.capture());
            MongoDbBasedTenantDaoTest.assertCreationDocumentContainsStatusProperties(document.getValue(), "initial-version");
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Timeout(io.vertx.junit5.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JsonObject(io.vertx.core.json.JsonObject) Device(org.eclipse.hono.service.management.device.Device) MongoClient(io.vertx.ext.mongo.MongoClient) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) VertxExtension(io.vertx.junit5.VertxExtension) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ChronoUnit(java.time.temporal.ChronoUnit) Optional(java.util.Optional) FindOptions(io.vertx.ext.mongo.FindOptions) NoopSpan(io.opentracing.noop.NoopSpan) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Device(org.eclipse.hono.service.management.device.Device) JsonObject(io.vertx.core.json.JsonObject) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) Test(org.junit.jupiter.api.Test)

Example 2 with DeviceDto

use of org.eclipse.hono.service.management.device.DeviceDto in project hono by eclipse.

the class MongoDbBasedDeviceDao method update.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> update(final DeviceDto deviceConfig, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(deviceConfig);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("update Device").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, deviceConfig.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, deviceConfig.getDeviceId()).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    final JsonObject updateDeviceQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(deviceConfig.getTenantId()).withDeviceId(deviceConfig.getDeviceId()).document();
    final var document = JsonObject.mapFrom(deviceConfig);
    if (LOG.isTraceEnabled()) {
        LOG.trace("replacing existing device document with:{}{}", System.lineSeparator(), document.encodePrettily());
    }
    return mongoClient.findOneAndReplaceWithOptions(collectionName, updateDeviceQuery, document, new FindOptions(), new UpdateOptions().setReturningNewDocument(true)).compose(result -> {
        if (result == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(deviceConfig.getDeviceId(), resourceVersion, getById(deviceConfig.getTenantId(), deviceConfig.getDeviceId(), span));
        } else {
            span.log("successfully updated device");
            return Future.succeededFuture(result.getString(DeviceDto.FIELD_VERSION));
        }
    }).onFailure(t -> TracingHelper.logError(span, "error updating device", t)).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) Sort(org.eclipse.hono.service.management.Sort) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) SearchResult(org.eclipse.hono.service.management.SearchResult) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) Set(java.util.Set) MongoClient(io.vertx.ext.mongo.MongoClient) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) FindOptions(io.vertx.ext.mongo.FindOptions) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Example 3 with DeviceDto

use of org.eclipse.hono.service.management.device.DeviceDto in project hono by eclipse.

the class MongoDbBasedDeviceDaoTest method testUpdateSetsLastUpdate.

/**
 * Verifies that the DAO sets the new version and last update time but also keeps the original
 * creation date when updating a device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateSetsLastUpdate(final VertxTestContext ctx) {
    final var existingRecord = DeviceDto.forRead(DeviceDto::new, "tenantId", "deviceId", new Device(), false, false, Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.SECONDS), null, "initial-version");
    when(mongoClient.findOneAndReplaceWithOptions(anyString(), any(JsonObject.class), any(JsonObject.class), any(FindOptions.class), any(UpdateOptions.class))).thenReturn(Future.succeededFuture(new JsonObject().put(DeviceDto.FIELD_VERSION, "new-version")));
    final var dto = DeviceDto.forUpdate(() -> existingRecord, "tenantId", "deviceId", new Device(), "new-version");
    dao.update(dto, Optional.of(existingRecord.getVersion()), NoopSpan.INSTANCE.context()).onComplete(ctx.succeeding(newVersion -> {
        ctx.verify(() -> {
            final var document = ArgumentCaptor.forClass(JsonObject.class);
            verify(mongoClient).findOneAndReplaceWithOptions(eq("devices"), any(JsonObject.class), document.capture(), any(FindOptions.class), any(UpdateOptions.class));
            MongoDbBasedTenantDaoTest.assertUpdateDocumentContainsStatusProperties(document.getValue(), "new-version", existingRecord.getCreationTime());
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Timeout(io.vertx.junit5.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JsonObject(io.vertx.core.json.JsonObject) Device(org.eclipse.hono.service.management.device.Device) MongoClient(io.vertx.ext.mongo.MongoClient) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) VertxExtension(io.vertx.junit5.VertxExtension) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ChronoUnit(java.time.temporal.ChronoUnit) Optional(java.util.Optional) FindOptions(io.vertx.ext.mongo.FindOptions) NoopSpan(io.opentracing.noop.NoopSpan) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) FindOptions(io.vertx.ext.mongo.FindOptions) Device(org.eclipse.hono.service.management.device.Device) JsonObject(io.vertx.core.json.JsonObject) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) Test(org.junit.jupiter.api.Test)

Example 4 with DeviceDto

use of org.eclipse.hono.service.management.device.DeviceDto in project hono by eclipse.

the class MongoDbBasedDeviceDao method create.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> create(final DeviceDto deviceConfig, final SpanContext tracingContext) {
    Objects.requireNonNull(deviceConfig);
    final Span span = tracer.buildSpan("create Device").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, deviceConfig.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, deviceConfig.getDeviceId()).start();
    return mongoClient.insert(collectionName, JsonObject.mapFrom(deviceConfig)).map(success -> {
        span.log("successfully created device");
        LOG.debug("successfully created device [tenant: {}, device-id: {}, resource-version: {}]", deviceConfig.getTenantId(), deviceConfig.getDeviceId(), deviceConfig.getVersion());
        return deviceConfig.getVersion();
    }).recover(error -> {
        if (MongoDbBasedDao.isDuplicateKeyError(error)) {
            LOG.debug("device [{}] already exists for tenant [{}]", deviceConfig.getDeviceId(), deviceConfig.getTenantId(), error);
            TracingHelper.logError(span, "device already exists");
            throw new ClientErrorException(deviceConfig.getTenantId(), HttpURLConnection.HTTP_CONFLICT, "device already exists");
        } else {
            TracingHelper.logError(span, "error creating device", error);
            return mapError(error);
        }
    }).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) Sort(org.eclipse.hono.service.management.Sort) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) SearchResult(org.eclipse.hono.service.management.SearchResult) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) Set(java.util.Set) MongoClient(io.vertx.ext.mongo.MongoClient) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) DeviceDto(org.eclipse.hono.service.management.device.DeviceDto) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span)

Aggregations

Future (io.vertx.core.Future)4 JsonObject (io.vertx.core.json.JsonObject)4 FindOptions (io.vertx.ext.mongo.FindOptions)4 MongoClient (io.vertx.ext.mongo.MongoClient)4 UpdateOptions (io.vertx.ext.mongo.UpdateOptions)4 Optional (java.util.Optional)4 DeviceDto (org.eclipse.hono.service.management.device.DeviceDto)4 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 References (io.opentracing.References)2 Span (io.opentracing.Span)2 SpanContext (io.opentracing.SpanContext)2 Tracer (io.opentracing.Tracer)2 NoopSpan (io.opentracing.noop.NoopSpan)2 Promise (io.vertx.core.Promise)2 JsonArray (io.vertx.core.json.JsonArray)2 HealthCheckHandler (io.vertx.ext.healthchecks.HealthCheckHandler)2 Status (io.vertx.ext.healthchecks.Status)2 IndexOptions (io.vertx.ext.mongo.IndexOptions)2 Timeout (io.vertx.junit5.Timeout)2 VertxExtension (io.vertx.junit5.VertxExtension)2