use of com.mongodb.client.MongoClient in project mongo-java-driver by mongodb.
the class Entities method initClient.
private void initClient(final BsonDocument entity, final String id, final Function<MongoClientSettings, MongoClient> mongoClientSupplier, final boolean waitForPoolAsyncWorkManagerStart) {
if (!SUPPORTED_CLIENT_ENTITY_OPTIONS.containsAll(entity.keySet())) {
throw new UnsupportedOperationException("Client entity contains unsupported options: " + entity.keySet() + ". Supported options are " + SUPPORTED_CLIENT_ENTITY_OPTIONS);
}
MongoClientSettings.Builder clientSettingsBuilder;
if (entity.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue() && (isSharded() || isLoadBalanced())) {
assumeTrue("Multiple mongos connection string not available for sharded cluster", !isSharded() || getMultiMongosConnectionString() != null);
assumeTrue("Multiple mongos connection string not available for load-balanced cluster", !isLoadBalanced() || getMultiMongosConnectionString() != null);
clientSettingsBuilder = getMultiMongosMongoClientSettingsBuilder();
} else {
clientSettingsBuilder = getMongoClientSettingsBuilder();
}
if (entity.containsKey("observeEvents")) {
List<String> ignoreCommandMonitoringEvents = entity.getArray("ignoreCommandMonitoringEvents", new BsonArray()).stream().map(type -> type.asString().getValue()).collect(Collectors.toList());
ignoreCommandMonitoringEvents.add("configureFailPoint");
TestCommandListener testCommandListener = new TestCommandListener(entity.getArray("observeEvents").stream().map(type -> type.asString().getValue()).collect(Collectors.toList()), ignoreCommandMonitoringEvents, entity.getBoolean("observeSensitiveCommands", BsonBoolean.FALSE).getValue());
clientSettingsBuilder.addCommandListener(testCommandListener);
putEntity(id + "-command-listener", testCommandListener, clientCommandListeners);
TestConnectionPoolListener testConnectionPoolListener = new TestConnectionPoolListener(entity.getArray("observeEvents").stream().map(type -> type.asString().getValue()).collect(Collectors.toList()));
clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(testConnectionPoolListener));
putEntity(id + "-connection-pool-listener", testConnectionPoolListener, clientConnectionPoolListeners);
} else {
// Regardless of whether events are observed, we still need to track some info about the pool in order to implement
// the assertNumberConnectionsCheckedOut operation
TestConnectionPoolListener testConnectionPoolListener = new TestConnectionPoolListener();
clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(testConnectionPoolListener));
putEntity(id + "-connection-pool-listener", testConnectionPoolListener, clientConnectionPoolListeners);
}
if (entity.containsKey("storeEventsAsEntities")) {
BsonArray storeEventsAsEntitiesArray = entity.getArray("storeEventsAsEntities");
for (BsonValue eventValue : storeEventsAsEntitiesArray) {
BsonDocument eventDocument = eventValue.asDocument();
String key = eventDocument.getString("id").getValue();
BsonArray eventList = eventDocument.getArray("events");
List<BsonDocument> eventDocumentList = synchronizedList(new ArrayList<>());
putEntity(key, eventDocumentList, eventsMap);
if (eventList.stream().map(value -> value.asString().getValue()).anyMatch(value -> value.startsWith("Command"))) {
clientSettingsBuilder.addCommandListener(new EntityCommandListener(eventList.stream().map(value -> value.asString().getValue()).collect(Collectors.toSet()), eventDocumentList));
}
if (eventList.stream().map(value -> value.asString().getValue()).anyMatch(value -> value.startsWith("Pool") || value.startsWith("Connection"))) {
clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new EntityConnectionPoolListener(eventList.stream().map(value -> value.asString().getValue()).collect(Collectors.toSet()), eventDocumentList)));
}
}
}
clientSettingsBuilder.applyToServerSettings(builder -> {
builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
builder.minHeartbeatFrequency(50, TimeUnit.MILLISECONDS);
});
if (entity.containsKey("uriOptions")) {
entity.getDocument("uriOptions").forEach((key, value) -> {
switch(key) {
case "retryReads":
clientSettingsBuilder.retryReads(value.asBoolean().getValue());
break;
case "retryWrites":
clientSettingsBuilder.retryWrites(value.asBoolean().getValue());
break;
case "readConcernLevel":
clientSettingsBuilder.readConcern(new ReadConcern(ReadConcernLevel.fromString(value.asString().getValue())));
break;
case "w":
clientSettingsBuilder.writeConcern(new WriteConcern(value.asInt32().intValue()));
break;
case "maxPoolSize":
clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.maxSize(value.asNumber().intValue()));
break;
case "waitQueueTimeoutMS":
clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.maxWaitTime(value.asNumber().longValue(), TimeUnit.MILLISECONDS));
break;
case "loadBalanced":
if (value.asBoolean().getValue()) {
clientSettingsBuilder.applyToClusterSettings(builder -> builder.mode(ClusterConnectionMode.LOAD_BALANCED));
}
break;
case "appname":
clientSettingsBuilder.applicationName(value.asString().getValue());
break;
default:
throw new UnsupportedOperationException("Unsupported uri option: " + key);
}
});
}
if (entity.containsKey("serverApi")) {
BsonDocument serverApiDocument = entity.getDocument("serverApi");
String apiVersion = serverApiDocument.getString("version").getValue();
ServerApi.Builder serverApiBuilder = ServerApi.builder().version(ServerApiVersion.findByValue(apiVersion));
if (serverApiDocument.containsKey("deprecationErrors")) {
serverApiBuilder.deprecationErrors(serverApiDocument.getBoolean("deprecationErrors").getValue());
}
if (serverApiDocument.containsKey("strict")) {
serverApiBuilder.strict(serverApiDocument.getBoolean("strict").getValue());
}
clientSettingsBuilder.serverApi(serverApiBuilder.build());
}
putEntity(id, mongoClientSupplier.apply(clientSettingsBuilder.build()), clients);
if (waitForPoolAsyncWorkManagerStart) {
waitForPoolAsyncWorkManagerStart();
}
}
use of com.mongodb.client.MongoClient in project mongo-java-driver by mongodb.
the class Entities method initSession.
private void initSession(final BsonDocument entity, final String id) {
MongoClient client = clients.get(entity.getString("client").getValue());
ClientSessionOptions.Builder optionsBuilder = ClientSessionOptions.builder();
if (entity.containsKey("sessionOptions")) {
for (Map.Entry<String, BsonValue> entry : entity.getDocument("sessionOptions").entrySet()) {
switch(entry.getKey()) {
case "defaultTransactionOptions":
optionsBuilder.defaultTransactionOptions(getTransactionOptions(entry.getValue().asDocument()));
break;
case "snapshot":
optionsBuilder.snapshot(entry.getValue().asBoolean().getValue());
break;
default:
throw new UnsupportedOperationException("Unsupported session option: " + entry.getKey());
}
}
}
ClientSession session = client.startSession(optionsBuilder.build());
putEntity(id, session, sessions);
putEntity(id + "-identifier", session.getServerSession().getIdentifier(), sessionIdentifiers);
}
use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.
the class MongoDbFactoryParserIntegrationTests method testWriteConcern.
// DATAMONGO-2199
@Test
public void testWriteConcern() throws Exception {
try (MongoClient client = MongoTestUtils.client()) {
SimpleMongoClientDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(client, "database");
dbFactory.setWriteConcern(WriteConcern.ACKNOWLEDGED);
dbFactory.getMongoDatabase();
assertThat(ReflectionTestUtils.getField(dbFactory, "writeConcern")).isEqualTo(WriteConcern.ACKNOWLEDGED);
}
}
use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.
the class MongoNamespaceTests method testThirdMongoDbFactory.
// DATAMONGO-789
@Test
public void testThirdMongoDbFactory() {
assertThat(ctx.containsBean("thirdMongoDbFactory")).isTrue();
MongoDatabaseFactory dbf = (MongoDatabaseFactory) ctx.getBean("thirdMongoDbFactory");
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
assertThat(mongo.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
}
use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.
the class MongoPersistentEntityIndexCreatorIntegrationTests method createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails.
// DATAMONGO-1125
@Test
public void createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails() {
expectedException.expect(DataIntegrityViolationException.class);
expectedException.expectMessage("collection 'datamongo-1125'");
expectedException.expectMessage("dalinar.kohlin");
expectedException.expectMessage("lastname");
expectedException.expectCause(IsInstanceOf.<Throwable>instanceOf(MongoCommandException.class));
try (MongoClient client = MongoTestUtils.client()) {
MongoTemplate mongoTemplate = new MongoTemplate(client, "issue");
MongoPersistentEntityIndexCreator indexCreator = new MongoPersistentEntityIndexCreator(new MongoMappingContext(), mongoTemplate);
indexCreator.createIndex(new IndexDefinitionHolder("dalinar.kohlin", new Index().named("stormlight").on("lastname", Direction.ASC).unique(), "datamongo-1125"));
indexCreator.createIndex(new IndexDefinitionHolder("dalinar.kohlin", new Index().named("stormlight").on("lastname", Direction.ASC).sparse(), "datamongo-1125"));
}
}
Aggregations