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"));
}
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();
}
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");
}
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();
}
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();
}
Aggregations