org.springframework.data.mongodb.core.CollectionOptions Java Examples

The following examples show how to use org.springframework.data.mongodb.core.CollectionOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebfluxDemo.java    From spring-five-functional-reactive with Apache License 2.0 6 votes vote down vote up
/**
 * Application runner to initialize a capped collection for {@link Event}s and insert a new {@link Event} every two
 * seconds.
 * 
 * @param operations
 * @param reactiveOperations
 * @return
 */
@Bean
ApplicationRunner onStart(MongoOperations operations, ReactiveMongoOperations reactiveOperations) {

	return args -> {

		CollectionOptions options = CollectionOptions.empty() //
				.capped() //
				.size(2048) //
				.maxDocuments(1000);

		operations.dropCollection(Event.class);
		operations.createCollection(Event.class, options);

		Flux.interval(Duration.ofSeconds(2)) //
				.map(counter -> new Event(LocalDateTime.now())) //
				.flatMap(reactiveOperations::save) //
				.log() //
				.subscribe();
	};
}
 
Example #2
Source File: ReactiveComapnyApplication.java    From reactive-company with Apache License 2.0 6 votes vote down vote up
@Bean
CommandLineRunner initData(ReactiveMongoTemplate reactiveMongoTemplate, BlogPostRepository blogPostRepository, ProjectRepository projectRepository) {
	return (p) -> {
		reactiveMongoTemplate.dropCollection(BlogPost.class).then(reactiveMongoTemplate.createCollection(
				BlogPost.class, CollectionOptions.empty().capped(104857600).size(104857600))).block();
		
		//blogPostRepository.deleteAll().block();
		blogPostRepository.save(new BlogPost("authorId1", "title1", "content1", "tagString1")).block();
		blogPostRepository.save(new BlogPost("authorId2", "title2", "content2", "tagString2")).block();
		blogPostRepository.save(new BlogPost("authorId3", "title3", "content3", "tagString3")).block();
		blogPostRepository.save(new BlogPost("authorId4", "title4", "content4", "tagString4")).block();

		projectRepository.deleteAll().block();
		projectRepository.save(new Project("name1", "repoUrl1", "siteUrl1", "category1", "description1")).block();
		projectRepository.save(new Project("name2", "repoUrl2", "siteUrl2", "category2", "description2")).block();
		projectRepository.save(new Project("name3", "repoUrl3", "siteUrl3", "category3", "description3")).block();
		projectRepository.save(new Project("name4", "repoUrl4", "siteUrl4", "category4", "description4")).block();
	};
}
 
Example #3
Source File: RxJava2PersonRepositoryIntegrationTest.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

	Mono<MongoCollection<Document>> recreateCollection = operations.collectionExists(Person.class) //
			.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
			.then(operations.createCollection(Person.class, CollectionOptions.empty() //
					.size(1024 * 1024) //
					.maxDocuments(100) //
					.capped()));

	StepVerifier.create(recreateCollection).expectNextCount(1).verifyComplete();

	repository.saveAll(Flowable.just(new Person("Walter", "White", 50), //
			new Person("Skyler", "White", 45), //
			new Person("Saul", "Goodman", 42), //
			new Person("Jesse", "Pinkman", 27))) //
			.test() //
			.awaitCount(4) //
			.assertNoErrors() //
			.awaitTerminalEvent();
}
 
Example #4
Source File: ReactivePersonRepositoryIntegrationTest.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

	Mono<MongoCollection<Document>> recreateCollection = operations.collectionExists(Person.class) //
			.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
			.then(operations.createCollection(Person.class, CollectionOptions.empty() //
					.size(1024 * 1024) //
					.maxDocuments(100) //
					.capped()));

	StepVerifier.create(recreateCollection).expectNextCount(1).verifyComplete();

	Flux<Person> insertAll = operations.insertAll(Flux.just(new Person("Walter", "White", 50), //
					new Person("Skyler", "White", 45), //
					new Person("Saul", "Goodman", 42), //
			new Person("Jesse", "Pinkman", 27)).collectList());

	StepVerifier.create(insertAll).expectNextCount(4).verifyComplete();
}
 
Example #5
Source File: SensorsSimulator.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
private void initializeDb() {
   CollectionOptions collectionOptions = CollectionOptions.empty()
      .capped()
      .size(COLLECTION_MAX_SIZE);

   mongoOperations.createCollection(
       SensorsReadings.COLLECTION_NAME,
       collectionOptions
   ).block();
}
 
Example #6
Source File: MongoConfig.java    From service-block-samples with Apache License 2.0 5 votes vote down vote up
@Bean
CommandLineRunner commandLineRunner(MongoOperations operations) {
    return (args) -> {
        // Setup the streaming data endpoint
        if (operations.collectionExists("tightCouplingEvent")) {
            operations.dropCollection("tightCouplingEvent");
        }
        if (operations.collectionExists("query")) {
            operations.dropCollection("query");
        }

        CollectionOptions options = new CollectionOptions(5242880, 100000, true);
        operations.createCollection("tightCouplingEvent", options);
    };
}
 
