com.mongodb.MongoClientOptions Java Examples

The following examples show how to use com.mongodb.MongoClientOptions. 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
Source File: MongoDBService.java    From nuls-v2 with MIT License 7 votes vote down vote up
@Override
public void afterPropertiesSet() {
    try {
        long time1, time2;
        time1 = System.currentTimeMillis();
        MongoClientOptions options = MongoClientOptions.builder()
                .connectionsPerHost(ApiContext.maxAliveConnect)
                .threadsAllowedToBlockForConnectionMultiplier(ApiContext.maxAliveConnect)
                .socketTimeout(ApiContext.socketTimeout)
                .maxWaitTime(ApiContext.maxWaitTime)
                .connectTimeout(ApiContext.connectTimeOut)
                .build();
        ServerAddress serverAddress = new ServerAddress(ApiContext.databaseUrl, ApiContext.databasePort);
        MongoClient mongoClient = new MongoClient(serverAddress, options);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DATABASE_NAME);

        mongoDatabase.getCollection(TEST_TABLE).drop();
        time2 = System.currentTimeMillis();
        LoggerUtil.commonLog.info("------connect mongodb use time:" + (time2 - time1));
        this.client = mongoClient;
        this.db = mongoDatabase;
    } catch (Exception e) {
        LoggerUtil.commonLog.error(e);
        System.exit(-1);
    }
}
 
Example #2
Source File: MongoClientWrapper.java    From mongowp with Apache License 2.0 6 votes vote down vote up
@Inject
public MongoClientWrapper(MongoClientConfiguration configuration) throws
    UnreachableMongoServerException {
  try {
    MongoClientOptions options = toMongoClientOptions(configuration);
    ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration);

    testAddress(configuration.getHostAndPort(), options);

    this.configuration = configuration;

    this.driverClient = new com.mongodb.MongoClient(
        new ServerAddress(
            configuration.getHostAndPort().getHostText(),
            configuration.getHostAndPort().getPort()),
        credentials,
        options
    );

    version = calculateVersion();
    codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec());
    closed = false;
  } catch (com.mongodb.MongoException ex) {
    throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex);
  }
}
 
Example #3
Source File: MongoLocalConfig.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Bean
public MongoClient mongo() throws UnknownHostException {
    // location of db
    ServerAddress sa = new ServerAddress(
            environment.getProperty("mongodb.host"),
            environment.getProperty("mongodb.port", Integer.class)
    );

    // set optional default parameters here
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    // none yet

    MongoClientOptions options = builder.build();

    return new MongoClient(sa, options);
}
 
Example #4
Source File: MongoSchemaFactory.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  final String host = (String) operand.get("host");
  final String database = (String) operand.get("database");
  final String authMechanismName = (String) operand.get("authMechanism");

  final MongoClientOptions.Builder options = MongoClientOptions.builder();

  final MongoCredential credential;
  if (authMechanismName != null) {
    credential = createCredential(operand);
  } else {
    credential = null;
  }

  return new MongoSchema(host, database, credential, options.build());
}
 
Example #5
Source File: MongoSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  final String host = (String) operand.get("host");
  final Integer port = Integer.valueOf(operand.get("port").toString());
  final String database = (String) operand.get("dbName");
  final String authMechanismName = (String) operand.get("authMechanism");

  final MongoClientOptions.Builder options = MongoClientOptions.builder();

  final List<MongoCredential> credentials = new ArrayList<>();
  if (authMechanismName != null) {
    final MongoCredential credential = createCredentials(operand);
    credentials.add(credential);
  }

  return new MongoSchema(host, port,database, credentials, options.build());
}
 
Example #6
Source File: MongoConfiguration.java    From mongolastic with MIT License 6 votes vote down vote up
private void prepareClient() {
    try {
        ServerAddress address = new ServerAddress(config.getMongo().getHost(), config.getMongo().getPort());
        MongoClientOptions options = MongoClientOptions.builder()
                .serverSelectionTimeout(5000)
                .socketKeepAlive(false)
                .readPreference(ReadPreference.primaryPreferred())
                .sslInvalidHostNameAllowed(true)
                .build();

         client = connectToClient(address, options);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        System.exit(-1);
    }
}
 
