Search in sources :

Example 76 with MongoClient

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

the class MongoClientFactoryTests method uriCanBeCustomized.

@Test
public void uriCanBeCustomized() {
    MongoProperties properties = new MongoProperties();
    properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test");
    MongoClient client = createMongoClient(properties);
    List<ServerAddress> allAddresses = extractServerAddresses(client);
    assertThat(allAddresses).hasSize(2);
    assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345);
    assertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456);
    List<MongoCredential> credentialsList = client.getCredentialsList();
    assertThat(credentialsList).hasSize(1);
    assertMongoCredential(credentialsList.get(0), "user", "secret", "test");
}
Also used : MongoClient(com.mongodb.MongoClient) MongoCredential(com.mongodb.MongoCredential) ServerAddress(com.mongodb.ServerAddress) Test(org.junit.Test)

Example 77 with MongoClient

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

the class MongoPropertiesTests method allMongoClientOptionsCanBeSet.

@Test
public void allMongoClientOptionsCanBeSet() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.alwaysUseMBeans(true);
    builder.connectionsPerHost(101);
    builder.connectTimeout(10001);
    builder.cursorFinalizerEnabled(false);
    builder.description("test");
    builder.maxWaitTime(120001);
    builder.socketKeepAlive(true);
    builder.socketTimeout(1000);
    builder.threadsAllowedToBlockForConnectionMultiplier(6);
    builder.minConnectionsPerHost(0);
    builder.maxConnectionIdleTime(60000);
    builder.maxConnectionLifeTime(60000);
    builder.heartbeatFrequency(10001);
    builder.minHeartbeatFrequency(501);
    builder.heartbeatConnectTimeout(20001);
    builder.heartbeatSocketTimeout(20001);
    builder.localThreshold(20);
    builder.requiredReplicaSetName("testReplicaSetName");
    MongoClientOptions options = builder.build();
    MongoProperties properties = new MongoProperties();
    MongoClient client = new MongoClientFactory(properties, null).createMongoClient(options);
    MongoClientOptions wrapped = client.getMongoClientOptions();
    assertThat(wrapped.isAlwaysUseMBeans()).isEqualTo(options.isAlwaysUseMBeans());
    assertThat(wrapped.getConnectionsPerHost()).isEqualTo(options.getConnectionsPerHost());
    assertThat(wrapped.getConnectTimeout()).isEqualTo(options.getConnectTimeout());
    assertThat(wrapped.isCursorFinalizerEnabled()).isEqualTo(options.isCursorFinalizerEnabled());
    assertThat(wrapped.getDescription()).isEqualTo(options.getDescription());
    assertThat(wrapped.getMaxWaitTime()).isEqualTo(options.getMaxWaitTime());
    assertThat(wrapped.getSocketTimeout()).isEqualTo(options.getSocketTimeout());
    assertThat(wrapped.isSocketKeepAlive()).isEqualTo(options.isSocketKeepAlive());
    assertThat(wrapped.getThreadsAllowedToBlockForConnectionMultiplier()).isEqualTo(options.getThreadsAllowedToBlockForConnectionMultiplier());
    assertThat(wrapped.getMinConnectionsPerHost()).isEqualTo(options.getMinConnectionsPerHost());
    assertThat(wrapped.getMaxConnectionIdleTime()).isEqualTo(options.getMaxConnectionIdleTime());
    assertThat(wrapped.getMaxConnectionLifeTime()).isEqualTo(options.getMaxConnectionLifeTime());
    assertThat(wrapped.getHeartbeatFrequency()).isEqualTo(options.getHeartbeatFrequency());
    assertThat(wrapped.getMinHeartbeatFrequency()).isEqualTo(options.getMinHeartbeatFrequency());
    assertThat(wrapped.getHeartbeatConnectTimeout()).isEqualTo(options.getHeartbeatConnectTimeout());
    assertThat(wrapped.getHeartbeatSocketTimeout()).isEqualTo(options.getHeartbeatSocketTimeout());
    assertThat(wrapped.getLocalThreshold()).isEqualTo(options.getLocalThreshold());
    assertThat(wrapped.getRequiredReplicaSetName()).isEqualTo(options.getRequiredReplicaSetName());
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientOptions(com.mongodb.MongoClientOptions) Test(org.junit.Test)

Example 78 with MongoClient

use of com.mongodb.MongoClient in project spring-cloud-connectors by spring-cloud.

the class MongoServiceConnectorCreatorTest method cloudMongoCreationNoConfig.

@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 mongo = (MongoClient) ReflectionTestUtils.getField(mongoDbFactory, "mongo");
    assertNotNull(mongo);
    MongoCredential credentials = mongo.getCredentialsList().get(0);
    List<ServerAddress> addresses = extractServerAddresses(mongo);
    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"));
}
Also used : MongoClient(com.mongodb.MongoClient) MongoDbFactory(org.springframework.data.mongodb.MongoDbFactory) MongoCredential(com.mongodb.MongoCredential) ServerAddress(com.mongodb.ServerAddress) MongoServiceInfo(org.springframework.cloud.service.common.MongoServiceInfo) Test(org.junit.Test)

