Java Code Examples for org.springframework.data.mongodb.MongoDbFactory

The following examples show how to use org.springframework.data.mongodb.MongoDbFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Bean
@ConditionalOnMissingBean(MongoDbFactory.class)
public MongoDbFactorySupport<?> mongoDbFactory(ObjectProvider<MongoClient> mongo,
		ObjectProvider<com.mongodb.client.MongoClient> mongoClient) {
	MongoClient preferredClient = mongo.getIfAvailable();
	if (preferredClient != null) {
		return new SimpleMongoDbFactory(preferredClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	com.mongodb.client.MongoClient fallbackClient = mongoClient.getIfAvailable();
	if (fallbackClient != null) {
		return new SimpleMongoClientDbFactory(fallbackClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	throw new IllegalStateException("Expected to find at least one MongoDB client.");
}
 
Example 2
Source Project: iot-dc3   Source File: MongoConfig.java    License: Apache License 2.0 6 votes vote down vote up
public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {
    //创建客户端参数
    MongoClientOptions options = mongoClientOptions(properties);

    //创建客户端和Factory
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : properties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }

    //创建认证客户端
    MongoCredential mongoCredential = MongoCredential
            .createScramSha1Credential(
                    properties.getUsername(),
                    properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                    properties.getPassword().toCharArray()
            );
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, options);

    return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
}
 
Example 3
@Bean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, SequenceOption sequenceOption) {
	DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);

	MongoCustomConversions conversions = new MongoCustomConversions(resolverConverter());
	MongoMappingContext mappingContext = new BHBMongoMappingContext();
	mappingContext.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
	mappingContext.afterPropertiesSet();
	MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mappingContext);
	// _class 剔除
	converter.setTypeMapper(new DefaultMongoTypeMapper(null));
	converter.setCustomConversions(conversions);
	converter.afterPropertiesSet();

	// 需要自增时
	// MongoTemplate template=new DTXDMongoTemplate(mongoDbFactory,converter,
	// sequenceOption);
	MongoTemplate template = new MongoTemplate(mongoDbFactory, converter);
	return template;
}
 
Example 4
/** {@inheritDoc} */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
	if (MONGO_DB_FACTORY_AVAILABLE && bean instanceof MongoDbFactory) {
		final MongoDbFactory mongoDbFactory = (MongoDbFactory) bean;
		final InvocationHandler invocationHandler = new InvocationHandler() {
			/** {@inheritDoc} */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object result = method.invoke(mongoDbFactory, args);
				if (result instanceof MongoDatabase) {
					result = MongoWrapper.createDatabaseProxy((MongoDatabase) result);
				}
				return result;
			}
		};
		final MongoDbFactory factory = JdbcWrapper.createProxy(mongoDbFactory,
				invocationHandler);
		LOG.debug("mongodb monitoring initialized");
		return factory;
	}

	return bean;
}
 
Example 5
/** Test. */
@Test
public void testSpringAOP() {
	final Counter servicesCounter = MonitoringProxy.getServicesCounter();
	servicesCounter.clear();
	final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
			MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME);
	try {
		final MongoDbFactory mongoDbFactory = context.getBean(MongoDbFactory.class);
		assertNotNull("toString", mongoDbFactory.toString());
		assertNotNull("getDb", mongoDbFactory.getDb());

		final SpringMongoDbFactoryBeanPostProcessor springMongoDbFactoryBeanPostProcessor = context
				.getBean(SpringMongoDbFactoryBeanPostProcessor.class);
		assertEquals("order", Ordered.LOWEST_PRECEDENCE,
				springMongoDbFactoryBeanPostProcessor.getOrder());
		springMongoDbFactoryBeanPostProcessor.setOrder(1);
		assertEquals("order", 1, springMongoDbFactoryBeanPostProcessor.getOrder());
	} finally {
		context.close();
	}
}
 
Example 6
@Test
public void cloudMongoCreationNoConfig() throws Exception {
	MongoServiceInfo serviceInfo = new MongoServiceInfo("id", TEST_HOST, TEST_PORT, TEST_USERNAME, TEST_PASSWORD, TEST_DB);

	MongoDbFactory mongoDbFactory = testCreator.create(serviceInfo, null);
	assertNotNull(mongoDbFactory);

	MongoClient mongoClient = getMongoClientField(mongoDbFactory);

	MongoCredential credentials = mongoClient.getCredentialsList().get(0);

	List<ServerAddress> addresses = extractServerAddresses(mongoClient);
	assertEquals(1, addresses.size());

	ServerAddress address = addresses.get(0);

	assertEquals(serviceInfo.getHost(), address.getHost());
	assertEquals(serviceInfo.getPort(), address.getPort());
	assertEquals(serviceInfo.getUserName(), credentials.getUserName());
	assertNotNull(credentials.getPassword());

	// Don't do connector.getDatabase().getName() as that will try to initiate the connection
	assertEquals(serviceInfo.getDatabase(), ReflectionTestUtils.getField(mongoDbFactory, "databaseName"));
}
 
