Search in sources :

Example 1 with MongoDatabase

use of com.mongodb.reactivestreams.client.MongoDatabase in project mongo-java-driver by mongodb.

the class ConnectionsSurvivePrimaryStepDownProseTest method setUp.

@Before
public void setUp() {
    assumeTrue(isDiscoverableReplicaSet() && serverVersionAtLeast(4, 0));
    connectionPoolListener = new TestConnectionPoolListener();
    MongoClientSettings settings = MongoClientSettings.builder(getMongoClientSettings()).retryWrites(false).applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(connectionPoolListener)).build();
    collectionHelper = new CollectionHelper<>(new DocumentCodec(), new MongoNamespace(getDefaultDatabaseName(), COLLECTION_NAME));
    client = MongoClients.create(settings);
    MongoDatabase database = client.getDatabase(getDefaultDatabaseName());
    collection = client.getDatabase(getDefaultDatabaseName()).getCollection(COLLECTION_NAME);
    Mono.from(collection.withWriteConcern(WriteConcern.MAJORITY).drop()).block(TIMEOUT_DURATION);
    Mono.from(database.withWriteConcern(WriteConcern.MAJORITY).createCollection(COLLECTION_NAME)).block(TIMEOUT_DURATION);
}
Also used : Document(org.bson.Document) ClusterFixture.isDiscoverableReplicaSet(com.mongodb.ClusterFixture.isDiscoverableReplicaSet) Assume.assumeFalse(org.junit.Assume.assumeFalse) Fixture.getMongoClientSettings(com.mongodb.reactivestreams.client.Fixture.getMongoClientSettings) MongoClients(com.mongodb.reactivestreams.client.MongoClients) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) MongoClient(com.mongodb.reactivestreams.client.MongoClient) TIMEOUT_DURATION(com.mongodb.ClusterFixture.TIMEOUT_DURATION) Collections.singletonList(java.util.Collections.singletonList) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Arrays.asList(java.util.Arrays.asList) After(org.junit.After) DocumentCodec(org.bson.codecs.DocumentCodec) Assert.fail(org.junit.Assert.fail) MongoNotPrimaryException(com.mongodb.MongoNotPrimaryException) Before(org.junit.Before) CollectionHelper(com.mongodb.client.test.CollectionHelper) MongoNamespace(com.mongodb.MongoNamespace) MongoException(com.mongodb.MongoException) Assert.assertNotNull(org.junit.Assert.assertNotNull) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) ClusterFixture.getDefaultDatabaseName(com.mongodb.ClusterFixture.getDefaultDatabaseName) List(java.util.List) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) WriteConcern(com.mongodb.WriteConcern) Assert.assertEquals(org.junit.Assert.assertEquals) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) DocumentCodec(org.bson.codecs.DocumentCodec) Fixture.getMongoClientSettings(com.mongodb.reactivestreams.client.Fixture.getMongoClientSettings) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Before(org.junit.Before)

Example 2 with MongoDatabase

use of com.mongodb.reactivestreams.client.MongoDatabase in project mongo-java-driver by mongodb.

the class PojoQuickTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }
    // create codec registry for POJOs
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
    // get a handle to the "people" collection
    final MongoCollection<Person> collection = database.getCollection("people", Person.class);
    // drop all the data in it
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // make a document and insert it
    final Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(ada).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // get it (since it's the only one in there since we dropped the rest earlier on)
    ObservableSubscriber<Person> personSubscriber = new PrintToStringSubscriber<>();
    collection.find().first().subscribe(personSubscriber);
    personSubscriber.await();
    // now, lets add some more people so we can explore queries and cursors
    List<Person> people = asList(new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)));
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(people).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // get all the documents in the collection and print them out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find().subscribe(personSubscriber);
    personSubscriber.await();
    // now use a query to get 1 document out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(eq("address.city", "Wimborne")).first().subscribe(personSubscriber);
    personSubscriber.await();
    // now lets find every over 30
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(gt("age", 30)).subscribe(personSubscriber);
    personSubscriber.await();
    // Update One
    ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace"))).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Update Many
    updateSubscriber = new OperationSubscriber<>();
    collection.updateMany(not(eq("zip", null)), set("zip", null)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Replace One
    updateSubscriber = new OperationSubscriber<>();
    collection.replaceOne(eq("name", "Ada Lovelace"), ada).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Delete One
    ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
    collection.deleteOne(eq("address.city", "Wimborne")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Delete Many
    deleteSubscriber = new OperationSubscriber<>();
    collection.deleteMany(eq("address.city", "London")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Clean up
    successSubscriber = new OperationSubscriber<>();
    database.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) InsertManyResult(com.mongodb.client.result.InsertManyResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient) InsertOneResult(com.mongodb.client.result.InsertOneResult) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) PrintToStringSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintToStringSubscriber) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

