Search in sources :

Example 6 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber in project mongo-java-driver by mongodb.

the class QuickTour 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]);
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    // get a handle to the "test" collection
    final MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(doc).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // get it (since it's the only one in there since we dropped the rest earlier on)
    ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(documents).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // find first
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // lets get all the documents in the collection and print them out
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Query Filters
    // now use a query to get 1 document out
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(eq("i", 71)).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // now use a range query to get a larger subset
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(gt("i", 50)).subscribe(documentSubscriber);
    successSubscriber.await();
    // range query with multiple constraints
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(and(gt("i", 50), lte("i", 100))).subscribe(documentSubscriber);
    successSubscriber.await();
    // Sorting
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(exists("i")).sort(descending("i")).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Projection
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().projection(excludeId()).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Aggregation
    documentSubscriber = new PrintDocumentSubscriber();
    collection.aggregate(asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))).subscribe(documentSubscriber);
    documentSubscriber.await();
    documentSubscriber = new PrintDocumentSubscriber();
    collection.aggregate(singletonList(group(null, sum("total", "$i")))).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Update One
    ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
    collection.updateOne(eq("i", 10), set("i", 110)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Update Many
    updateSubscriber = new OperationSubscriber<>();
    collection.updateMany(lt("i", 100), inc("i", 100)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Delete One
    ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
    collection.deleteOne(eq("i", 110)).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Delete Many
    deleteSubscriber = new OperationSubscriber<>();
    collection.deleteMany(gte("i", 100)).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Create Index
    OperationSubscriber<String> createIndexSubscriber = new PrintSubscriber<>("Create Index Result: %s");
    collection.createIndex(new Document("i", 1)).subscribe(createIndexSubscriber);
    createIndexSubscriber.await();
    // Clean up
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : PrintDocumentSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) ArrayList(java.util.ArrayList) Document(org.bson.Document) InsertManyResult(com.mongodb.client.result.InsertManyResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient) PrintSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintSubscriber) InsertOneResult(com.mongodb.client.result.InsertOneResult) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

Example 7 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExplicitEncryptionAndDecryptionTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // Explicitly decrypt the field
    System.out.println(clientEncryption.decrypt(new BsonBinary(doc.get("encryptedField", Binary.class).getData())));
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber in project mongo-java-driver by mongodb.

the class ClientSideEncryptionSimpleTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    String keyVaultNamespace = "admin.datakeys";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(autoEncryptionSettings).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", "123456789")).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : PrintDocumentSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber) HashMap(java.util.HashMap) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) Document(org.bson.Document) MongoClient(com.mongodb.reactivestreams.client.MongoClient) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) InsertOneResult(com.mongodb.client.result.InsertOneResult) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber in project mongo-java-driver by mongodb.

the class DocumentationSamples method testQueryingAtTheTopLevel.

@Test
public void testQueryingAtTheTopLevel() {
    // Start Example 6
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(asList(Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"), Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"), Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"), Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"), Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }"))).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // End Example 6
    ObservableSubscriber<Long> countSubscriber = new OperationSubscriber<>();
    collection.countDocuments().subscribe(countSubscriber);
    countSubscriber.await();
    // Start Example 7
    FindPublisher<Document> findPublisher = collection.find(new Document());
    // End Example 7
    ObservableSubscriber<Document> findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 8
    findPublisher = collection.find();
    // End Example 8
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 9
    findPublisher = collection.find(eq("status", "D"));
    // End Example 9
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 10
    findPublisher = collection.find(in("status", "A", "D"));
    // End Example 10
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 11
    findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));
    // End Example 11
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 12
    findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));
    // End Example 12
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 13
    findPublisher = collection.find(and(eq("status", "A"), or(lt("qty", 30), regex("item", "^p"))));
    // End Example 13
    findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) Document(org.bson.Document) InsertManyResult(com.mongodb.client.result.InsertManyResult) Test(org.junit.Test)

Example 10 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber in project mongo-java-driver by mongodb.

the class DocumentationSamples method testInsert.

@Test
public void testInsert() {
    // Start Example 1
    Document canvas = new Document("item", "canvas").append("qty", 100).append("tags", singletonList("cotton"));
    Document size = new Document("h", 28).append("w", 35.5).append("uom", "cm");
    canvas.put("size", size);
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(canvas).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // End Example 1
    // Start Example 2
    FindPublisher<Document> findPublisher = collection.find(eq("item", "canvas"));
    // End Example 2
    ObservableSubscriber<Document> findSubscriber = new OperationSubscriber<>();
    findPublisher.subscribe(findSubscriber);
    findSubscriber.await();
    // Start Example 3
    Document journal = new Document("item", "journal").append("qty", 25).append("tags", asList("blank", "red"));
    Document journalSize = new Document("h", 14).append("w", 21).append("uom", "cm");
    journal.put("size", journalSize);
    Document mat = new Document("item", "mat").append("qty", 85).append("tags", singletonList("gray"));
    Document matSize = new Document("h", 27.9).append("w", 35.5).append("uom", "cm");
    mat.put("size", matSize);
    Document mousePad = new Document("item", "mousePad").append("qty", 25).append("tags", asList("gel", "blue"));
    Document mousePadSize = new Document("h", 19).append("w", 22.85).append("uom", "cm");
    mousePad.put("size", mousePadSize);
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(asList(journal, mat, mousePad)).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // End Example 3
    ObservableSubscriber<Long> countSubscriber = new OperationSubscriber<>();
    collection.countDocuments().subscribe(countSubscriber);
    countSubscriber.await();
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) Document(org.bson.Document) InsertOneResult(com.mongodb.client.result.InsertOneResult) InsertManyResult(com.mongodb.client.result.InsertManyResult) Test(org.junit.Test)

Aggregations

OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)11 Document (org.bson.Document)10 InsertOneResult (com.mongodb.client.result.InsertOneResult)9 MongoClient (com.mongodb.reactivestreams.client.MongoClient)7 MongoClientSettings (com.mongodb.MongoClientSettings)4 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)4 InsertManyResult (com.mongodb.client.result.InsertManyResult)4 SecureRandom (java.security.SecureRandom)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 BsonBinary (org.bson.BsonBinary)4 Test (org.junit.Test)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 ConnectionString (com.mongodb.ConnectionString)3 EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)3 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)3 BsonString (org.bson.BsonString)3 PrintDocumentSubscriber (reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber)3 AutoEncryptionSettings (com.mongodb.AutoEncryptionSettings)2 MongoNamespace (com.mongodb.MongoNamespace)2