Search in sources :

Example 21 with MongoNamespace

use of com.mongodb.MongoNamespace in project mongo-java-driver by mongodb.

the class MongoDatabaseImplTest method testCreateCollection.

@Test
void testCreateCollection() {
    String collectionName = "coll";
    assertAll("createCollection", () -> assertAll("check validation", () -> assertThrows(IllegalArgumentException.class, () -> database.createCollection(null)), () -> assertThrows(IllegalArgumentException.class, () -> database.createCollection(collectionName, null)), () -> assertThrows(IllegalArgumentException.class, () -> database.createCollection(null, collectionName)), () -> assertThrows(IllegalArgumentException.class, () -> database.createCollection(clientSession, collectionName, null))), () -> {
        Publisher<Void> expected = mongoOperationPublisher.createCollection(null, new MongoNamespace(database.getName(), collectionName), new CreateCollectionOptions());
        assertPublisherIsTheSameAs(expected, database.createCollection(collectionName), "Default");
    }, () -> {
        CreateCollectionOptions options = new CreateCollectionOptions().sizeInBytes(500).capped(true);
        Publisher<Void> expected = mongoOperationPublisher.createCollection(null, new MongoNamespace(database.getName(), collectionName), options);
        assertPublisherIsTheSameAs(expected, database.createCollection(collectionName, options), "With options");
    }, () -> {
        Publisher<Void> expected = mongoOperationPublisher.createCollection(clientSession, new MongoNamespace(database.getName(), collectionName), new CreateCollectionOptions());
        assertPublisherIsTheSameAs(expected, database.createCollection(clientSession, collectionName), "With client session");
    }, () -> {
        CreateCollectionOptions options = new CreateCollectionOptions().sizeInBytes(500).capped(true);
        Publisher<Void> expected = mongoOperationPublisher.createCollection(clientSession, new MongoNamespace(database.getName(), collectionName), options);
        assertPublisherIsTheSameAs(expected, database.createCollection(clientSession, collectionName, options), "With client session & options");
    });
}
Also used : CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) MongoNamespace(com.mongodb.MongoNamespace) Test(org.junit.jupiter.api.Test)

Example 22 with MongoNamespace

use of com.mongodb.MongoNamespace in project mongo-java-driver by mongodb.

the class AggregatePublisherImplTest method shouldBuildTheExpectedOperationsForDollarOutWithHintString.

@DisplayName("Should build the expected AggregateOperation for $out with hint string")
@Test
void shouldBuildTheExpectedOperationsForDollarOutWithHintString() {
    String collectionName = "collectionName";
    List<BsonDocument> pipeline = asList(BsonDocument.parse("{'$match': 1}"), BsonDocument.parse(format("{'$out': '%s'}", collectionName)));
    MongoNamespace collectionNamespace = new MongoNamespace(NAMESPACE.getDatabaseName(), collectionName);
    TestOperationExecutor executor = createOperationExecutor(asList(getBatchCursor(), getBatchCursor(), getBatchCursor(), null));
    AggregatePublisher<Document> publisher = new AggregatePublisherImpl<>(null, createMongoOperationPublisher(executor), pipeline, AggregationLevel.COLLECTION);
    AggregateToCollectionOperation expectedOperation = new AggregateToCollectionOperation(NAMESPACE, pipeline, ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED);
    publisher.hintString("x_1");
    expectedOperation.hint(new BsonString("x_1"));
    Flux.from(publisher).blockFirst();
    assertEquals(ReadPreference.primary(), executor.getReadPreference());
    VoidReadOperationThenCursorReadOperation operation = (VoidReadOperationThenCursorReadOperation) executor.getReadOperation();
    assertOperationIsTheSameAs(expectedOperation, operation.getReadOperation());
}
Also used : AggregateToCollectionOperation(com.mongodb.internal.operation.AggregateToCollectionOperation) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonString(org.bson.BsonString) MongoNamespace(com.mongodb.MongoNamespace) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 23 with MongoNamespace