Example 3 with MongoDatabase

use of com.mongodb.reactivestreams.client.MongoDatabase in project mongo-java-driver by mongodb.

the class GridFSTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 * @throws FileNotFoundException if the sample file cannot be found
 * @throws IOException if there was an exception closing an input stream
 */
public static void main(final String[] args) throws FileNotFoundException, IOException {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    ObservableSubscriber<Void> dropSubscriber = new OperationSubscriber<>();
    database.drop().subscribe(dropSubscriber);
    dropSubscriber.await();
    GridFSBucket gridFSBucket = GridFSBuckets.create(database);
    /*
         * UploadFromPublisher Example
         */
    // Get the input publisher
    Publisher<ByteBuffer> publisherToUploadFrom = toPublisher(ByteBuffer.wrap("MongoDB Tutorial..".getBytes(StandardCharsets.UTF_8)));
    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(new Document("type", "presentation"));
    ObservableSubscriber<ObjectId> uploadSubscriber = new OperationSubscriber<>();
    gridFSBucket.uploadFromPublisher("mongodb-tutorial", publisherToUploadFrom, options).subscribe(uploadSubscriber);
    ObjectId fileId = uploadSubscriber.get().get(0);
    /*
         * Find documents
         */
    System.out.println("File names:");
    ConsumerSubscriber<GridFSFile> filesSubscriber = new ConsumerSubscriber<>(gridFSFile -> System.out.println(" - " + gridFSFile.getFilename()));
    gridFSBucket.find().subscribe(filesSubscriber);
    filesSubscriber.await();
    /*
         * Find documents with a filter
         */
    filesSubscriber = new ConsumerSubscriber<>(gridFSFile -> System.out.println("Found: " + gridFSFile.getFilename()));
    gridFSBucket.find(eq("metadata.contentType", "image/png")).subscribe(filesSubscriber);
    filesSubscriber.await();
    /*
         * DownloadToPublisher
         */
    ObservableSubscriber<ByteBuffer> downloadSubscriber = new OperationSubscriber<>();
    gridFSBucket.downloadToPublisher(fileId).subscribe(downloadSubscriber);
    Integer size = downloadSubscriber.get().stream().map(Buffer::limit).reduce(0, Integer::sum);
    System.out.println("downloaded file sized: " + size);
    /*
         * DownloadToStreamByName
         */
    GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions().revision(0);
    downloadSubscriber = new OperationSubscriber<>();
    gridFSBucket.downloadToPublisher("mongodb-tutorial", downloadOptions).subscribe(downloadSubscriber);
    size = downloadSubscriber.get().stream().map(Buffer::limit).reduce(0, Integer::sum);
    System.out.println("downloaded file sized: " + size);
    /*
         * Rename
         */
    OperationSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    gridFSBucket.rename(fileId, "mongodbTutorial").subscribe(successSubscriber);
    successSubscriber.await();
    System.out.println("Renamed file");
    /*
         * Delete
         */
    successSubscriber = new OperationSubscriber<>();
    gridFSBucket.delete(fileId).subscribe(successSubscriber);
    successSubscriber.await();
    System.out.println("Deleted file");
    // Final cleanup
    successSubscriber = new OperationSubscriber<>();
    database.drop().subscribe(successSubscriber);
    successSubscriber.await();
    System.out.println("Finished");
}
Also used : Document(org.bson.Document) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) Publisher(org.reactivestreams.Publisher) ConsumerSubscriber(reactivestreams.helpers.SubscriberHelpers.ConsumerSubscriber) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) MongoClients(com.mongodb.reactivestreams.client.MongoClients) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ByteBuffer(java.nio.ByteBuffer) StandardCharsets(java.nio.charset.StandardCharsets) MongoClient(com.mongodb.reactivestreams.client.MongoClient) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions) GridFSBuckets(com.mongodb.reactivestreams.client.gridfs.GridFSBuckets) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) GridFSDownloadOptions(com.mongodb.client.gridfs.model.GridFSDownloadOptions) GridFSBucket(com.mongodb.reactivestreams.client.gridfs.GridFSBucket) ObservableSubscriber(reactivestreams.helpers.SubscriberHelpers.ObservableSubscriber) Buffer(java.nio.Buffer) PublisherHelpers.toPublisher(reactivestreams.helpers.PublisherHelpers.toPublisher) ObjectId(org.bson.types.ObjectId) Filters.eq(com.mongodb.client.model.Filters.eq) ByteBuffer(java.nio.ByteBuffer) Buffer(java.nio.Buffer) ObjectId(org.bson.types.ObjectId) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) Document(org.bson.Document) ByteBuffer(java.nio.ByteBuffer) GridFSBucket(com.mongodb.reactivestreams.client.gridfs.GridFSBucket) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ConsumerSubscriber(reactivestreams.helpers.SubscriberHelpers.ConsumerSubscriber) GridFSDownloadOptions(com.mongodb.client.gridfs.model.GridFSDownloadOptions) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions)

