use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.
the class ReactiveMongoTemplate method doUpdate.
protected Mono<UpdateResult> doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class<?> entityClass, final boolean upsert, final boolean multi) {
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
Flux<UpdateResult> result = execute(collectionName, collection -> {
increaseVersionForUpdateIfNecessary(entity, update);
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
if (!UpdateMapper.isUpdateObject(updateObj)) {
return collectionToUse.replaceOne(queryObj, updateObj, updateOptions);
}
if (multi) {
return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
}
return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
}).doOnNext(updateResult -> {
if (entity != null && entity.hasVersionProperty() && !multi) {
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (dbObjectContainsVersionProperty(queryObj, entity))
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toString() + " to collection " + collectionName);
}
}
});
return result.next();
}
use of org.springframework.data.mongodb.core.query.Collation in project cas by apereo.
the class MongoDbWebAuthnCredentialRepository method getRegistrationsByUsername.
@Override
public Collection<CredentialRegistration> getRegistrationsByUsername(final String username) {
val query = new Query().addCriteria(Criteria.where(MongoDbWebAuthnCredentialRegistration.FIELD_USERNAME).is(username)).collation(Collation.of(Locale.ENGLISH).strength(Collation.ComparisonLevel.primary()));
val records = mongoTemplate.find(query, MongoDbWebAuthnCredentialRegistration.class, getProperties().getAuthn().getMfa().getWebAuthn().getMongo().getCollection());
return records.stream().map(record -> getCipherExecutor().decode(record.getRecords())).map(Unchecked.function(record -> WebAuthnUtils.getObjectMapper().readValue(record, new TypeReference<Set<CredentialRegistration>>() {
}))).flatMap(Collection::stream).collect(Collectors.toList());
}
use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.
the class AggregationOptions method fromDocument.
/**
* Creates new {@link AggregationOptions} given {@link Document} containing aggregation options.
*
* @param document must not be {@literal null}.
* @return the {@link AggregationOptions}.
* @since 2.0
*/
public static AggregationOptions fromDocument(Document document) {
Assert.notNull(document, "Document must not be null!");
boolean allowDiskUse = document.getBoolean(ALLOW_DISK_USE, false);
boolean explain = document.getBoolean(EXPLAIN, false);
Document cursor = document.get(CURSOR, Document.class);
Collation collation = document.containsKey(COLLATION) ? Collation.from(document.get(COLLATION, Document.class)) : null;
String comment = document.getString(COMMENT);
Document hint = document.get(HINT, Document.class);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment, hint);
if (document.containsKey(MAX_TIME)) {
options.maxTime = Duration.ofMillis(document.getLong(MAX_TIME));
}
return options;
}
use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.
the class DefaultReactiveIndexOperationsTests method shouldCreateIndexWithCollationCorrectly.
// DATAMONGO-1518
@Test
public void shouldCreateIndexWithCollationCorrectly() {
IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC).collation(Collation.of("de_AT").caseFirst(CaseFirst.off()));
indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
Document expected = //
new Document("locale", "de_AT").append("caseLevel", //
false).append("caseFirst", //
"off").append("strength", //
3).append("numericOrdering", //
false).append("alternate", //
"non-ignorable").append("maxVariable", //
"punct").append("normalization", //
false).append("backwards", false);
//
indexOps.getIndexInfo().filter(this.indexByName("with-collation")).as(StepVerifier::create).consumeNextWith(indexInfo -> {
assertThat(indexInfo.getCollation()).isPresent();
// version is set by MongoDB server - we remove it to avoid errors when upgrading server version.
Document result = indexInfo.getCollation().get();
result.remove("version");
assertThat(result).isEqualTo(expected);
}).verifyComplete();
}
use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.
the class MongoTemplate method aggregateStream.
@SuppressWarnings("ConstantConditions")
protected <O> CloseableIterator<O> aggregateStream(Aggregation aggregation, String collectionName, Class<O> outputType, @Nullable AggregationOperationContext context) {
Assert.hasText(collectionName, "Collection name must not be null or empty!");
Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
Assert.notNull(outputType, "Output type must not be null!");
Assert.isTrue(!aggregation.getOptions().isExplain(), "Can't use explain option with streaming!");
AggregationDefinition aggregationDefinition = queryOperations.createAggregation(aggregation, context);
AggregationOptions options = aggregation.getOptions();
List<Document> pipeline = aggregationDefinition.getAggregationPipeline();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Streaming aggregation: %s in collection %s", serializeToJsonSafely(pipeline), collectionName));
}
ReadDocumentCallback<O> readCallback = new ReadDocumentCallback<>(mongoConverter, outputType, collectionName);
return execute(collectionName, (CollectionCallback<CloseableIterator<O>>) collection -> {
AggregateIterable<Document> cursor = collection.aggregate(pipeline, Document.class).allowDiskUse(options.isAllowDiskUse());
if (options.getCursorBatchSize() != null) {
cursor = cursor.batchSize(options.getCursorBatchSize());
}
options.getComment().ifPresent(cursor::comment);
options.getHint().ifPresent(cursor::hint);
Class<?> domainType = aggregation instanceof TypedAggregation ? ((TypedAggregation) aggregation).getInputType() : null;
Optionals.firstNonEmpty(options::getCollation, () -> operations.forType(domainType).getCollation()).map(Collation::toMongoCollation).ifPresent(cursor::collation);
return new CloseableIterableCursorAdapter<>(cursor, exceptionTranslator, readCallback);
});
}
Aggregations