Java Code Examples for com.mongodb.MongoClientSettings#Builder

The following examples show how to use com.mongodb.MongoClientSettings#Builder . 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: EmbedMongoConfiguration.java    From syndesis with Apache License 2.0 8 votes vote down vote up
private static MongoClient getClient(Boolean useCredentials, String replicaSet) {
    MongoClientSettings.Builder settings = MongoClientSettings.builder();

    if (useCredentials) {
        MongoCredential credentials = MongoCredential.createCredential(
            USER, ADMIN_DB, PASSWORD.toCharArray());
        settings.credential(credentials);
    }
    StringBuilder connectionString = new StringBuilder(String.format("mongodb://%s:%d", HOST, PORT));
    if (replicaSet != null) {
        connectionString.append(String.format("/?replicaSet=%s", REPLICA_SET));
    }
    ConnectionString uri = new ConnectionString(connectionString.toString());
    settings.applyConnectionString(uri);

    settings.readPreference(ReadPreference.primaryPreferred());

    return MongoClients.create(settings.build());
}
 
Example 2
Source File: DatabaseManager.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private DatabaseManager() {
    final MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder()
            .codecRegistry(CODEC_REGISTRY)
            .applicationName(String.format("Shadbot V%s", Config.VERSION));

    if (!Config.IS_SNAPSHOT) {
        final String username = CredentialManager.getInstance().get(Credential.DATABASE_USERNAME);
        final String pwd = CredentialManager.getInstance().get(Credential.DATABASE_PWD);
        final String host = CredentialManager.getInstance().get(Credential.DATABASE_HOST);
        final String port = CredentialManager.getInstance().get(Credential.DATABASE_PORT);
        if (username != null && pwd != null && host != null && port != null) {
            settingsBuilder.applyConnectionString(new ConnectionString(
                    String.format("mongodb://%s:%s@%s:%s/%s", username, pwd, host, port, Config.DATABASE_NAME)));
        }
    }

    this.client = MongoClients.create(settingsBuilder.build());

    final MongoDatabase database = this.client.getDatabase(Config.DATABASE_NAME);
    this.premiumCollection = new PremiumCollection(database);
    this.guildsCollection = new GuildsCollection(database);
    this.lotteryCollection = new LotteryCollection(database);
    this.usersCollection = new UsersCollection(database);
}
 
Example 3
Source File: NewsServiceApp.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Bean
MongoClient mongoClient(MongoProperties properties) {
    ConnectionString connectionString = new ConnectionString(properties.determineUri());
    MongoClientSettings.Builder builder = MongoClientSettings
            .builder()
            .streamFactoryFactory(NettyStreamFactory::new)
            .applyToClusterSettings(b -> b.applyConnectionString(connectionString))
            .applyToConnectionPoolSettings(b -> b.applyConnectionString(connectionString))
            .applyToServerSettings(b -> b.applyConnectionString(connectionString))
            .applyToSslSettings(b -> b.applyConnectionString(connectionString))
            .applyToSocketSettings(b -> b.applyConnectionString(connectionString))
            .codecRegistry(fromRegistries(
                MongoClients.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder()
                                               .automatic(true)
                                               .register(News.class)
                                               .build())
            ));

    if (connectionString.getReadPreference() != null) {
        builder.readPreference(connectionString.getReadPreference());
    }
    if (connectionString.getReadConcern() != null) {
        builder.readConcern(connectionString.getReadConcern());
    }
    if (connectionString.getWriteConcern() != null) {
        builder.writeConcern(connectionString.getWriteConcern());
    }
    if (connectionString.getApplicationName() != null) {
        builder.applicationName(connectionString.getApplicationName());
    }
    return MongoClients.create(builder.build());
}
 
Example 4
Source File: WithEmbeddedMongo.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
default MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://localhost/news");
    MongoClientSettings.Builder builder = MongoClientSettings.builder()
            .streamFactoryFactory(NettyStreamFactory::new)
            .applyToClusterSettings((cs) -> cs
                    .applyConnectionString(connectionString))
            .applyToConnectionPoolSettings(cps -> cps
                    .applyConnectionString(connectionString))
            .applyToServerSettings(ss -> ss
                    .applyConnectionString(connectionString))
          // TODO: Do not work with JDK11 without the next line being commented (null is not allowed)
          //.credential(connectionString.getCredential())
            .applyToSslSettings(ss -> ss
                    .applyConnectionString(connectionString))
            .applyToSocketSettings(ss -> ss
                    .applyConnectionString(connectionString))
            .codecRegistry(fromRegistries(
                    MongoClients.getDefaultCodecRegistry(),
                    fromProviders(PojoCodecProvider.builder()
                            .automatic(true)
                            .register(News.class)
                            .build())
            ));

    if (connectionString.getReadPreference() != null) {
        builder.readPreference(connectionString.getReadPreference());
    }
    if (connectionString.getReadConcern() != null) {
        builder.readConcern(connectionString.getReadConcern());
    }
    if (connectionString.getWriteConcern() != null) {
        builder.writeConcern(connectionString.getWriteConcern());
    }
    if (connectionString.getApplicationName() != null) {
        builder.applicationName(connectionString.getApplicationName());
    }

    return MongoClients.create(builder.build());
}
 