Example 4 with MongoDatabase

use of com.mongodb.reactivestreams.client.MongoDatabase in project spring-data-mongodb by spring-projects.

the class ReactivePerformanceTests method setupCollections.

private void setupCollections() {
    MongoDatabase db = this.mongo.getDatabase(DATABASE_NAME);
    for (String collectionName : COLLECTION_NAMES) {
        MongoCollection<Document> collection = db.getCollection(collectionName);
        Mono.from(collection.drop()).block();
        Mono.from(db.createCollection(collectionName, getCreateCollectionOptions())).block();
        collection.createIndex(new BasicDBObject("firstname", -1));
        collection.createIndex(new BasicDBObject("lastname", -1));
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) Document(org.bson.Document) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

Example 5 with MongoDatabase

use of com.mongodb.reactivestreams.client.MongoDatabase in project spring-data-mongodb by spring-projects.

the class ReactiveQuerydslMongoPredicateExecutorTests method translatesExceptionsCorrectly.

// DATAMONGO-2182, DATAMONGO-2265
@Test
public void translatesExceptionsCorrectly() {
    ReactiveMongoOperations ops = new ReactiveMongoTemplate(dbFactory) {

        @Override
        protected Mono<MongoDatabase> doGetDatabase() {
            return Mono.error(new MongoException(18, "Authentication Failed"));
        }
    };
    ReactiveMongoRepositoryFactory factory = new ReactiveMongoRepositoryFactory(ops);
    MongoEntityInformation<Person, String> entityInformation = factory.getEntityInformation(Person.class);
    repository = new ReactiveQuerydslMongoPredicateExecutor<>(entityInformation, ops);
    // 
    repository.findOne(person.firstname.contains("batman")).as(// 
    StepVerifier::create).expectError(// 
    PermissionDeniedDataAccessException.class).verify();
}
Also used : ReactiveMongoTemplate(org.springframework.data.mongodb.core.ReactiveMongoTemplate) MongoException(com.mongodb.MongoException) ReactiveMongoOperations(org.springframework.data.mongodb.core.ReactiveMongoOperations) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) StepVerifier(reactor.test.StepVerifier) Person(org.springframework.data.mongodb.repository.Person) QPerson(org.springframework.data.mongodb.repository.QPerson) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Test(org.junit.Test)

Aggregations

MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)7 MongoClient (com.mongodb.reactivestreams.client.MongoClient)4 Document (org.bson.Document)4 OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)3 MongoException (com.mongodb.MongoException)2 DeleteResult (com.mongodb.client.result.DeleteResult)2 InsertManyResult (com.mongodb.client.result.InsertManyResult)2 InsertOneResult (com.mongodb.client.result.InsertOneResult)2 UpdateResult (com.mongodb.client.result.UpdateResult)2 MongoClients (com.mongodb.reactivestreams.client.MongoClients)2 Test (org.junit.Test)2 BasicDBObject (com.mongodb.BasicDBObject)1 TIMEOUT_DURATION (com.mongodb.ClusterFixture.TIMEOUT_DURATION)1 ClusterFixture.getDefaultDatabaseName (com.mongodb.ClusterFixture.getDefaultDatabaseName)1 ClusterFixture.isDiscoverableReplicaSet (com.mongodb.ClusterFixture.isDiscoverableReplicaSet)1 ClusterFixture.serverVersionAtLeast (com.mongodb.ClusterFixture.serverVersionAtLeast)1 MongoClientSettings (com.mongodb.MongoClientSettings)1 MongoNamespace (com.mongodb.MongoNamespace)1 MongoNotPrimaryException (com.mongodb.MongoNotPrimaryException)1 WriteConcern (com.mongodb.WriteConcern)1