Example 79 with MongoClient

use of com.mongodb.MongoClient in project spring-cloud-connectors by spring-cloud.

the class MongoDbFactoryCloudConfigTestHelper method assertConfigProperties.

public static void assertConfigProperties(MongoDbFactory connector, String writeConcern, Integer connectionsPerHost, Integer maxWaitTime) {
    if (connectionsPerHost == null) {
        // default
        connectionsPerHost = 100;
    }
    if (maxWaitTime == null) {
        // default
        maxWaitTime = 120000;
    }
    assertNotNull(connector);
    assertEquals(ReflectionTestUtils.getField(connector, "writeConcern"), writeConcern == null ? null : WriteConcern.valueOf(writeConcern));
    MongoClient mongoClient = (MongoClient) ReflectionTestUtils.getField(connector, "mongo");
    assertEquals(connectionsPerHost.intValue(), mongoClient.getMongoClientOptions().getConnectionsPerHost());
    assertEquals(maxWaitTime.intValue(), mongoClient.getMongoClientOptions().getMaxWaitTime());
}
Also used : MongoClient(com.mongodb.MongoClient)

Example 80 with MongoClient

use of com.mongodb.MongoClient in project GNS by MobilityFirst.

the class MongoRecords method init.

private void init(String nodeID, int mongoPort) {
    if (Config.getGlobalBoolean(GNSConfig.GNSC.IN_MEMORY_DB)) {
        return;
    }
    mongoCollectionSpecs = new MongoCollectionSpecs();
    mongoCollectionSpecs.addCollectionSpec(DBNAMERECORD, NameRecord.NAME);
    // add location as another index
    mongoCollectionSpecs.getCollectionSpec(DBNAMERECORD).addOtherIndex(new BasicDBObject(NameRecord.VALUES_MAP.getName() + "." + GNSProtocol.LOCATION_FIELD_NAME.toString(), "2d"));
    // The good thing is that indexes are not required for 2dsphere fields, but they will make things faster
    mongoCollectionSpecs.getCollectionSpec(DBNAMERECORD).addOtherIndex(new BasicDBObject(NameRecord.VALUES_MAP.getName() + "." + GNSProtocol.LOCATION_FIELD_NAME_2D_SPHERE.toString(), "2dsphere"));
    mongoCollectionSpecs.getCollectionSpec(DBNAMERECORD).addOtherIndex(new BasicDBObject(NameRecord.VALUES_MAP.getName() + "." + GNSProtocol.IPADDRESS_FIELD_NAME.toString(), 1));
    boolean fatalException = false;
    try {
        // use a unique name in case we have more than one on a machine (need to remove periods, btw)
        dbName = DBROOTNAME + sanitizeDBName(nodeID);
        //MongoCredential credential = MongoCredential.createMongoCRCredential("admin", dbName, "changeit".toCharArray());
        if (mongoPort > 0) {
            //mongoClient = new MongoClient(new ServerAddress("localhost", mongoPort), Arrays.asList(credential));
            mongoClient = new MongoClient("localhost", mongoPort);
        } else {
            mongoClient = new MongoClient("localhost");
        }
        db = mongoClient.getDB(dbName);
        initializeIndexes();
    } catch (UnknownHostException e) {
        fatalException = true;
        DatabaseConfig.getLogger().log(Level.SEVERE, "{0} Unable to open Mongo DB: {1}", new Object[] { dbName, e.getMessage() });
    } catch (com.mongodb.MongoServerSelectionException msse) {
        fatalException = true;
        DatabaseConfig.getLogger().log(Level.SEVERE, "{0} Fatal exception while trying to initialize Mongo DB: {1}", new Object[] { dbName, msse });
    } finally {
        if (fatalException) {
            Util.suicide("Mongo DB initialization failed likely because a mongo DB server is not listening at the expected port; exiting.");
        }
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) MongoClient(com.mongodb.MongoClient) UnknownHostException(java.net.UnknownHostException) JSONObject(org.json.JSONObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Aggregations

MongoClient (com.mongodb.MongoClient)126 Test (org.junit.Test)31 MongoClientURI (com.mongodb.MongoClientURI)29 Document (org.bson.Document)26 ServerAddress (com.mongodb.ServerAddress)21 MongoDatabase (com.mongodb.client.MongoDatabase)21 Before (org.junit.Before)20 BasicDBObject (com.mongodb.BasicDBObject)11 ArrayList (java.util.ArrayList)11 MongoCredential (com.mongodb.MongoCredential)9 MongoException (com.mongodb.MongoException)8 DB (com.mongodb.DB)7 DBCollection (com.mongodb.DBCollection)7 UnknownHostException (java.net.UnknownHostException)7 MongoTemplate (org.springframework.data.mongodb.core.MongoTemplate)7 DBObject (com.mongodb.DBObject)6 MongoClientOptions (com.mongodb.MongoClientOptions)6 IOException (java.io.IOException)5 List (java.util.List)5 MongoDbFactory (org.springframework.data.mongodb.MongoDbFactory)5