Search in sources :

Example 11 with MongoClient

use of com.mongodb.client.MongoClient in project spring-boot by spring-projects.

the class EmbeddedMongoAutoConfigurationTests method customMongoServerConfiguration.

@Test
void customMongoServerConfiguration() {
    loadWithValidVersion(CustomMongoConfiguration.class);
    Map<String, MongoClient> mongoClients = this.context.getBeansOfType(MongoClient.class);
    assertThat(mongoClients).isNotEmpty();
    for (String mongoClientBeanName : mongoClients.keySet()) {
        BeanDefinition beanDefinition = this.context.getBeanFactory().getBeanDefinition(mongoClientBeanName);
        assertThat(beanDefinition.getDependsOn()).contains("customMongoServer");
    }
}
Also used : MongoClient(com.mongodb.client.MongoClient) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Test(org.junit.jupiter.api.Test)

Example 12 with MongoClient

use of com.mongodb.client.MongoClient in project spring-boot by spring-projects.

the class EmbeddedMongoAutoConfigurationTests method useRandomPortByDefault.

@Test
void useRandomPortByDefault() {
    loadWithValidVersion();
    assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1);
    MongoClient client = this.context.getBean(MongoClient.class);
    Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port"));
    assertThat(getPort(client)).isEqualTo(mongoPort);
}
Also used : MongoClient(com.mongodb.client.MongoClient) Test(org.junit.jupiter.api.Test)

Example 13 with MongoClient

use of com.mongodb.client.MongoClient 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 14 with MongoClient

use of com.mongodb.client.MongoClient in project rocketmq-externals by apache.

the class MongoFactoryTest method testSSLTrustStore.

@Test
public void testSSLTrustStore() {
    sourceTaskConfig.setMongoUserName("user_test");
    sourceTaskConfig.setMongoPassWord("pwd_test");
    sourceTaskConfig.setSsl(true);
    sourceTaskConfig.setSslInvalidHostNameAllowed(true);
    sourceTaskConfig.setTrustStore("/Users/home/test.pem");
    sourceTaskConfig.setTrustStorePassword("test001");
    sourceTaskConfig.setServerSelectionTimeoutMS(10000);
    MongoClient client = mongoClientFactory.createMongoClient(replicaSetConfig);
    MongoCollection<Document> collection = client.getDatabase("test").getCollection("person");
    Document document = new Document();
    document.put("name", "test");
    collection.insertOne(document);
    MongoCursor<Document> iterator = collection.find().iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}
Also used : MongoClient(com.mongodb.client.MongoClient) Document(org.bson.Document) Test(org.junit.Test)

Example 15 with MongoClient

use of com.mongodb.client.MongoClient 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

MongoClient (com.mongodb.client.MongoClient)45 Document (org.bson.Document)22 MongoDatabase (com.mongodb.client.MongoDatabase)19 Test (org.junit.Test)10 Map (java.util.Map)9 MongoClientSettings (com.mongodb.MongoClientSettings)8 ServerAddress (com.mongodb.ServerAddress)8 HashMap (java.util.HashMap)7 ConnectionString (com.mongodb.ConnectionString)6 BsonDocument (org.bson.BsonDocument)6 BsonString (org.bson.BsonString)6 Test (org.junit.jupiter.api.Test)6 List (java.util.List)5 SecureRandom (java.security.SecureRandom)4 Set (java.util.Set)4 TimeUnit (java.util.concurrent.TimeUnit)4 BsonValue (org.bson.BsonValue)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 ClientSessionOptions (com.mongodb.ClientSessionOptions)3 ClusterFixture.getMultiMongosConnectionString (com.mongodb.ClusterFixture.getMultiMongosConnectionString)3