Example #7
Source File: HelperMongo.java    From helper with MIT License 6 votes vote down vote up
public HelperMongo(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    this.client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            mongoCredential,
            MongoClientOptions.builder().build()
    );
    this.database = this.client.getDatabase(credentials.getDatabase());
    this.morphia = new Morphia();
    this.morphiaDatastore = this.morphia.createDatastore(this.client, credentials.getDatabase());
    this.morphia.getMapper().getOptions().setObjectFactory(new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass() {
            return LoaderUtils.getPlugin().getClassloader();
        }
    });
}
 
Example #8
Source File: MongoConfig.java    From iot-dc3 with 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 #9
Source File: AbstractConfiguration.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
private Map<String, Method> createSettingsMap() {
    final Map<String, Method> settingsMap = new HashMap<>();

    final Method[] methods = MongoClientOptions.Builder.class.getDeclaredMethods();
    for (final Method method : methods) {
        if (method.getParameterTypes().length == 1) {
            final Class<?> parameterType = method.getParameterTypes()[0];
            // only int, string and boolean

            if (int.class.equals(parameterType) || String.class.equals(parameterType) || boolean.class.equals(parameterType)) {
                settingsMap.put(method.getName(), method);
            }
        }
    }

    return settingsMap;
}
 
Example #10
Source File: MongoWrapper.java    From MongoDb-Sink-Connector with Apache License 2.0 6 votes vote down vote up
private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);

    try {
        MongoClientOptions actualOptions;
        if (options != null) {
            actualOptions = options;
        } else {
            actualOptions = new MongoClientOptions.Builder().build();
        }
        ServerAddress server = new ServerAddress(host, port);
        if (credentials != null) {
            return new MongoClient(server, credentials, actualOptions);
        } else {
            return new MongoClient(server, actualOptions);
        }
    } catch (MongoException ex) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port,
                credentials, ex);
        throw new ConnectException("MongoDb client cannot be created.", ex);
    }
}
 
Example #11
Source File: MongoDB.java    From jelectrum with MIT License 6 votes vote down vote up
public MongoDB(Config config)
  throws Exception
{
  super(config);

  conf.require("mongo_db_host");
  conf.require("mongo_db_name");
  conf.require("mongo_db_connections_per_host");

  MongoClientOptions.Builder opts = MongoClientOptions.builder();
  opts.connectionsPerHost(conf.getInt("mongo_db_connections_per_host"));
  opts.threadsAllowedToBlockForConnectionMultiplier(100);
  opts.socketTimeout(3600000);


  mc = new MongoClient(new ServerAddress(conf.get("mongo_db_host")), opts.build());

  db = mc.getDB(conf.get("mongo_db_name"));


  open();
}
 
Example #12
Source File: AbstractMongoIT.java    From mongo-mapper with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    CodecRegistry codecRegistry = CodecRegistries.fromProviders(MongoMapper.getProviders());
    MongoClientOptions settings = MongoClientOptions.builder().codecRegistry(codecRegistry).build();

    String port = System.getProperty("embedMongoPort");
    Assert.assertNotNull("Please, set system property 'embedMongoPort' to run this test outside Maven.", port);

    client = new MongoClient(new ServerAddress("127.0.0.1", Integer.parseInt(port)), settings);
    dbName = "mapper_test" + UUID.randomUUID();
    db = client.getDatabase(dbName);
}
 
