Search in sources :

Example 1 with FindOptions

use of io.vertx.ext.mongo.FindOptions in project vertx-zero by silentbalanceyh.

the class MongoReadOpts method toFull.

/**
 * Query all records by pager/sorter both
 *
 * @param pager
 * @param sorter
 * @return
 */
public static FindOptions toFull(final Pager pager, final Sorter sorter) {
    final FindOptions options = new FindOptions();
    Fn.safeNull(() -> {
        options.setLimit(pager.getSize());
        options.setSkip(pager.getStart());
    }, pager);
    Fn.safeNull(() -> options.setSort(sorter.toJson((mode) -> mode ? 1 : -1)), sorter);
    return options;
}
Also used : FindOptions(io.vertx.ext.mongo.FindOptions)

Example 2 with FindOptions

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

the class MongoDbBasedTenantDao method getBySubjectDn.

/**
 * {@inheritDoc}
 */
@Override
public Future<TenantDto> getBySubjectDn(final X500Principal subjectDn, final SpanContext tracingContext) {
    Objects.requireNonNull(subjectDn);
    final String dn = subjectDn.getName(X500Principal.RFC2253);
    final Span span = tracer.buildSpan("get Tenant by subject DN").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_SUBJECT_DN, dn).start();
    return mongoClient.findWithOptions(collectionName, MongoDbDocumentBuilder.builder().withCa(dn).document(), new FindOptions().setLimit(2)).map(matchingDocuments -> {
        if (matchingDocuments.size() == 0) {
            LOG.debug("could not find tenant with matching trust anchor [subject DN: {}]", dn);
            throw new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "no such tenant");
        } else if (matchingDocuments.size() == 1) {
            final JsonObject tenantJsonResult = matchingDocuments.get(0);
            return TenantDto.forRead(tenantJsonResult.getString(Constants.JSON_FIELD_TENANT_ID), tenantJsonResult.getJsonObject(TenantDto.FIELD_TENANT).mapTo(Tenant.class), tenantJsonResult.getInstant(TenantDto.FIELD_CREATED), tenantJsonResult.getInstant(TenantDto.FIELD_UPDATED_ON), tenantJsonResult.getString(TenantDto.FIELD_VERSION));
        } else {
            LOG.debug("found multiple tenants with matching trust anchor [subject DN: {}]", dn);
            throw new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "found multiple tenants with matching trust anchor");
        }
    }).onFailure(t -> TracingHelper.logError(span, "error retrieving tenant", t)).recover(this::mapError).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) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Example 3 with FindOptions

use of io.vertx.ext.mongo.FindOptions 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 4 with FindOptions

use of io.vertx.ext.mongo.FindOptions 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 5 with FindOptions

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

the class MongoDbBasedDeviceDao method resolveGroupMembers.

/**
 * {@inheritDoc}
 */
@Override
public Future<Set<String>> resolveGroupMembers(final String tenantId, final Set<String> viaGroups, final SpanContext tracingContext) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(viaGroups);
    if (viaGroups.isEmpty()) {
        return Future.succeededFuture(Set.of());
    }
    final Span span = tracer.buildSpan("resolve group members").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    span.log("resolving " + viaGroups.size() + " device groups");
    final var deviceMemberOfSpec = new JsonObject().put("$exists", true).put("$in", new JsonArray(List.copyOf(viaGroups)));
    final JsonObject resolveGroupMembersQuery = MongoDbDocumentBuilder.builder().withTenantId(tenantId).document().put(PROPERTY_DEVICE_MEMBER_OF, deviceMemberOfSpec);
    // retrieve only the deviceId instead of the whole document.
    final FindOptions findOptions = new FindOptions().setFields(new JsonObject().put(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID, true).put("_id", false));
    return mongoClient.findWithOptions(collectionName, resolveGroupMembersQuery, findOptions).map(documents -> {
        if (documents == null) {
            final Set<String> result = Set.of();
            return result;
        } else {
            span.log("successfully resolved " + documents.size() + " group members");
            return documents.stream().map(json -> json.getString(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID)).collect(Collectors.toSet());
        }
    }).onComplete(r -> span.finish());
}
Also used : JsonArray(io.vertx.core.json.JsonArray) 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) Set(java.util.Set) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Aggregations

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