Example #7
Source File: TenantLogRepository.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
private void checkCollection(String collectionName) {

		if (!mongoAuditTemplate.collectionExists(collectionName)) {
			CollectionOptions options = new CollectionOptions(512000, MAX_DOCUMENTS, true);
			mongoAuditTemplate.createCollection(collectionName, options);
		}

	}
 
Example #8
Source File: WebFluxIntegrationTests.java    From POC with Apache License 2.0 5 votes vote down vote up
@BeforeAll
void setUp() {
	if (!this.operations.collectionExists(Book.class).block()) {
		this.operations.createCollection(Book.class,
				CollectionOptions.empty().size(1024 * 1024).maxDocuments(100).capped()).then().block();
	}
	this.bookReactiveRepository.save(
			Book.builder().title("MongoDbCookBook").text("MongoDB Data Book").author("Raja").bookId("1").build())
			.then().block();
}
 
Example #9
Source File: InfoLogsCounterManualTest.java    From tutorials with MIT License 5 votes vote down vote up
private void createCappedCollectionUsingReactiveMongoTemplate(ReactiveMongoTemplate reactiveMongoTemplate) {
    reactiveMongoTemplate.dropCollection(Log.class).block();
    reactiveMongoTemplate.createCollection(Log.class, CollectionOptions.empty()
      .maxDocuments(5)
      .size(1024 * 1024L)
      .capped()).block();
}
 
Example #10
Source File: WarnLogsCounterManualTest.java    From tutorials with MIT License 5 votes vote down vote up
private void createCappedCollectionUsingReactiveMongoTemplate(ReactiveMongoTemplate reactiveMongoTemplate) {
    reactiveMongoTemplate.dropCollection(Log.class).block();
    reactiveMongoTemplate.createCollection(Log.class, CollectionOptions.empty()
      .maxDocuments(5)
      .size(1024 * 1024L)
      .capped()).block();
}
 
Example #11
Source File: LoggerCarrierAspectTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    mockedEntityRepository = mock(MongoRepository.class);
    DBCollection mockedCollection = Mockito.mock(DBCollection.class);
    DB mockedDB = Mockito.mock(DB.class);
    SecurityEvent event = createSecurityEvent();
    LoggerCarrierAspect.aspectOf().setEntityRepository(mockedEntityRepository);
    LoggerCarrierAspect.aspectOf().setCapSize(new String("100"));

    MongoEntityTemplate mockedMongoTemplate = mock(MongoEntityTemplate.class);
    when(mockedEntityRepository.getTemplate()).thenReturn(mockedMongoTemplate);

    when(mockedMongoTemplate.collectionExists("securityEvent")).thenReturn(false);
    audit(event);
    Mockito.verify(mockedMongoTemplate, times(1)).createCollection(any(String.class), any(CollectionOptions.class));
    Mockito.verify(mockedEntityRepository, times(1)).create(any(String.class), any(Map.class), any(Map.class), any(String.class));

    when(mockedMongoTemplate.collectionExists("securityEvent")).thenReturn(true);
    when(mockedMongoTemplate.getCollection("securityEvent")).thenReturn(mockedCollection);
    when(mockedCollection.isCapped()).thenReturn(true);
    audit(event);
    Mockito.verify(mockedEntityRepository, times(2)).create(any(String.class), any(Map.class), any(Map.class), any(String.class));

    when(mockedMongoTemplate.collectionExists("securityEvent")).thenReturn(true);
    when(mockedMongoTemplate.getCollection("securityEvent")).thenReturn(mockedCollection);
    when(mockedMongoTemplate.getDb()).thenReturn(mockedDB);
    when(mockedCollection.isCapped()).thenReturn(false);
    audit(event);
    Mockito.verify(mockedDB, times(1)).command(any(DBObject.class));

    Mockito.verify(mockedEntityRepository, times(3)).create(any(String.class), any(Map.class), any(Map.class), any(String.class));
}
 
Example #12
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
private void checkCollection(String collectionName) {
	if (!mongoPrivateStorageTemplate.collectionExists(collectionName)) {
		CollectionOptions options = new CollectionOptions(1073741824, null, false);
		mongoPrivateStorageTemplate.createCollection(collectionName, options);
	}
}
 
