Search in sources :

Example 1 with OperationSubscriber

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

the class ClientSideEncryptionBypassAutoEncryptionTest method shouldAutoDecryptManuallyEncryptedData.

@Test
public void shouldAutoDecryptManuallyEncryptedData() {
    String fieldValue = "123456789";
    ObservableSubscriber<BsonBinary> binarySubscriber = new OperationSubscriber<>();
    clientEncryption.createDataKey("local", new DataKeyOptions()).subscribe(binarySubscriber);
    BsonBinary dataKeyId = binarySubscriber.get().get(0);
    binarySubscriber = new OperationSubscriber<>();
    clientEncryption.encrypt(new BsonString(fieldValue), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId)).subscribe(binarySubscriber);
    BsonBinary encryptedFieldValue = binarySubscriber.get().get(0);
    MongoCollection<Document> collection = clientEncrypted.getDatabase(Fixture.getDefaultDatabaseName()).getCollection("test");
    ObservableSubscriber<InsertOneResult> insertSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertSubscriber);
    insertSubscriber.await();
    ObservableSubscriber<Document> resultSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(resultSubscriber);
    assertEquals(fieldValue, resultSubscriber.get().get(0).getString("encryptedField"));
}
Also used : BsonBinary(org.bson.BsonBinary) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonString(org.bson.BsonString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) InsertOneResult(com.mongodb.client.result.InsertOneResult) Test(org.junit.Test)

Example 2 with OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber 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 OperationSubscriber

use of reactivestreams.helpers.SubscriberHelpers.OperationSubscriber 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 OperationSubscriber

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

the class ClientSideEncryptionAutoEncryptionSettingsTour 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.
 *
 * @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";
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    ObservableSubscriber<BsonBinary> dataKeySubscriber = new OperationSubscriber<>();
    clientEncryption.createDataKey("local", new DataKeyOptions()).subscribe(dataKeySubscriber);
    dataKeySubscriber.await();
    String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeySubscriber.getReceived().get(0).getData());
    final String dbName = "test";
    final String collName = "coll";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).schemaMap(new HashMap<String, BsonDocument>() {

        {
            put(dbName + "." + collName, // Need a schema that references the new data key
            BsonDocument.parse("{" + "  properties: {" + "    encryptedField: {" + "      encrypt: {" + "        keyId: [{" + "          \"$binary\": {" + "            \"base64\": \"" + base64DataKeyId + "\"," + "            \"subType\": \"04\"" + "          }" + "        }]," + "        bsonType: \"string\"," + "        algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" + "      }" + "    }" + "  }," + "  \"bsonType\": \"object\"" + "}"));
        }
    }).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) ClientEncryption(com.mongodb.reactivestreams.client.vault.ClientEncryption) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) InsertOneResult(com.mongodb.client.result.InsertOneResult) BsonBinary(org.bson.BsonBinary) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with OperationSubscriber

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

the class ClientSideEncryptionExplicitEncryptionOnlyTour 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().autoEncryptionSettings(AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).bypassAutoEncryption(true).build()).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());
    // 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)

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