use of com.mongodb.MongoNamespace in project mongo-java-driver by mongodb.

the class AggregatePublisherImplTest method shouldBuildTheExpectedOperationsForDollarMergeString.

@DisplayName("Should build the expected AggregateOperation for $merge string")
@Test
void shouldBuildTheExpectedOperationsForDollarMergeString() {
    String collectionName = "collectionName";
    MongoNamespace collectionNamespace = new MongoNamespace(NAMESPACE.getDatabaseName(), collectionName);
    List<BsonDocument> pipeline = asList(BsonDocument.parse("{'$match': 1}"), BsonDocument.parse(format("{'$merge': '%s'}", collectionName)));
    TestOperationExecutor executor = createOperationExecutor(asList(getBatchCursor(), getBatchCursor(), getBatchCursor(), null));
    AggregatePublisher<Document> publisher = new AggregatePublisherImpl<>(null, createMongoOperationPublisher(executor), pipeline, AggregationLevel.COLLECTION);
    AggregateToCollectionOperation expectedOperation = new AggregateToCollectionOperation(NAMESPACE, pipeline, ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED);
    // default input should be as expected
    Flux.from(publisher).blockFirst();
    VoidReadOperationThenCursorReadOperation operation = (VoidReadOperationThenCursorReadOperation) executor.getReadOperation();
    assertEquals(ReadPreference.primary(), executor.getReadPreference());
    assertOperationIsTheSameAs(expectedOperation, operation.getReadOperation());
    FindOperation<Document> expectedFindOperation = new FindOperation<>(collectionNamespace, getDefaultCodecRegistry().get(Document.class)).filter(new BsonDocument()).batchSize(Integer.MAX_VALUE).retryReads(true);
    assertOperationIsTheSameAs(expectedFindOperation, operation.getCursorReadOperation());
}
Also used : AggregateToCollectionOperation(com.mongodb.internal.operation.AggregateToCollectionOperation) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) MongoNamespace(com.mongodb.MongoNamespace) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 24 with MongoNamespace

use of com.mongodb.MongoNamespace in project mongo-java-driver by mongodb.

the class AggregatePublisherImplTest method shouldBuildTheExpectedOperationsForDollarOut.

