use of com.mongodb.client.result.InsertOneResult 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();
}
use of com.mongodb.client.result.InsertOneResult 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();
}
use of com.mongodb.client.result.InsertOneResult 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();
}
use of com.mongodb.client.result.InsertOneResult in project mongo-java-driver by mongodb.
the class InsertPrimer method insertADocument.
@Test
public void insertADocument() throws ParseException {
// @begin: insert-a-document
// @code: start
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
db.getCollection("restaurants").insertOne(new Document("address", new Document().append("street", "2 Avenue").append("zipcode", "10075").append("building", "1480").append("coord", asList(-73.9557413, 40.7720266))).append("borough", "Manhattan").append("cuisine", "Italian").append("grades", asList(new Document().append("date", format.parse("2014-10-01T00:00:00Z")).append("grade", "A").append("score", 11), new Document().append("date", format.parse("2014-01-16T00:00:00Z")).append("grade", "B").append("score", 17))).append("name", "Vella").append("restaurant_id", "41704620")).subscribe(insertOneSubscriber);
insertOneSubscriber.await();
// @code: end
// @post: The method does not return a result
// @end: insert-a-document
}
use of com.mongodb.client.result.InsertOneResult in project mongo-java-driver by mongodb.
the class BatchCursorFluxTest method ensureExists.
/**
* This method ensures that the server considers the specified {@code collection} existing for the purposes of, e.g.,
* {@link MongoCollection#drop()}, instead of replying with
* {@code "errmsg": "ns not found", "code": 26, "codeName": "NamespaceNotFound"}.
*
* @return {@code operationTime} starting at which the {@code collection} is guaranteed to exist.
*/
private static BsonTimestamp ensureExists(final MongoClient client, final MongoCollection<Document> collection) {
BsonValue insertedId = Mono.from(collection.insertOne(Document.parse("{}"))).map(InsertOneResult::getInsertedId).block(TIMEOUT_DURATION);
BsonArray deleteStatements = new BsonArray();
deleteStatements.add(new BsonDocument().append("q", new BsonDocument().append("_id", insertedId)).append("limit", new BsonInt32(1)));
Publisher<Document> deletePublisher = client.getDatabase(collection.getNamespace().getDatabaseName()).runCommand(new BsonDocument().append("delete", new BsonString(collection.getNamespace().getCollectionName())).append("deletes", deleteStatements));
BsonTimestamp operationTime = Mono.from(deletePublisher).map(doc -> doc.get("operationTime", BsonTimestamp.class)).block(TIMEOUT_DURATION);
assertNotNull(operationTime);
return operationTime;
}
Aggregations