Search in sources :

Example 86 with ServerAddress

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);
}
Also used : MongoClient(com.mongodb.MongoClient) MongoCredential(com.mongodb.MongoCredential) MongoClientOptions(com.mongodb.MongoClientOptions) ServerAddress(com.mongodb.ServerAddress)

Example 87 with ServerAddress

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());
}
Also used : lombok.val(lombok.val) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) Document(org.springframework.data.mongodb.core.mapping.Document) LoggingUtils(org.apereo.cas.util.LoggingUtils) SocketSettings(com.mongodb.connection.SocketSettings) SSLContexts(org.apache.http.ssl.SSLContexts) ReadConcern(com.mongodb.ReadConcern) AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) ClassUtils(org.springframework.util.ClassUtils) PropertyNameFieldNamingStrategy(org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy) MongoClients(com.mongodb.client.MongoClients) Collection(java.util.Collection) Set(java.util.Set) CodecRegistries(org.bson.codecs.configuration.CodecRegistries) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Stream(java.util.stream.Stream) JodaTimeConverters(org.springframework.data.convert.JodaTimeConverters) MongoClientSettings(com.mongodb.MongoClientSettings) IndexDefinition(org.springframework.data.mongodb.core.index.IndexDefinition) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoCredential(com.mongodb.MongoCredential) MongoClient(com.mongodb.client.MongoClient) MongoCollection(com.mongodb.client.MongoCollection) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) FieldNamingStrategy(org.springframework.data.mapping.model.FieldNamingStrategy) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) ServerSettings(com.mongodb.connection.ServerSettings) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) CollectionUtils(org.apereo.cas.util.CollectionUtils) Jsr310Converters(org.springframework.data.convert.Jsr310Converters) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) Converter(org.springframework.core.convert.converter.Converter) Persistent(org.springframework.data.annotation.Persistent) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) lombok.val(lombok.val) TimeUnit(java.util.concurrent.TimeUnit) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) ConnectionString(com.mongodb.ConnectionString) ReadConcernLevel(com.mongodb.ReadConcernLevel) BaseMongoDbProperties(org.apereo.cas.configuration.model.support.mongo.BaseMongoDbProperties) MongoOperations(org.springframework.data.mongodb.core.MongoOperations) DefaultDbRefResolver(org.springframework.data.mongodb.core.convert.DefaultDbRefResolver) WriteConcern(com.mongodb.WriteConcern) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) BeanCreationException(org.springframework.beans.factory.BeanCreationException) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ServerAddress(com.mongodb.ServerAddress) ConnectionString(com.mongodb.ConnectionString) ReadConcern(com.mongodb.ReadConcern)

Example 88 with ServerAddress

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();
}
Also used : ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) Arrays(java.util.Arrays) DataAccessException(org.springframework.dao.DataAccessException) MongoCredential(com.mongodb.MongoCredential) MongoClient(com.mongodb.client.MongoClient) ClusterSettings(com.mongodb.connection.ClusterSettings) Function(java.util.function.Function) ServerSettings(com.mongodb.connection.ServerSettings) AbstractFactoryBean(org.springframework.beans.factory.config.AbstractFactoryBean) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) SocketSettings(com.mongodb.connection.SocketSettings) Nullable(org.springframework.lang.Nullable) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) ObjectUtils(org.springframework.util.ObjectUtils) MongoClients(com.mongodb.client.MongoClients) ClusterListener(com.mongodb.event.ClusterListener) UuidRepresentation(org.bson.UuidRepresentation) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Builder(com.mongodb.MongoClientSettings.Builder) List(java.util.List) ConnectionString(com.mongodb.ConnectionString) CollectionUtils(org.springframework.util.CollectionUtils) MongoClientSettings(com.mongodb.MongoClientSettings) SpringDataMongoDB(org.springframework.data.mongodb.SpringDataMongoDB) StringUtils(org.springframework.util.StringUtils) ClusterSettings(com.mongodb.connection.ClusterSettings) Builder(com.mongodb.MongoClientSettings.Builder) MongoClientSettings(com.mongodb.MongoClientSettings) SocketSettings(com.mongodb.connection.SocketSettings) SslSettings(com.mongodb.connection.SslSettings) ServerSettings(com.mongodb.connection.ServerSettings) ClusterListener(com.mongodb.event.ClusterListener) ConnectionString(com.mongodb.ConnectionString) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings)

Example 89 with ServerAddress

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());
}
Also used : BulkWriteOptions(com.mongodb.client.model.BulkWriteOptions) BsonDocument(org.bson.BsonDocument) WriteConcernError(com.mongodb.bulk.WriteConcernError) ServerAddress(com.mongodb.ServerAddress) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.jupiter.api.Test)

Example 90 with ServerAddress

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());
    }
}
Also used : MongoClient(com.mongodb.client.MongoClient) AbstractApplicationContext(org.springframework.context.support.AbstractApplicationContext) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ServerAddress(com.mongodb.ServerAddress) ClassPathResource(org.springframework.core.io.ClassPathResource) Test(org.junit.jupiter.api.Test)

Aggregations

ServerAddress (com.mongodb.ServerAddress)201 Test (org.junit.Test)49 MongoClient (com.mongodb.MongoClient)48 ArrayList (java.util.ArrayList)31 Test (org.junit.jupiter.api.Test)31 MongoCredential (com.mongodb.MongoCredential)30 ClusterSettings (com.mongodb.connection.ClusterSettings)20 ClusterId (com.mongodb.connection.ClusterId)19 MongoClientSettings (com.mongodb.MongoClientSettings)18 BsonDocument (org.bson.BsonDocument)18 Before (org.junit.Before)18 ClusterDescription (com.mongodb.connection.ClusterDescription)15 Document (org.bson.Document)14 ServerDescription (com.mongodb.connection.ServerDescription)13 List (java.util.List)12 RepeatedTest (org.junit.jupiter.api.RepeatedTest)12 ConnectionString (com.mongodb.ConnectionString)10 MongoClient (com.mongodb.client.MongoClient)9 MongoDatabase (com.mongodb.client.MongoDatabase)9 ServerId (com.mongodb.connection.ServerId)8