Search in sources :

Example 1 with UpdateOptions

use of io.vertx.ext.mongo.UpdateOptions in project hono by eclipse.

the class MongoDbBasedTenantDao method update.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> update(final TenantDto newTenantConfig, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(newTenantConfig);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("update Tenant").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, newTenantConfig.getTenantId()).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    final JsonObject updateTenantQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(newTenantConfig.getTenantId()).document();
    return validateTrustAnchors(newTenantConfig, span).compose(ok -> mongoClient.findOneAndReplaceWithOptions(collectionName, updateTenantQuery, JsonObject.mapFrom(newTenantConfig), new FindOptions(), new UpdateOptions().setReturningNewDocument(true))).compose(updateResult -> {
        if (updateResult == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(newTenantConfig.getTenantId(), resourceVersion, getById(newTenantConfig.getTenantId(), false, span));
        } else {
            LOG.debug("successfully updated tenant [tenant-id: {}]", newTenantConfig.getTenantId());
            span.log("successfully updated tenant");
            return Future.succeededFuture(updateResult.getString(TenantDto.FIELD_VERSION));
        }
    }).recover(error -> {
        if (MongoDbBasedDao.isDuplicateKeyError(error)) {
            LOG.debug("failed to update tenant [{}], tenant alias already in use", newTenantConfig.getTenantId(), error);
            final var exception = new ClientErrorException(newTenantConfig.getTenantId(), HttpURLConnection.HTTP_CONFLICT, "tenant alias already in use");
            TracingHelper.logError(span, exception);
            return Future.failedFuture(exception);
        } else {
            TracingHelper.logError(span, "error updating tenant", error);
            return mapError(error);
        }
    }).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X500Principal(javax.security.auth.x500.X500Principal) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ArrayList(java.util.ArrayList) 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) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) 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) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Example 2 with UpdateOptions

use of io.vertx.ext.mongo.UpdateOptions 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 UpdateOptions

use of io.vertx.ext.mongo.UpdateOptions in project okapi by folio-org.

the class MongoUtil method add.

public void add(T env, String id, Handler<ExtendedAsyncResult<Void>> fut) {
    JsonObject jq = new JsonObject().put("_id", id);
    String s = Json.encodePrettily(env);
    JsonObject document = new JsonObject(s);
    encode(document, id);
    UpdateOptions options = new UpdateOptions().setUpsert(true);
    cli.updateCollectionWithOptions(collection, jq, new JsonObject().put("$set", document), options, res -> {
        if (res.succeeded()) {
            fut.handle(new Success<>());
        } else {
            fut.handle(new Failure<>(INTERNAL, res.cause()));
        }
    });
}
Also used : JsonObject(io.vertx.core.json.JsonObject) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Example 4 with UpdateOptions

use of io.vertx.ext.mongo.UpdateOptions in project hono by eclipse.

the class MongoDbBasedCredentialsDao method update.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> update(final CredentialsDto credentials, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(credentials);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("update Credentials").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, credentials.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, credentials.getDeviceId()).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    credentials.getCredentials().stream().forEach(cred -> cred.encryptFields(fieldLevelEncryption));
    final JsonObject replaceCredentialsQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(credentials.getTenantId()).withDeviceId(credentials.getDeviceId()).document();
    final var document = JsonObject.mapFrom(credentials);
    if (LOG.isTraceEnabled()) {
        LOG.trace("updating credentials of device [tenant: {}, device-id: {}, resource-version; {}]:{}{}", credentials.getTenantId(), credentials.getDeviceId(), resourceVersion.orElse(null), System.lineSeparator(), document.encodePrettily());
    }
    return mongoClient.findOneAndReplaceWithOptions(collectionName, replaceCredentialsQuery, document, new FindOptions(), new UpdateOptions().setReturningNewDocument(true)).compose(result -> {
        if (result == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(String.format("credentials [tenant-id: %s, device-id: %s]", credentials.getTenantId(), credentials.getDeviceId()), resourceVersion, getByDeviceId(credentials.getTenantId(), credentials.getDeviceId()));
        } else {
            LOG.debug("successfully updated credentials for device [tenant: {}, device-id: {}]", credentials.getTenantId(), credentials.getDeviceId());
            span.log("successfully updated credentials");
            if (LOG.isTraceEnabled()) {
                LOG.trace("new document in DB:{}{}", System.lineSeparator(), result.encodePrettily());
            }
            return Future.succeededFuture(result.getString(CredentialsDto.FIELD_VERSION));
        }
    }).recover(error -> {
        if (MongoDbBasedDao.isDuplicateKeyError(error)) {
            return Future.failedFuture(new ClientErrorException(credentials.getTenantId(), HttpURLConnection.HTTP_CONFLICT, "credentials (type, auth-id) must be unique for device"));
        } else {
            return Future.failedFuture(error);
        }
    }).onFailure(error -> {
        LOG.debug("error updating credentials", error);
        TracingHelper.logError(span, "error updating credentials", error);
    }).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) FieldLevelEncryption(org.eclipse.hono.deviceregistry.util.FieldLevelEncryption) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) 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) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Aggregations

JsonObject (io.vertx.core.json.JsonObject)4 UpdateOptions (io.vertx.ext.mongo.UpdateOptions)4 References (io.opentracing.References)3 Span (io.opentracing.Span)3 SpanContext (io.opentracing.SpanContext)3 Tracer (io.opentracing.Tracer)3 Future (io.vertx.core.Future)3 Promise (io.vertx.core.Promise)3 HealthCheckHandler (io.vertx.ext.healthchecks.HealthCheckHandler)3 Status (io.vertx.ext.healthchecks.Status)3 FindOptions (io.vertx.ext.mongo.FindOptions)3 IndexOptions (io.vertx.ext.mongo.IndexOptions)3 MongoClient (io.vertx.ext.mongo.MongoClient)3 HttpURLConnection (java.net.HttpURLConnection)3 Objects (java.util.Objects)3 Optional (java.util.Optional)3 UUID (java.util.UUID)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 ClientErrorException (org.eclipse.hono.client.ClientErrorException)3 MongoDbDocumentBuilder (org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder)3