Example #13
Source File: EclipseLinkConfigurationTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testMongoClientOptions() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("eclipselink.nosql.property.mongo.db", "foo");

    // it looks like only the two options below are supported by EclipseLink

    final ReadPreference readPreference = ReadPreference.nearest();
    final WriteConcern writeConcern = WriteConcern.JOURNALED;

    properties.put("eclipselink.nosql.property.mongo.read-preference", readPreference.getName());
    properties.put("eclipselink.nosql.property.mongo.write-concern", "JOURNALED");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final MongoClientOptions clientOptions = configuration.getClientOptions();
    assertThat(clientOptions, notNullValue());
    assertThat(clientOptions.getReadPreference(), equalTo(readPreference));
    assertThat(clientOptions.getWriteConcern(), equalTo(writeConcern));
}
 
Example #14
Source File: CustomMongoHealthIndicator.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String, Object> getMongoClientOptionsAsMap(MongoClientOptions mongoClientOptions) {
    Map<String, Object> config = new HashMap<>();
    config.put("applicationName", mongoClientOptions.getApplicationName());
    config.put("description", mongoClientOptions.getDescription());
    config.put("retryWrites", mongoClientOptions.getRetryWrites());
    config.put("connectionsPerHost", mongoClientOptions.getConnectionsPerHost());
    config.put("minConnectionsPerHost", mongoClientOptions.getMinConnectionsPerHost());
    config.put("threadsAllowedToBlockForConnectionMultiplier", mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier());
    config.put("maxWaitQueueSize", mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() * mongoClientOptions.getConnectionsPerHost()); // from MongoClientOptions.java or ConnectionPoolSettings.java
    config.put("serverSelectionTimeout", mongoClientOptions.getServerSelectionTimeout());
    config.put("maxWaitTime", mongoClientOptions.getMaxWaitTime());
    config.put("maxConnectionIdleTime", mongoClientOptions.getMaxConnectionIdleTime());
    config.put("connectTimeout", mongoClientOptions.getConnectTimeout());
    config.put("socketTimeout", mongoClientOptions.getSocketTimeout());
    config.put("heartbeatFrequency", mongoClientOptions.getHeartbeatFrequency());
    config.put("minHeartbeatFrequency", mongoClientOptions.getMinHeartbeatFrequency());
    config.put("heartbeatConnectTimeout", mongoClientOptions.getHeartbeatConnectTimeout());
    config.put("heartbeatSocketTimeout", mongoClientOptions.getHeartbeatSocketTimeout());
    config.put("localThreshold", mongoClientOptions.getLocalThreshold());
    config.put("requiredReplicaSetName", mongoClientOptions.getRequiredReplicaSetName());
    config.put("isSslEnabled", mongoClientOptions.isSslEnabled());
    config.put("isSslInvalidHostNameAllowed", mongoClientOptions.isSslInvalidHostNameAllowed());
    config.put("isAlwaysUseMBeans", mongoClientOptions.isAlwaysUseMBeans());
    config.put("isCursorFinalizerEnabled", mongoClientOptions.isCursorFinalizerEnabled());
    // Sadly spring-boot-actuator does not support nested details: https://github.com/spring-projects/spring-boot/issues/15795
    config.put("readPreferences.isSlaveOk", mongoClientOptions.getReadPreference().isSlaveOk());
    config.put("readPreferences.name", mongoClientOptions.getReadPreference().getName());
    config.put("readConcern.level", mongoClientOptions.getReadConcern().getLevel());
    config.put("readConcern.isServerDefault", mongoClientOptions.getReadConcern().isServerDefault());
    config.put("writeConcern.w", mongoClientOptions.getWriteConcern().getWObject());
    config.put("writeConcern.wTimeoutMS", mongoClientOptions.getWriteConcern().getWtimeout());
    config.put("writeConcern.fsync", mongoClientOptions.getWriteConcern().getFsync());
    config.put("writeConcern.journal", mongoClientOptions.getWriteConcern().getJournal());
    return config;
}
 
Example #15
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private MongoClient baseClient(MongoClientOptions connectionOptions) {
    if (usesAuthentication) {
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, authenticationDatabase, password.toCharArray());
        return new MongoClient(address, ImmutableList.of(credential), connectionOptions);
    } else {
        return new MongoClient(address, connectionOptions);
    }
}
 