Example 7
@Test
public void cloudScanWithAllTypesOfServices() {
	ApplicationContext testContext = getTestApplicationContext(createMysqlService("mysqlDb"), 
															  createPostgresqlService("postDb"),
															  createMongoService("mongoDb"),
															  createRedisService("redisDb"),
															  createRabbitService("rabbit"));
	
	assertNotNull("Getting service by id", testContext.getBean("mysqlDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mysqlDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("postDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("postDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("mongoDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mongoDb", MongoDbFactory.class));		
	
	assertNotNull("Getting service by id", testContext.getBean("redisDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("redisDb", RedisConnectionFactory.class));		

	assertNotNull("Getting service by id", testContext.getBean("rabbit"));
	assertNotNull("Getting service by id and type", testContext.getBean("rabbit", ConnectionFactory.class));		
}
 
Example 8
@Bean
@ConditionalOnMissingBean(MongoConverter.class)
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
		MongoMappingContext context, MongoCustomConversions conversions) {
	DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
	MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver,
			context);
	// 去掉 _class项
	mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
	mappingConverter.setCustomConversions(conversions);
	return mappingConverter;
}
 
Example 9
@Bean
@ConditionalOnMissingBean
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory,
		MongoTemplate mongoTemplate) {
	return new GridFsTemplate(
			new GridFsMongoDbFactory(mongoDbFactory, this.beihuMongoProperties),
			mongoTemplate.getConverter());
}
 
Example 10
Source Project: iot-dc3   Source File: MongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public MongoTemplate mongoTemplate(
        MongoClientOptionProperties properties,
        MongoDbFactory factory,
        MongoMappingContext context,
        MongoCustomConversions conversions
) {
    return new MongoTemplate(mongoDbFactory(properties), mappingMongoConverter(factory, context, conversions));
}
 
Example 11
Source Project: iot-dc3   Source File: MongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
public MappingMongoConverter mappingMongoConverter(
        MongoDbFactory factory,
        MongoMappingContext context,
        MongoCustomConversions conversions
) {
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
    MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
    mappingConverter.setCustomConversions(conversions);
    mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    return mappingConverter;
}
 
Example 12
public static void assertConfigProperties(MongoDbFactory connector, String writeConcern, Integer connectionsPerHost, Integer maxWaitTime) {
	if (connectionsPerHost == null) {
		connectionsPerHost = 100; // default
	}
	if (maxWaitTime == null) {
		maxWaitTime = 120000; // default
	}
	assertNotNull(connector);

	assertEquals(ReflectionTestUtils.getField(connector,  "writeConcern"), writeConcern == null ? null : WriteConcern.valueOf(writeConcern));
	
	MongoClient mongoClient = (MongoClient) ReflectionTestUtils.getField(connector, "mongoClient");
	assertEquals(connectionsPerHost.intValue(), mongoClient.getMongoClientOptions().getConnectionsPerHost());
	assertEquals(maxWaitTime.intValue(), mongoClient.getMongoClientOptions().getMaxWaitTime());
}
 
Example 13
@Test
public void allServicesProvisioned() {
	ApplicationContext testContext = getTestApplicationContext("cloud-all-services.xml", 
															   createMysqlService("mysqlDb"), 
															   createPostgresqlService("postDb"),
															   createMongoService("mongoDb"),
															   createRedisService("redisDb"),
															   createRabbitService("rabbit"),
															   createCassandraService("cassandra"));
	
	assertNotNull("Getting service by id", testContext.getBean("mysqlDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mysqlDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("postDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("postDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("mongoDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mongoDb", MongoDbFactory.class));		
	
	assertNotNull("Getting service by id", testContext.getBean("redisDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("redisDb", RedisConnectionFactory.class));		

	assertNotNull("Getting service by id", testContext.getBean("rabbit"));
	assertNotNull("Getting service by id and type", testContext.getBean("rabbit", ConnectionFactory.class));

	assertNotNull("Getting service by id", testContext.getBean("cassandra"));
		assertNotNull("Getting service by id and type", testContext.getBean("cassandra", Cluster.class));
}
 
Example 14
@Bean(name = "mongoTemplate")
public MongoTemplate createMongoTemplate() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(host, port);
    //TODO Configure additional MongoDB mongoClient settings if needed
    MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, database, new UserCredentials(username, password));
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), new MongoMappingContext());
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));

    return new MongoTemplate(factory, converter);
}
 
Example 15
Source Project: bearchoke   Source File: AxonMongoTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public AxonMongoTemplate(MongoDbFactory mongoDbFactory) {
    this.mongoDbFactory = mongoDbFactory;
    this.mongoTemplate = new org.springframework.data.mongodb.core.MongoTemplate(mongoDbFactory);

    domainEventsCollectionName = DEFAULT_DOMAINEVENTS_COLLECTION;
    snapshotEventsCollectionName = DEFAULT_SNAPSHOTEVENTS_COLLECTION;
}
 
Example 16
Source Project: hello-spring-cloud   Source File: HomeController.java    License: Apache License 2.0 5 votes vote down vote up
private String toString(MongoDbFactory mongoDbFactory) {
    if (mongoDbFactory == null) {
        return "<none>";
    } else {
        try {
            return mongoDbFactory.getDb().getMongo().getAddress().toString();
        } catch (Exception ex) {
            return "<invalid address> " + mongoDbFactory.getDb().getMongo().toString();
        }
    }
}
 
Example 17
Source Project: spring-music   Source File: MongoLocalConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public MongoDbFactory mongoDbFactory() {
    try {
        return new SimpleMongoDbFactory(new MongoClient(), "music");
    } catch (UnknownHostException e) {
        throw new RuntimeException("Error creating MongoDbFactory: " + e);
    }
}
 
Example 18
@Test
public void cloudMongoCreationWithMultipleHostsByUri() throws Exception {
	String uri = String.format("%s://%s:%[email protected]%s:%s/%s", MONGODB_SCHEME, TEST_USERNAME, TEST_PASSWORD,
			StringUtils.arrayToDelimitedString(TEST_HOSTS, ","), TEST_PORT, TEST_DB);

	MongoServiceInfo serviceInfo = new MongoServiceInfo("id", uri);

	MongoDbFactory mongoDbFactory = testCreator.create(serviceInfo, null);
	assertNotNull(mongoDbFactory);

	MongoClient mongoClient = getMongoClientField(mongoDbFactory);

	List<ServerAddress> addresses = extractServerAddresses(mongoClient);
	assertEquals(3, addresses.size());

	MongoCredential credentials = mongoClient.getCredentialsList().get(0);
	assertEquals(TEST_USERNAME, credentials.getUserName());
	assertNotNull(credentials.getPassword());

	// Don't do connector.getDatabase().getName() as that will try to initiate the connection
	assertEquals(TEST_DB, ReflectionTestUtils.getField(mongoDbFactory, "databaseName"));

	ServerAddress address1 = addresses.get(0);
	assertEquals(TEST_HOST, address1.getHost());
	assertEquals(TEST_PORT_DEFAULT, address1.getPort());

	ServerAddress address2 = addresses.get(1);
	assertEquals(TEST_HOST_1, address2.getHost());
	assertEquals(TEST_PORT_DEFAULT, address2.getPort());

	ServerAddress address3 = addresses.get(2);
	assertEquals(TEST_HOST_2, address3.getHost());
	assertEquals(TEST_PORT, address3.getPort());
}
 
Example 19
@Test
public void withConfigAllOptionsSpecifiedWriteConcernNone() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernNone", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "none", 50, 200);
}
 
