use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.
the class ClientSideEncryptionCorpusTest method setUp.
@Before
public void setUp() throws IOException, URISyntaxException {
assumeTrue(serverVersionAtLeast(4, 2));
assumeTrue("Corpus tests disabled", hasEncryptionTestsEnabled());
MongoClientSettings clientSettings = getMongoClientSettingsBuilder().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).build();
// Step 1: create unencrypted client
client = MongoClients.create(clientSettings);
MongoDatabase db = client.getDatabase("db");
// Step 2: Drop and recreate db.coll with schema
BsonDocument schemaDocument = bsonDocumentFromPath("corpus-schema.json");
db.getCollection("coll").drop();
db.runCommand(new BsonDocument("create", new BsonString("coll")).append("validator", new BsonDocument("$jsonSchema", schemaDocument)));
// Step 3: Drop and create keyvault.datakeys
MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
MongoCollection<BsonDocument> dataKeysCollection = keyvaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
dataKeysCollection.drop();
dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-aws.json"));
dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-azure.json"));
dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-gcp.json"));
dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-kmip.json"));
dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-local.json"));
// Step 4: Configure our objects
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {
{
put("aws", new HashMap<String, Object>() {
{
put("accessKeyId", System.getProperty("org.mongodb.test.awsAccessKeyId"));
put("secretAccessKey", System.getProperty("org.mongodb.test.awsSecretAccessKey"));
}
});
put("azure", new HashMap<String, Object>() {
{
put("tenantId", System.getProperty("org.mongodb.test.azureTenantId"));
put("clientId", System.getProperty("org.mongodb.test.azureClientId"));
put("clientSecret", System.getProperty("org.mongodb.test.azureClientSecret"));
}
});
put("gcp", new HashMap<String, Object>() {
{
put("email", System.getProperty("org.mongodb.test.gcpEmail"));
put("privateKey", System.getProperty("org.mongodb.test.gcpPrivateKey"));
}
});
put("kmip", new HashMap<String, Object>() {
{
put("endpoint", System.getProperty("org.mongodb.test.kmipEndpoint", "localhost:5698"));
}
});
put("local", new HashMap<String, Object>() {
{
put("key", "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
}
});
}
};
HashMap<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
schemaMap.put("db.coll", schemaDocument);
AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders);
if (useLocalSchema) {
autoEncryptionSettingsBuilder.schemaMap(schemaMap);
}
clientSettings = getMongoClientSettingsBuilder().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).autoEncryptionSettings(autoEncryptionSettingsBuilder.build()).build();
autoEncryptingClient = MongoClients.create(clientSettings);
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientSettings()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys").build();
clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.
the class ClientSideEncryptionExternalKeyVaultTest method setUp.
@Before
public void setUp() throws IOException, URISyntaxException {
assumeTrue(serverVersionAtLeast(4, 2));
assumeTrue("Encryption test with external keyVault is disabled", isClientSideEncryptionTest());
/* Step 1: get unencrypted client and recreate keys collection */
client = getMongoClient();
MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
MongoCollection<BsonDocument> datakeys = keyvaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
datakeys.drop();
datakeys.insertOne(bsonDocumentFromPath("external-key.json"));
/* Step 2: create encryption objects. */
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>();
Map<String, Object> localMasterkey = new HashMap<String, Object>();
Map<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
byte[] localMasterkeyBytes = Base64.getDecoder().decode("Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
localMasterkey.put("key", localMasterkeyBytes);
kmsProviders.put("local", localMasterkey);
schemaMap.put("db.coll", bsonDocumentFromPath("external-schema.json"));
AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).schemaMap(schemaMap);
MongoClientSettings externalClientSettings = null;
if (withExternalKeyVault) {
externalClientSettings = getMongoClientSettingsBuilder().credential(MongoCredential.createCredential("fake-user", "admin", "fake-pwd".toCharArray())).build();
autoEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
}
AutoEncryptionSettings autoEncryptionSettings = autoEncryptionSettingsBuilder.build();
MongoClientSettings clientSettings = getMongoClientSettingsBuilder().autoEncryptionSettings(autoEncryptionSettings).build();
clientEncrypted = MongoClients.create(clientSettings);
ClientEncryptionSettings.Builder clientEncryptionSettingsBuilder = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientSettingsBuilder().build()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys");
if (withExternalKeyVault) {
clientEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
}
ClientEncryptionSettings clientEncryptionSettings = clientEncryptionSettingsBuilder.build();
clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.
the class ServerDiscoveryAndMonitoringProseTests method testHeartbeatFrequency.
@Test
@SuppressWarnings("try")
public void testHeartbeatFrequency() throws InterruptedException {
assumeFalse(isServerlessTest());
CountDownLatch latch = new CountDownLatch(5);
MongoClientSettings settings = getMongoClientSettingsBuilder().applyToServerSettings(new Block<ServerSettings.Builder>() {
@Override
public void apply(final ServerSettings.Builder builder) {
builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
builder.addServerMonitorListener(new ServerMonitorListener() {
@Override
public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
latch.countDown();
}
});
}
}).build();
try (MongoClient ignored = MongoClients.create(settings)) {
assertTrue("Took longer than expected to reach expected number of hearbeats", latch.await(500, TimeUnit.MILLISECONDS));
}
}
use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.
the class ServerDiscoveryAndMonitoringProseTests method testRTTUpdates.
@Test
public void testRTTUpdates() throws InterruptedException {
assumeTrue(isStandalone());
assumeTrue(serverVersionAtLeast(4, 4));
List<ServerDescriptionChangedEvent> events = synchronizedList(new ArrayList<>());
MongoClientSettings settings = getMongoClientSettingsBuilder().applicationName("streamingRttTest").applyToServerSettings(new Block<ServerSettings.Builder>() {
@Override
public void apply(final ServerSettings.Builder builder) {
builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
builder.addServerListener(new ServerListener() {
@Override
public void serverDescriptionChanged(final ServerDescriptionChangedEvent event) {
events.add(event);
}
});
}
}).build();
try (MongoClient client = MongoClients.create(settings)) {
client.getDatabase("admin").runCommand(new Document("ping", 1));
Thread.sleep(250);
assertTrue(events.size() >= 1);
events.forEach(event -> assertTrue(event.getNewDescription().getRoundTripTimeNanos() > 0));
configureFailPoint(parse(format("{" + "configureFailPoint: \"failCommand\"," + "mode: {times: 1000}," + " data: {" + " failCommands: [\"%s\", \"%s\"]," + " blockConnection: true," + " blockTimeMS: 100," + " appName: \"streamingRttTest\"" + " }" + "}", LEGACY_HELLO, HELLO)));
long startTime = System.currentTimeMillis();
while (true) {
long rttMillis = NANOSECONDS.toMillis(client.getClusterDescription().getServerDescriptions().get(0).getRoundTripTimeNanos());
if (rttMillis > 50) {
break;
}
assertFalse(System.currentTimeMillis() - startTime > 1000);
// noinspection BusyWait
Thread.sleep(50);
}
} finally {
disableFailPoint("failCommand");
}
}
use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.
the class ServerDiscoveryAndMonitoringProseTests method testConnectionPoolManagement.
/**
* See
* <a href="https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-tests.rst#connection-pool-management">Connection Pool Management</a>.
*/
@Test
@Ignore
@SuppressWarnings("try")
public void testConnectionPoolManagement() throws InterruptedException {
assumeTrue(serverVersionAtLeast(4, 3));
assumeFalse(isServerlessTest());
BlockingQueue<Object> events = new LinkedBlockingQueue<>();
ServerMonitorListener serverMonitorListener = new ServerMonitorListener() {
@Override
public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
put(events, event);
}
@Override
public void serverHeartbeatFailed(final ServerHeartbeatFailedEvent event) {
put(events, event);
}
};
ConnectionPoolListener connectionPoolListener = new ConnectionPoolListener() {
@Override
public void connectionPoolReady(final ConnectionPoolReadyEvent event) {
put(events, event);
}
@Override
public void connectionPoolCleared(final ConnectionPoolClearedEvent event) {
put(events, event);
}
};
String appName = "SDAMPoolManagementTest";
MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applicationName(appName).applyToClusterSettings(ClusterFixture::setDirectConnection).applyToServerSettings(builder -> builder.heartbeatFrequency(100, TimeUnit.MILLISECONDS).addServerMonitorListener(serverMonitorListener)).applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(connectionPoolListener)).build();
try (MongoClient unused = MongoClients.create(clientSettings)) {
/* Note that ServerHeartbeatSucceededEvent type is sometimes allowed but never required.
* This is because DefaultServerMonitor does not send such events in situations when a server check happens as part
* of a connection handshake. */
assertPoll(events, ServerHeartbeatSucceededEvent.class, singleton(ConnectionPoolReadyEvent.class));
configureFailPoint(new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(2))).append("data", new BsonDocument().append("failCommands", new BsonArray(asList(new BsonString("isMaster"), new BsonString("hello")))).append("errorCode", new BsonInt32(1234)).append("appName", new BsonString(appName))));
assertPoll(events, ServerHeartbeatSucceededEvent.class, new HashSet<>(asList(ServerHeartbeatFailedEvent.class, ConnectionPoolClearedEvent.class)));
assertPoll(events, null, new HashSet<>(asList(ServerHeartbeatSucceededEvent.class, ConnectionPoolReadyEvent.class)));
} finally {
disableFailPoint("failCommand");
}
}
Aggregations