Example #16
Source File: MongoPropertiesTest.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Test
void shouldConfigureCompressorListWhenClientServerCompressionIsEnabled() {
    //given
    final MongoProperties props = new MongoProperties();

    //when
    props.setClientServerCompressionEnabled(true);
    MongoClientOptions mongoClientOptions = props.toMongoClientOptions(MongoClient.getDefaultCodecRegistry(), Collections.singletonList(MongoCompressor.createZlibCompressor()));

    //then
    assertThat(mongoClientOptions.getCompressorList(), is(Collections.singletonList(MongoCompressor.createZlibCompressor())));
}
 
Example #17
Source File: MongoConfiguration.java    From mongolastic with MIT License 5 votes vote down vote up
private MongoClient connectToClient(ServerAddress address, MongoClientOptions options) {
    if (Objects.nonNull(config.getMongo().getAuth())) {

        String user = notNull("auth.name", config.getMongo().getAuth().getUser());
        String database = config.getMongo().getAuth().getSource();
        char[] pwd = config.getMongo().getAuth().getPwd().toCharArray();
        String mechanism = config.getMongo().getAuth().getMechanism();

        MongoCredential credential = findMongoCredential(user, database, pwd, mechanism);
        return new MongoClient(Arrays.asList(address), Arrays.asList(credential), options);

    } else {
        return new MongoClient(Arrays.asList(address), options);
    }
}
 
Example #18
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private MongoClient fastClient() {
    MongoClientOptions fastConnectionOptions = MongoClientOptions.builder()
            .connectTimeout(1000 * 10)
            .maxWaitTime(1000 * 10)
            .serverSelectionTimeout(1000 * 10)
            .build();

    return baseClient(fastConnectionOptions);
}
 
Example #19
Source File: MongoConfiguration.java    From orders with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClientOptions optionsProvider() {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.serverSelectionTimeout(10000);
    MongoClientOptions options = optionsBuilder.build();
    return options;
}
 
Example #20
Source File: KunderaConfigurationTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testMongoClientOptions() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("kundera.keyspace", "foo");

    final int connectionsPerHost = 1;
    final int connectTimeout = 2;
    final int maxWaitTime = 3;
    final int threadsAllowedToBlockForConnectionMultiplier = 4;
    final String requiredReplicaSetName = "Some Replica Name";

    // it looks like only the two options below are supported by Kundera
    properties.put("connection.perhost", "" + 1);
    properties.put("connection.timeout", "" + connectTimeout);
    properties.put("maxwait.time", "" + maxWaitTime);
    properties.put("threadsallowed.block.connectionmultiplier", "" + threadsAllowedToBlockForConnectionMultiplier);
    properties.put("replica.set.name", requiredReplicaSetName);

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final MongoClientOptions clientOptions = configuration.getClientOptions();
    assertThat(clientOptions, notNullValue());
    assertThat(clientOptions.getConnectionsPerHost(), equalTo(connectionsPerHost));
    assertThat(clientOptions.getConnectTimeout(), equalTo(connectTimeout));
    assertThat(clientOptions.getMaxWaitTime(), equalTo(maxWaitTime));
    assertThat(clientOptions.getThreadsAllowedToBlockForConnectionMultiplier(), equalTo(threadsAllowedToBlockForConnectionMultiplier));
    assertThat(clientOptions.getRequiredReplicaSetName(), equalTo(requiredReplicaSetName));
}
 