@DisplayName("Should build the expected AggregateOperation for $out")
@Test
void shouldBuildTheExpectedOperationsForDollarOut() {
    String collectionName = "collectionName";
    List<BsonDocument> pipeline = asList(BsonDocument.parse("{'$match': 1}"), BsonDocument.parse(format("{'$out': '%s'}", collectionName)));
    MongoNamespace collectionNamespace = new MongoNamespace(NAMESPACE.getDatabaseName(), collectionName);
    TestOperationExecutor executor = createOperationExecutor(asList(getBatchCursor(), getBatchCursor(), getBatchCursor(), null));
    AggregatePublisher<Document> publisher = new AggregatePublisherImpl<>(null, createMongoOperationPublisher(executor), pipeline, AggregationLevel.COLLECTION);
    AggregateToCollectionOperation expectedOperation = new AggregateToCollectionOperation(NAMESPACE, pipeline, ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED);
    // default input should be as expected
    Flux.from(publisher).blockFirst();
    VoidReadOperationThenCursorReadOperation operation = (VoidReadOperationThenCursorReadOperation) executor.getReadOperation();
    assertEquals(ReadPreference.primary(), executor.getReadPreference());
    assertOperationIsTheSameAs(expectedOperation, operation.getReadOperation());
    // Should apply settings
    publisher.allowDiskUse(true).batchSize(// Used in Find
    100).bypassDocumentValidation(true).collation(COLLATION).comment("my comment").hint(BsonDocument.parse("{a: 1}")).maxAwaitTime(20, // Ignored on $out
    SECONDS).maxTime(10, SECONDS);
    expectedOperation.allowDiskUse(true).bypassDocumentValidation(true).collation(COLLATION).comment("my comment").hint(BsonDocument.parse("{a: 1}")).maxTime(10, SECONDS);
    Flux.from(publisher).blockFirst();
    assertEquals(ReadPreference.primary(), executor.getReadPreference());
    operation = (VoidReadOperationThenCursorReadOperation) executor.getReadOperation();
    assertOperationIsTheSameAs(expectedOperation, operation.getReadOperation());
    FindOperation<Document> expectedFindOperation = new FindOperation<>(collectionNamespace, getDefaultCodecRegistry().get(Document.class)).batchSize(100).collation(COLLATION).filter(new BsonDocument()).maxAwaitTime(0, SECONDS).maxTime(0, SECONDS).retryReads(true);
    assertOperationIsTheSameAs(expectedFindOperation, operation.getCursorReadOperation());
    // Should handle database level aggregations
    publisher = new AggregatePublisherImpl<>(null, createMongoOperationPublisher(executor), pipeline, AggregationLevel.DATABASE);
    expectedOperation = new AggregateToCollectionOperation(NAMESPACE, pipeline, ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED);
    Flux.from(publisher).blockFirst();
    operation = (VoidReadOperationThenCursorReadOperation) executor.getReadOperation();
    assertEquals(ReadPreference.primary(), executor.getReadPreference());
    assertOperationIsTheSameAs(expectedOperation, operation.getReadOperation());
    // Should handle toCollection
    publisher = new AggregatePublisherImpl<>(null, createMongoOperationPublisher(executor), pipeline, AggregationLevel.COLLECTION);
    expectedOperation = new AggregateToCollectionOperation(NAMESPACE, pipeline, ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED);
    // default input should be as expected
    Flux.from(publisher.toCollection()).blockFirst();
    assertOperationIsTheSameAs(expectedOperation, executor.getReadOperation());
}
Also used : AggregateToCollectionOperation(com.mongodb.internal.operation.AggregateToCollectionOperation) BsonString(org.bson.BsonString) MongoNamespace(com.mongodb.MongoNamespace) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) BsonDocument(org.bson.BsonDocument) FindOperation(com.mongodb.internal.operation.FindOperation) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 25 with MongoNamespace

use of com.mongodb.MongoNamespace in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExplicitEncryptionAndDecryptionTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @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);
                }
            });
        }
    };
    MongoClientSettings clientSettings = MongoClientSettings.builder().build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    keyVaultCollection.drop();
    // Ensure that two data keys cannot share the same keyAltName.
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames")));
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    // Clear old data
    collection.drop();
    // 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));
    collection.insertOne(new Document("encryptedField", encryptedFieldValue));
    Document doc = collection.find().first();
    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) IndexOptions(com.mongodb.client.model.IndexOptions) BsonBinary(org.bson.BsonBinary) ClientEncryption(com.mongodb.client.vault.ClientEncryption) SecureRandom(java.security.SecureRandom) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

MongoNamespace (com.mongodb.MongoNamespace)55 BsonDocument (org.bson.BsonDocument)34 BsonString (org.bson.BsonString)21 Document (org.bson.Document)20 Before (org.junit.Before)17 MongoClientSettings (com.mongodb.MongoClientSettings)15 BsonValue (org.bson.BsonValue)13 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10 Map (java.util.Map)10 BsonDocumentCodec (org.bson.codecs.BsonDocumentCodec)10 DocumentCodec (org.bson.codecs.DocumentCodec)8 CollectionHelper (com.mongodb.client.test.CollectionHelper)7 Test (org.junit.jupiter.api.Test)7 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)6 ConnectionString (com.mongodb.ConnectionString)6 Test (org.junit.Test)6 IndexOptions (com.mongodb.client.model.IndexOptions)5 AggregateToCollectionOperation (com.mongodb.internal.operation.AggregateToCollectionOperation)5 DisplayName (org.junit.jupiter.api.DisplayName)5