Example 5
Source File: MongoClientCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    MongoCustomizersUtil.replaceAdminDBIfMissing(options);
    // Set connection parameter
    if (!options.containsKey("mongoConnection")) {
        if (options.containsKey("user") && options.containsKey("password")
                && options.containsKey("host")) {
            ConnectionParamsConfiguration mongoConf = new ConnectionParamsConfiguration(cast(options));
            // We need to force consumption in order to perform property placeholder done by Camel
            consumeOption(camelContext, options, "password", String.class, mongoConf::setPassword);
            LOGGER.debug("Creating and registering a client connection to {}", mongoConf);

            MongoClientSettings.Builder settings = MongoClientSettings.builder();
            MongoCredential credentials = MongoCredential.createCredential(
                mongoConf.getUser(),
                mongoConf.getAdminDB(),
                mongoConf.getPassword().toCharArray());

            ConnectionString uri = new ConnectionString(mongoConf.getMongoClientURI());
            settings.applyConnectionString(uri);
            settings.credential(credentials);

            MongoClient mongoClient = MongoClients.create(settings.build());

            options.put("mongoConnection", mongoClient);
            if (!options.containsKey("connectionBean")) {
                //We safely put a default name instead of leaving null
                options.put("connectionBean", String.format("%s-%s", mongoConf.getHost(), mongoConf.getUser()));
            }
        } else {
            LOGGER.warn(
                "Not enough information provided to set-up the MongoDB client. Required at least host, user and " +
                    "password.");
        }
    }
}
 
Example 6
Source File: TraceMongoDbAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(MongoClientSettings.Builder clientSettingsBuilder) {
	super.customize(clientSettingsBuilder);
	CommandListener listener = clientSettingsBuilder.build().getCommandListeners()
			.get(0);
	listener.commandStarted(new CommandStartedEvent(0, null, "", "",
			BDDMockito.mock(BsonDocument.class)));
	listener.commandSucceeded(new CommandSucceededEvent(1, null, "",
			BDDMockito.mock(BsonDocument.class), 100));
}
 
Example 7
Source File: TraceMongoDbAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(MongoClientSettings.Builder clientSettingsBuilder) {
	clientSettingsBuilder.addCommandListener(
			MongoDBTracing.create(this.tracing).commandListener());
}
 
Example 8
Source File: MongoClientOptionsParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
public MongoClientOptionsParser(Vertx vertx, JsonObject config) {
  Objects.requireNonNull(config);

  MongoClientSettings.Builder options = MongoClientSettings.builder();
  options.codecRegistry(CodecRegistries.fromRegistries(commonCodecRegistry, CodecRegistries.fromCodecs(new JsonObjectCodec(config))));

  // All parsers should support connection_string first
  String cs = config.getString("connection_string");
  ConnectionString connectionString = (cs == null) ? null : new ConnectionString(cs);
  String csDatabase = (connectionString != null) ? connectionString.getDatabase() : null;
  this.database = csDatabase != null ? csDatabase : config.getString("db_name", MongoClient.DEFAULT_DB_NAME);

  // ClusterSettings
  ClusterSettings clusterSettings = new ClusterSettingsParser(connectionString, config).settings();
  options.applyToClusterSettings(builder -> builder.applySettings(clusterSettings));

  // ConnectionPoolSettings
  ConnectionPoolSettings connectionPoolSettings = new ConnectionPoolSettingsParser(connectionString, config).settings();
  options.applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings));

  // Credentials
  // The previous mongo client supported credentials list but their new implementation supports only
  // one credentials. The deprecated code path resorts to using the last credentials if a list is passed
  // we are doing the same here.
  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  if (!credentials.isEmpty())
    options.credential(credentials.get(credentials.size() - 1));

  // SocketSettings
  SocketSettings socketSettings = new SocketSettingsParser(connectionString, config).settings();
  options.applyToSocketSettings(builder -> builder.applySettings(socketSettings));

  // Transport type
  new StreamTypeParser(config).streamFactory().ifPresent(options::streamFactoryFactory);

  // SSLSettings
  SslSettings sslSettings = new SSLSettingsParser(connectionString, config).settings(vertx);
  options.applyToSslSettings(builder -> builder.applySettings(sslSettings));

  // WriteConcern
  WriteConcern writeConcern = new WriteConcernParser(connectionString, config).writeConcern();
  if (writeConcern != null) {
    options.writeConcern(writeConcern);
  }

  // ReadConcern
  maybeReadConcern(connectionString, config).ifPresent(options::readConcern);

  // ReadPreference
  ReadPreference readPreference = new ReadPreferenceParser(connectionString, config).readPreference();
  if (readPreference != null) {
    options.readPreference(readPreference);
  }

  // ServerSettings
  ServerSettings serverSettings = new ServerSettingsParser(config).settings();
  options.applyToServerSettings(builder -> builder.applySettings(serverSettings));

  this.settings = options.build();
}
 
Example 9
Source File: ITMongoDB.java    From brave with Apache License 2.0 4 votes vote down vote up
static MongoClientSettings.Builder mongoClientSettingsBuilder() {
  return MongoClientSettings.builder().applyToClusterSettings(b -> b.hosts(singletonList(
    new ServerAddress(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGODB_PORT)))));
}