Example 20
@Test
public void withConfigAllOptionsSpecifiedWriteConcernSafe() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernSafe", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "safe", 50, 200);
}
 
Example 21
@Test
public void withConfigAllOptionsSpecifiedWriteConcernUnspecified() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 200);
}
 
Example 22
@Test
public void withConfigOnlyConnectionPerHostSpecified() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWaitUnspecified_WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 120000);
}
 
Example 23
@Test
public void withConfigAllOptionsSpecifiedWriteConcernNone() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-connectionPerHost50-maxWait200-WriteConcernNone", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "none", 50, 200);
}
 
Example 24
@Test
public void withConfigOnlyMaxWaitSpecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWait200-connectionPerHostUnspecified-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, null, 200);
}
 
Example 25
@Test
public void withConfigAllOptionsSpecifiedWriteConcernUnspecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWait200-connectionPerHost50-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 200);
}
 
Example 26
@Test
public void withConfigOnlyConnectionPerHostSpecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWaitUnspecified-connectionPerHost50-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, null);
}
 
Example 27
GridFsMongoDbFactory(MongoDbFactory mongoDbFactory, BeihuMongoProperties beihuMongoProperties) {
	Assert.notNull(mongoDbFactory, "MongoDbFactory must not be null");
	Assert.notNull(beihuMongoProperties, "Properties must not be null");
	this.mongoDbFactory = mongoDbFactory;
	this.beihuMongoProperties = beihuMongoProperties;
}
 
Example 28
@Override
public MongoDbFactory withSession(ClientSession session) {
	return this.mongoDbFactory.withSession(session);
}
 
Example 29
Source Project: ZTuoExchange_framework   Source File: MongoConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public MongoDbFactory dbFactory() throws Exception {
    return new SimpleMongoDbFactory(getMongoClientURI());
}
 
Example 30
Source Project: ZTuoExchange_framework   Source File: MongoConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public MongoDbFactory dbFactory() throws Exception {
    return new SimpleMongoDbFactory(getMongoClientURI());
}