Example #13
Source File: Data.java    From reactive-matchday with Apache License 2.0 4 votes vote down vote up
public static void initializeAllData(final ReactiveMongoTemplate mongoTemplate) {
    
    /*
     *  Drop collections, then create them again
     */
    final Mono<Void> initializeCollections =
            mongoTemplate
                    .dropCollection(Team.class)
                    .then(mongoTemplate.dropCollection(Match.class))
                    .then(mongoTemplate.dropCollection(Player.class))
                    .then(mongoTemplate.dropCollection(MatchEvent.class))
                    .then(mongoTemplate.dropCollection(MatchComment.class))
                    .then(mongoTemplate.createCollection(Team.class))
                    .then(mongoTemplate.createCollection(Match.class))
                    .then(mongoTemplate.createCollection(Player.class))
                    .then(mongoTemplate.createCollection(
                            MatchEvent.class, CollectionOptions.empty().size(104857600).capped())) // max: 100MBytes
                    .then(mongoTemplate.createCollection(
                            MatchComment.class, CollectionOptions.empty().size(104857600).capped())) // max: 100MBytes
                    .then();

    /*
     * Add some test data to the collections: teams and players will come from the
     * utility Data class, but we will generate matches between teams randomly each
     * time the application starts (for the fun of it)
     */
    final Mono<Void> initializeData =
            mongoTemplate
                    // Insert all the teams into the corresponding collection and log
                    .insert(Data.TEAMS, Team.class)
                    .log(LOGGER_INITIALIZE, Level.FINEST)
                    // Collect all inserted team codes and randomly shuffle the list
                    .map(Team::getCode).collectList().doOnNext(Collections::shuffle)
                    .flatMapMany(list -> Flux.fromIterable(list))
                    // Create groups of two teams and insert a new Match for them
                    .buffer(2).map(twoTeams -> new Match(twoTeams.get(0), twoTeams.get(1)))
                    .flatMap(mongoTemplate::insert)
                    .log(LOGGER_INITIALIZE, Level.FINEST)
                    .concatMap(match -> mongoTemplate.insert(new MatchEvent(match.getId(), MatchEvent.Type.MATCH_START, null, null)))
                    // Finally insert the players into their corresponding collection
                    .thenMany(Flux.fromIterable(Data.PLAYERS))
                    .flatMap(mongoTemplate::insert)
                    .log(LOGGER_INITIALIZE, Level.FINEST)
                    .then();


    /*
     * Perform the initialization, blocking (that's OK, we are bootstrapping a testing app)
     */
    initializeCollections.then(initializeData).block();
    
}
 
Example #14
Source File: DocumentValidation.java    From spring-data-examples with Apache License 2.0 4 votes vote down vote up
/**
 * MongoDB (as of version 3.2) supports validating documents against a given structure described by a query. The
 * structure can be built from {@link org.springframework.data.mongodb.core.query.Criteria} objects in the same way as
 * they are used for defining queries.
 *
 * <pre>
 *     <code>
 * {
 *     name : {
 *         $exists : true,
 *         $ne : null,
 *         $type : 2
 *     },
 *     age : {
 *         $exists : true,
 *         $ne : null,
 *         $type : 16,
 *         $gte : 0,
 *         $lte : 125
 *     }
 * }
 *     </code>
 * </pre>
 */
@Test
public void criteriaValidator() {

	Validator validator = Validator.criteria( //
			where("name").exists(true).ne(null).type(2) // non null String
					.and("age").exists(true).ne(null).type(16).gte(0).lte(125)) // non null int between 0 and 125
	;

	mongoOps.createCollection(Jedi.class, CollectionOptions.empty().validator(validator));

	assertThat(mongoOps.save(new Jedi("luke", "luke", "skywalker", 25))).isNotNull();

	assertThatExceptionOfType(DataIntegrityViolationException.class)
			.isThrownBy(() -> mongoOps.save(new Jedi("yoda", "yoda", null, 900)));
}
 
Example #15
Source File: DocumentValidation.java    From spring-data-examples with Apache License 2.0 4 votes vote down vote up
/**
 * As of version 3.6, MongoDB supports collections that validate documents against a provided JSON Schema that
 * complies to the JSON schema specification (draft 4).
 *
 * <pre>
 *     <code>
 * {
 *   "type": "object",
 *   "required": [ "name", "age" ],
 *   "properties": {
 *     "name": {
 *       "type": "string",
 *       "minLength": 1
 *     },
 *     "age": {
 *       "type": "int",
 *       "minimum" : 0,
 *       "exclusiveMinimum" : false,
 *       "maximum" : 125,
 *       "exclusiveMaximum" : false
 *     }
 *   }
 * }
 *     </code>
 * </pre>
 */
@Test
public void schemaValidator() {

	Validator validator = Validator.schema(MongoJsonSchema.builder() //
			.required("name", "age") //
			.properties( //
					string("name").minLength(1), //
					int32("age").gte(0).lte(125) //
			).build());
	mongoOps.createCollection(Jedi.class, CollectionOptions.empty().validator(validator));

	assertThat(mongoOps.save(new Jedi("luke", "luke", "skywalker", 25))).isNotNull();

	assertThatExceptionOfType(DataIntegrityViolationException.class)
			.isThrownBy(() -> mongoOps.save(new Jedi("yoda", "yoda", null, 900)));
}