Example #21
Source File: MongodManager.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void initializeReplicaSet(final List<IMongodConfig> mongodConfigList) throws UnknownHostException, InterruptedException {
    Thread.sleep(1000);
    final MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build();
    final ServerAddress arbitrerAddress = new ServerAddress(mongodConfigList.get(0).net().getServerAddress().getHostName(),
            mongodConfigList.get(0).net().getPort());

    try (MongoClient mongo = new MongoClient(arbitrerAddress, mo)) {
        final MongoDatabase mongoAdminDB = mongo.getDatabase("admin");

        Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1));
        LOGGER.info("isMaster: {}", cr);

        // Build replica set configuration settings
        final Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList);
        LOGGER.info("replSetSettings: {}", rsConfiguration);

        // Initialize replica set
        cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration));
        LOGGER.info("replSetInitiate: {}", cr);

        // Check replica set status before to proceed
        int maxWaitRounds = 10;
        do {
            LOGGER.info("Waiting for 1 second...");
            Thread.sleep(1000);
            cr = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1));
            LOGGER.info("replSetGetStatus: {}", cr);
            maxWaitRounds--;
        } while (!isReplicaSetStarted(cr) || maxWaitRounds != 0);

        if (!isReplicaSetStarted(cr) && maxWaitRounds == 0) {
            throw new RuntimeException("Could not initialize replica set");
        }
    }
}
 
Example #22
Source File: GeoRyaSailFactory.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MongoClient} that is connected to the configured database.
 *
 * @param mongoConf - Configures what will be connected to. (not null)
 * @throws ConfigurationRuntimeException An invalid port was provided by {@code mongoConf}.
 * @throws MongoException Couldn't connect to the MongoDB database.
 */
private static MongoClient createMongoClient(final MongoDBRdfConfiguration mongoConf) throws ConfigurationRuntimeException, MongoException {
    requireNonNull(mongoConf);
    requireNonNull(mongoConf.getMongoHostname());
    requireNonNull(mongoConf.getMongoPort());
    requireNonNull(mongoConf.getMongoDBName());

    // Connect to a running MongoDB server.
    final int port;
    try {
        port = Integer.parseInt( mongoConf.getMongoPort() );
    } catch(final NumberFormatException e) {
        throw new ConfigurationRuntimeException("Port '" + mongoConf.getMongoPort() + "' must be an integer.");
    }

    final ServerAddress server = new ServerAddress(mongoConf.getMongoHostname(), port);

    // Connect to a specific MongoDB Database if that information is provided.
    final String username = mongoConf.getMongoUser();
    final String database = mongoConf.getMongoDBName();
    final String password = mongoConf.getMongoPassword();
    if(username != null && password != null) {
        final MongoCredential cred = MongoCredential.createCredential(username, database, password.toCharArray());
        final MongoClientOptions options = new MongoClientOptions.Builder().build();
        return new MongoClient(server, cred, options);
    } else {
        return new MongoClient(server);
    }
}
 
Example #23
Source File: MongoStoreProvider.java    From alchemy with MIT License 5 votes vote down vote up
private MongoStoreProvider(List<ServerAddress> hosts,
                           List<MongoCredential> credentials,
                           MongoClientOptions options,
                           String database) {
    this(
        options == null ?
        new MongoClient(hosts, credentials) :
        new MongoClient(hosts, credentials, options),
        database
    );
}
 
Example #24
Source File: ReplicaSetBaseTest.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
protected void connectDBWithOptions(MongoClientOptions options){
    List<ServerAddress> serverList = new ArrayList<ServerAddress>();
    serverList.add(new ServerAddress("192.168.1.248", 27017));
    serverList.add(new ServerAddress("192.168.1.248", 27018));
    serverList.add(new ServerAddress("192.168.1.248", 27019));
    
    BuguConnection conn = BuguFramework.getInstance().createConnection();
    conn.setOptions(options);
    conn.setServerList(serverList);
    conn.setUsername("test");
    conn.setPassword("test");
    conn.setDatabase("test");
    conn.connect();
}
 
