Search in sources :

Example 6 with FindOptions

use of io.vertx.ext.mongo.FindOptions in project chili-core by codingchili.

the class MongoDBMap method query.

@Override
public QueryBuilder<Value> query(String field) {
    addIndex(field);
    return new AbstractQueryBuilder<Value>(this, field) {

        JsonArray statements = new JsonArray();

        JsonArray builder = new JsonArray();

        @Override
        public QueryBuilder<Value> and(String attribute) {
            addIndex(attribute);
            setAttribute(attribute);
            return this;
        }

        @Override
        public QueryBuilder<Value> or(String attribute) {
            addIndex(attribute);
            setAttribute(attribute);
            apply();
            return this;
        }

        /**
         * Applies the current state of the builder to the final query.
         */
        private void apply() {
            statements.add(new JsonObject().put(AND, builder));
            builder = new JsonArray();
        }

        @Override
        public QueryBuilder<Value> between(Long minimum, Long maximum) {
            builder.add(new JsonObject().put(attribute(), new JsonObject().put(GTE, minimum).put(LTE, maximum)));
            return this;
        }

        @Override
        public QueryBuilder<Value> like(String text) {
            text = Validator.toPlainText(text);
            builder.add(new JsonObject().put(attribute(), new JsonObject().put(REGEX, "^.*" + text + ".*$").put(OPTIONS, "i")));
            return this;
        }

        @Override
        public QueryBuilder<Value> startsWith(String text) {
            text = Validator.toPlainText(text);
            builder.add(new JsonObject().put(attribute(), new JsonObject().put(REGEX, "^" + text + ".*")));
            return this;
        }

        @Override
        public QueryBuilder<Value> in(Comparable... comparables) {
            List<Comparable> list = new ArrayList<>();
            list.addAll(Arrays.asList(comparables));
            builder.add(new JsonObject().put(attribute(), new JsonObject().put(IN, list)));
            return this;
        }

        @Override
        public QueryBuilder<Value> equalTo(Comparable match) {
            builder.add(new JsonObject().put(attribute(), match));
            return this;
        }

        @Override
        public QueryBuilder<Value> matches(String regex) {
            builder.add(new JsonObject().put(attribute(), new JsonObject().put(REGEX, regex)));
            return this;
        }

        @Override
        public void execute(Handler<AsyncResult<Collection<Value>>> handler) {
            apply();
            client.findWithOptions(collection, new JsonObject().put(OR, statements), getOptions(), find -> {
                if (find.succeeded()) {
                    handler.handle(result(toList(find.result())));
                } else {
                    handler.handle(error(find.cause()));
                }
            });
        }

        private FindOptions getOptions() {
            return new FindOptions().setLimit(pageSize).setSkip(pageSize * page).setSort(getSortOptions());
        }

        private JsonObject getSortOptions() {
            if (isOrdered) {
                return new JsonObject().put(getOrderByAttribute(), getSortDirection());
            } else {
                return new JsonObject();
            }
        }
    };
}
Also used : JsonArray(io.vertx.core.json.JsonArray) FindOptions(io.vertx.ext.mongo.FindOptions) JsonObject(io.vertx.core.json.JsonObject) Handler(io.vertx.core.Handler)

Example 7 with FindOptions

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

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