Search in sources :

Example 11 with InsertOneResult

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();
}
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 12 with InsertOneResult

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();
}
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 13 with InsertOneResult

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

Example 14 with InsertOneResult

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
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) InsertOneResult(com.mongodb.client.result.InsertOneResult) Document(org.bson.Document) SimpleDateFormat(java.text.SimpleDateFormat) Test(org.junit.Test)

Example 15 with InsertOneResult

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;
}
Also used : Document(org.bson.Document) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Mock(org.mockito.Mock) MongoClients(com.mongodb.reactivestreams.client.MongoClients) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) BsonString(org.bson.BsonString) MongoClient(com.mongodb.reactivestreams.client.MongoClient) BsonDocument(org.bson.BsonDocument) BsonValue(org.bson.BsonValue) TIMEOUT_DURATION(com.mongodb.ClusterFixture.TIMEOUT_DURATION) Fixture.getMongoClientBuilderFromConnectionString(com.mongodb.reactivestreams.client.Fixture.getMongoClientBuilderFromConnectionString) Collections.singletonList(java.util.Collections.singletonList) Fixture.drop(com.mongodb.reactivestreams.client.Fixture.drop) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BsonTimestamp(org.bson.BsonTimestamp) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Fixture.isReplicaSet(com.mongodb.reactivestreams.client.Fixture.isReplicaSet) Assertions.assertAll(org.junit.jupiter.api.Assertions.assertAll) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) CommandEvent(com.mongodb.event.CommandEvent) TestSubscriber(com.mongodb.reactivestreams.client.TestSubscriber) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) InsertOneResult(com.mongodb.client.result.InsertOneResult) Assertions.assertIterableEquals(org.junit.jupiter.api.Assertions.assertIterableEquals) Collections.emptyList(java.util.Collections.emptyList) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) Fixture.serverVersionAtLeast(com.mongodb.reactivestreams.client.Fixture.serverVersionAtLeast) Mockito.when(org.mockito.Mockito.when) ClusterFixture.getDefaultDatabaseName(com.mongodb.ClusterFixture.getDefaultDatabaseName) Collectors(java.util.stream.Collectors) DisplayName(org.junit.jupiter.api.DisplayName) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) List(java.util.List) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) MongoClientSettings(com.mongodb.MongoClientSettings) BsonInt32(org.bson.BsonInt32) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) Document(org.bson.Document) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) BsonDocument(org.bson.BsonDocument) BsonTimestamp(org.bson.BsonTimestamp) BsonValue(org.bson.BsonValue)

Aggregations

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