use of com.mongodb.ServerAddress in project java-design-patterns by iluwatar.
the class MongoDb method connect.
/**
* Connect to Db. Check th connection
*/
@Override
public void connect() {
MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_USER, DATABASE_NAME, MONGO_PASSWORD.toCharArray());
MongoClientOptions options = MongoClientOptions.builder().build();
client = new MongoClient(new ServerAddress(), List.of(mongoCredential), options);
db = client.getDatabase(DATABASE_NAME);
}
use of com.mongodb.ServerAddress in project cas by apereo.
the class MongoDbConnectionFactory method buildMongoDbClient.
/**
* Build mongo db client.
*
* @param mongo the mongo
* @return the mongo client
*/
public MongoClient buildMongoDbClient(final BaseMongoDbProperties mongo) {
val settingsBuilder = MongoClientSettings.builder();
if (StringUtils.isNotBlank(mongo.getClientUri())) {
LOGGER.debug("Using MongoDb client URI [{}] to connect to MongoDb instance", mongo.getClientUri());
settingsBuilder.applyConnectionString(new ConnectionString(mongo.getClientUri()));
} else {
val serverAddresses = mongo.getHost().split(",");
if (serverAddresses.length == 0) {
throw new BeanCreationException("Unable to build a MongoDb client without any hosts/servers defined");
}
val servers = new ArrayList<ServerAddress>(0);
if (serverAddresses.length > 1) {
LOGGER.debug("Multiple MongoDb server addresses are defined. Ignoring port [{}], " + "assuming ports are defined as part of the address", mongo.getPort());
Arrays.stream(serverAddresses).filter(StringUtils::isNotBlank).map(ServerAddress::new).forEach(servers::add);
} else {
val port = mongo.getPort() > 0 ? mongo.getPort() : DEFAULT_PORT;
LOGGER.debug("Found single MongoDb server address [{}] using port [{}]", mongo.getHost(), port);
val addr = new ServerAddress(mongo.getHost(), port);
servers.add(addr);
}
settingsBuilder.applyToClusterSettings(builder -> builder.hosts(servers));
val credential = buildMongoCredential(mongo);
settingsBuilder.credential(credential).writeConcern(WriteConcern.valueOf(mongo.getWriteConcern())).codecRegistry(CodecRegistries.fromRegistries(CodecRegistries.fromProviders(new BaseConverters.ZonedDateTimeCodecProvider()), MongoClientSettings.getDefaultCodecRegistry())).readConcern(new ReadConcern(ReadConcernLevel.valueOf(mongo.getReadConcern()))).applyToConnectionPoolSettings(builder -> {
val poolConfig = mongo.getPool();
val pool = ConnectionPoolSettings.builder().maxConnectionLifeTime(Beans.newDuration(poolConfig.getLifeTime()).toMillis(), TimeUnit.MILLISECONDS).maxConnectionIdleTime(Beans.newDuration(poolConfig.getIdleTime()).toMillis(), TimeUnit.MILLISECONDS).maxSize(poolConfig.getMaxSize()).minSize(poolConfig.getMinSize()).maxWaitTime(Beans.newDuration(poolConfig.getMaxWaitTime()).toMillis(), TimeUnit.MILLISECONDS).build();
builder.applySettings(pool);
}).applyToSocketSettings(builder -> {
val socket = SocketSettings.builder().connectTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).readTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
builder.applySettings(socket);
}).applyToSslSettings(builder -> {
val ssl = SslSettings.builder().enabled(mongo.isSslEnabled()).context(this.sslContext).build();
builder.applySettings(ssl);
}).applyToServerSettings(builder -> {
val server = ServerSettings.builder().heartbeatFrequency((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
builder.applySettings(server);
}).retryWrites(mongo.isRetryWrites());
}
return MongoClients.create(settingsBuilder.build());
}
use of com.mongodb.ServerAddress in project spring-data-mongodb by spring-projects.
the class MongoClientFactoryBean method computeClientSetting.
/**
* Create {@link MongoClientSettings} based on configuration and priority (lower is better).
* <ol>
* <li>{@link MongoClientFactoryBean#mongoClientSettings}</li>
* <li>{@link MongoClientFactoryBean#connectionString}</li>
* <li>default {@link MongoClientSettings}</li>
* </ol>
*
* @since 3.0
*/
protected MongoClientSettings computeClientSetting() {
if (connectionString != null && (StringUtils.hasText(host) || port != null)) {
throw new IllegalStateException("ConnectionString and host/port configuration exclude one another!");
}
ConnectionString connectionString = this.connectionString != null ? this.connectionString : new ConnectionString(String.format("mongodb://%s:%s", getOrDefault(host, ServerAddress.defaultHost()), getOrDefault(port, "" + ServerAddress.defaultPort())));
Builder builder = MongoClientSettings.builder().applyConnectionString(connectionString);
builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
if (mongoClientSettings != null) {
MongoClientSettings defaultSettings = MongoClientSettings.builder().build();
SslSettings sslSettings = mongoClientSettings.getSslSettings();
ClusterSettings clusterSettings = mongoClientSettings.getClusterSettings();
ConnectionPoolSettings connectionPoolSettings = mongoClientSettings.getConnectionPoolSettings();
SocketSettings socketSettings = mongoClientSettings.getSocketSettings();
ServerSettings serverSettings = mongoClientSettings.getServerSettings();
builder = //
builder.applicationName(computeSettingsValue(defaultSettings.getApplicationName(), mongoClientSettings.getApplicationName(), //
connectionString.getApplicationName())).applyToSslSettings(settings -> {
applySettings(settings::enabled, computeSettingsValue(SslSettings::isEnabled, defaultSettings.getSslSettings(), sslSettings, connectionString.getSslEnabled()));
applySettings(settings::invalidHostNameAllowed, (computeSettingsValue(SslSettings::isInvalidHostNameAllowed, defaultSettings.getSslSettings(), sslSettings, connectionString.getSslInvalidHostnameAllowed())));
settings.context(sslSettings.getContext());
}).applyToClusterSettings(settings -> {
applySettings(settings::hosts, computeSettingsValue(ClusterSettings::getHosts, defaultSettings.getClusterSettings(), clusterSettings, connectionString.getHosts().stream().map(ServerAddress::new).collect(Collectors.toList())));
applySettings(settings::requiredReplicaSetName, computeSettingsValue(ClusterSettings::getRequiredReplicaSetName, defaultSettings.getClusterSettings(), clusterSettings, connectionString.getRequiredReplicaSetName()));
applySettings(settings::srvHost, computeSettingsValue(ClusterSettings::getSrvHost, defaultSettings.getClusterSettings(), clusterSettings, null));
applySettings(settings::mode, computeSettingsValue(ClusterSettings::getMode, defaultSettings.getClusterSettings(), clusterSettings, null));
applySettings(it -> settings.localThreshold(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ClusterSettings it) -> it.getLocalThreshold(TimeUnit.MILLISECONDS), defaultSettings.getClusterSettings(), clusterSettings, connectionString.getLocalThreshold()));
applySettings(settings::requiredClusterType, computeSettingsValue(ClusterSettings::getRequiredClusterType, defaultSettings.getClusterSettings(), clusterSettings, null));
applySettings(it -> settings.serverSelectionTimeout(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ClusterSettings it) -> it.getServerSelectionTimeout(TimeUnit.MILLISECONDS), defaultSettings.getClusterSettings(), clusterSettings, connectionString.getServerSelectionTimeout()));
applySettings(settings::serverSelector, computeSettingsValue(ClusterSettings::getServerSelector, defaultSettings.getClusterSettings(), clusterSettings, null));
List<ClusterListener> clusterListeners = computeSettingsValue(ClusterSettings::getClusterListeners, defaultSettings.getClusterSettings(), clusterSettings, null);
if (clusterListeners != null) {
clusterListeners.forEach(settings::addClusterListener);
}
}).applyToConnectionPoolSettings(settings -> {
applySettings(it -> settings.maintenanceFrequency(it, TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaintenanceFrequency(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, null));
applySettings(it -> settings.maxConnectionIdleTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxConnectionIdleTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionIdleTime()));
applySettings(it -> settings.maxConnectionLifeTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxConnectionLifeTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionLifeTime()));
applySettings(it -> settings.maxWaitTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxWaitTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxWaitTime()));
applySettings(it -> settings.maintenanceInitialDelay(it, TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaintenanceInitialDelay(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, null));
applySettings(settings::minSize, computeSettingsValue(ConnectionPoolSettings::getMinSize, defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMinConnectionPoolSize()));
applySettings(settings::maxSize, computeSettingsValue(ConnectionPoolSettings::getMaxSize, defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionPoolSize()));
}).applyToSocketSettings(settings -> {
applySettings(it -> settings.connectTimeout(it, TimeUnit.MILLISECONDS), computeSettingsValue((SocketSettings it) -> it.getConnectTimeout(TimeUnit.MILLISECONDS), defaultSettings.getSocketSettings(), socketSettings, connectionString.getConnectTimeout()));
applySettings(it -> settings.readTimeout(it, TimeUnit.MILLISECONDS), computeSettingsValue((SocketSettings it) -> it.getReadTimeout(TimeUnit.MILLISECONDS), defaultSettings.getSocketSettings(), socketSettings, connectionString.getSocketTimeout()));
applySettings(settings::receiveBufferSize, computeSettingsValue(SocketSettings::getReceiveBufferSize, defaultSettings.getSocketSettings(), socketSettings, null));
applySettings(settings::sendBufferSize, computeSettingsValue(SocketSettings::getSendBufferSize, defaultSettings.getSocketSettings(), socketSettings, null));
}).applyToServerSettings(settings -> {
applySettings(it -> settings.minHeartbeatFrequency(it.intValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ServerSettings it) -> it.getMinHeartbeatFrequency(TimeUnit.MILLISECONDS), defaultSettings.getServerSettings(), serverSettings, null));
applySettings(it -> settings.heartbeatFrequency(it.intValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ServerSettings it) -> it.getHeartbeatFrequency(TimeUnit.MILLISECONDS), defaultSettings.getServerSettings(), serverSettings, connectionString.getHeartbeatFrequency()));
settings.applySettings(serverSettings);
}).autoEncryptionSettings(//
mongoClientSettings.getAutoEncryptionSettings()).codecRegistry(//
mongoClientSettings.getCodecRegistry());
applySettings(builder::readConcern, computeSettingsValue(defaultSettings.getReadConcern(), mongoClientSettings.getReadConcern(), connectionString.getReadConcern()));
applySettings(builder::writeConcern, computeSettingsValue(defaultSettings.getWriteConcern(), mongoClientSettings.getWriteConcern(), connectionString.getWriteConcern()));
applySettings(builder::readPreference, computeSettingsValue(defaultSettings.getReadPreference(), mongoClientSettings.getReadPreference(), connectionString.getReadPreference()));
applySettings(builder::retryReads, computeSettingsValue(defaultSettings.getRetryReads(), mongoClientSettings.getRetryReads(), connectionString.getRetryReads()));
applySettings(builder::retryWrites, computeSettingsValue(defaultSettings.getRetryWrites(), mongoClientSettings.getRetryWrites(), connectionString.getRetryWritesValue()));
applySettings(builder::uuidRepresentation, computeSettingsValue(null, mongoClientSettings.getUuidRepresentation(), UuidRepresentation.JAVA_LEGACY));
}
if (!CollectionUtils.isEmpty(credential)) {
builder = builder.credential(credential.iterator().next());
}
if (StringUtils.hasText(replicaSet)) {
builder.applyToClusterSettings((settings) -> {
settings.requiredReplicaSetName(replicaSet);
});
}
return builder.build();
}
use of com.mongodb.ServerAddress in project spring-data-mongodb by spring-projects.
the class DefaultBulkOperationsUnitTests method translateMongoBulkOperationExceptionWithWriteConcernError.
// DATAMONGO-2285
@Test
public void translateMongoBulkOperationExceptionWithWriteConcernError() {
when(collection.bulkWrite(anyList(), any(BulkWriteOptions.class))).thenThrow(new MongoBulkWriteException(null, Collections.emptyList(), new WriteConcernError(42, "codename", "writeconcern error happened", new BsonDocument()), new ServerAddress()));
assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> ops.insert(new SomeDomainType()).execute());
}
use of com.mongodb.ServerAddress in project spring-data-mongodb by spring-projects.
the class MongoClientParserIntegrationTests method createsMongoClientWithDefaultsCorrectly.
// DATAMONGO-1158
@Test
public void createsMongoClientWithDefaultsCorrectly() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
try (AbstractApplicationContext context = new GenericApplicationContext(factory)) {
context.refresh();
MongoClient client = context.getBean("mongoClient", MongoClient.class);
assertThat(client.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
}
}
Aggregations