Example #25
Source File: HibernateOgmConfiguration.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void configureClientOptions(final Map<String, Object> properties) {
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    setOptions(builder, (final String key) -> (String) properties.get(HIBERNATE_OGM_MONGODB_OPTIONS_PREFIX + "." + key));

    final String writeConcern = (String) properties.get(HIBERNATE_OGM_MONGODB_WRITE_CONCERN);
    final String readPreference = (String) properties.get(HIBERNATE_OGM_MONGODB_READ_PREFERENCE);

    if (writeConcern != null) {
        builder.writeConcern(WriteConcern.valueOf(writeConcern));
    }
    if (readPreference != null) {
        builder.readPreference(ReadPreference.valueOf(readPreference));
    }
    mongoClientOptions = builder.build();
}
 
Example #26
Source File: EclipseLinkConfiguration.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void configureClientOptions(final Map<String, Object> properties) {
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    final String writeConcern = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_WRITE_CONCERN);
    final String readPreference = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_READ_PREFERENCE);

    if (writeConcern != null) {
        builder.writeConcern(WriteConcern.valueOf(writeConcern));
    }
    if (readPreference != null) {
        builder.readPreference(ReadPreference.valueOf(readPreference));
    }

    mongoClientOptions = builder.build();
}
 
Example #27
Source File: MongoWrapperTest.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
@Test
public void checkConnectionWithCredentials() throws Exception {
    Map<String, Object> configMap = new HashMap<>();
    configMap.put(MONGO_USERNAME, "myuser");
    configMap.put(MONGO_PASSWORD, "mypassword");
    configMap.put(MONGO_PORT, MONGO_PORT_DEFAULT + 1000);
    configMap.put(MONGO_HOST, "localhost");
    configMap.put(MONGO_DATABASE, "mydb");
    configMap.put(COLLECTION_FORMAT, "{$topic}");
    configMap.put(TOPICS_CONFIG, "a");

    Field credentialsField = MongoWrapper.class.getDeclaredField("credentials");
    credentialsField.setAccessible(true);
    MongoClientOptions timeout = MongoClientOptions.builder()
            .connectTimeout(1)
            .socketTimeout(1)
            .serverSelectionTimeout(1)
            .build();
    MongoWrapper wrapper = new MongoWrapper(new AbstractConfig(CONFIG_DEF, configMap), timeout);

    assertThat(credentialsField.get(wrapper), is(not(nullValue())));
    assertFalse(wrapper.checkConnection());

    thrown.expect(MongoException.class);
    try {
        wrapper.store("mytopic", new Document());
    } finally {
        wrapper.close();
    }
}
 
Example #28
Source File: DatabasesForMongoDBCreator.java    From bluemix-cloud-connectors with Apache License 2.0 5 votes vote down vote up
private MongoClientOptions.Builder getMongoOptions(MongoDbFactoryConfig config) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    if (config != null) {
        if (config.getConnectionsPerHost() != null) {
            builder.connectionsPerHost(config.getConnectionsPerHost());
        }
        if (config.getMaxWaitTime() != null) {
            builder.maxWaitTime(config.getMaxWaitTime());
        }
        if (config.getWriteConcern() != null) {
            builder.writeConcern(new WriteConcern(config.getWriteConcern()));
        }
    }
    return builder;
}
 
Example #29
Source File: MongoConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClient legacyMongoClient() {
	final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
			fromProviders(PojoCodecProvider.builder().automatic(true).build()));
	final MongoClientOptions options = MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build();

	final MongoCredential credentials = MongoCredential.createScramSha1Credential(this.username, "admin", this.password.toCharArray());
	return new MongoClient(new ServerAddress(this.host, NumberUtils.toInt(this.port)), credentials, options);
}
 
Example #30
Source File: MongoDBDriver.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static MongoClientOptions.Builder createDefaultClientOptionsBuilder(Properties connProperties )
  {
      Builder clientOptionsBuilder = new MongoClientOptions.Builder( );
if ( connProperties != null )
{
	if ( hasKeepSocketAlive( connProperties ) ) // need to change
												// setting,
												// as MongoDB default is
												// false
		clientOptionsBuilder.socketKeepAlive( true );

}
return clientOptionsBuilder;
  }