com.mongodb.MongoClientSettings Java Examples

The following examples show how to use com.mongodb.MongoClientSettings. 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: AggregationQuery.java    From immutables with Apache License 2.0 7 votes vote down vote up
AggregationQuery(Query query, PathNaming pathNaming) {
  this.query = maybeRewriteDistinctToGroupBy(query);
  this.pathNaming = Objects.requireNonNull(pathNaming, "naming");

  BiMap<Expression, String> biMap = HashBiMap.create();

  List<Path> paths = Stream.concat(query.projections().stream(), Stream.concat(query.groupBy().stream(), query.collations().stream().map(Collation::expression)))
          .map(AggregationQuery::extractPath).collect(Collectors.toList());

  @SuppressWarnings("unchecked")
  ExpressionNaming naming = ExpressionNaming.from(UniqueCachedNaming.of(paths.iterator()));
  paths.forEach(p -> biMap.put(p, naming.name(p)));

  this.projectionNaming = ExpressionNaming.from(UniqueCachedNaming.of(query.projections()));
  this.naming = ImmutableBiMap.copyOf(biMap);
  this.codecRegistry = MongoClientSettings.getDefaultCodecRegistry();
}
 
Example #3
Source File: MongoSourceTask.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * This method also is responsible for caching the {@code resumeAfter} value for the change
 * stream.
 */
private void setCachedResultAndResumeToken() {
  MongoChangeStreamCursor<ChangeStreamDocument<Document>> changeStreamCursor =
      getChangeStreamIterable(sourceConfig, mongoClient).cursor();
  ChangeStreamDocument<Document> firstResult = changeStreamCursor.tryNext();
  if (firstResult != null) {
    cachedResult =
        new BsonDocumentWrapper<>(
            firstResult,
            ChangeStreamDocument.createCodec(
                Document.class, MongoClientSettings.getDefaultCodecRegistry()));
  }
  cachedResumeToken =
      firstResult != null ? firstResult.getResumeToken() : changeStreamCursor.getResumeToken();
  changeStreamCursor.close();
}
 
Example #4
Source File: MongoDb4Provider.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private MongoDb4Provider(final String connectionStringSource, final boolean isCapped,
        final Integer collectionSize) {
    LOGGER.debug("Creating ConnectionString {}...", connectionStringSource);
    this.connectionString = new ConnectionString(connectionStringSource);
    LOGGER.debug("Created ConnectionString {}", connectionString);
    LOGGER.debug("Creating MongoClientSettings...");
    // @formatter:off
    final MongoClientSettings settings = MongoClientSettings.builder()
            .applyConnectionString(this.connectionString)
            .codecRegistry(CODEC_REGISTRIES)
            .build();
    // @formatter:on
    LOGGER.debug("Created MongoClientSettings {}", settings);
    LOGGER.debug("Creating MongoClient {}...", settings);
    this.mongoClient = MongoClients.create(settings);
    LOGGER.debug("Created MongoClient {}", mongoClient);
    String databaseName = this.connectionString.getDatabase();
    LOGGER.debug("Getting MongoDatabase {}...", databaseName);
    this.mongoDatabase = this.mongoClient.getDatabase(databaseName);
    LOGGER.debug("Got MongoDatabase {}", mongoDatabase);
    this.isCapped = isCapped;
    this.collectionSize = collectionSize;
}
 
Example #5
Source File: TestBase.java    From morphia with Apache License 2.0 6 votes vote down vote up
protected TestBase() {
    Builder builder = MongoClientSettings.builder();

    try {
        builder.uuidRepresentation(mapperOptions.getUuidRepresentation());
    } catch(Exception ignored) {
        // not a 4.0 driver
    }

    MongoClientSettings clientSettings = builder
                           .applyConnectionString(new ConnectionString(getMongoURI()))
                                                            .build();

    this.mongoClient = MongoClients.create(clientSettings);
    this.database = getMongoClient().getDatabase(TEST_DB_NAME);
    this.ds = Morphia.createDatastore(getMongoClient(), database.getName());
    ds.setQueryFactory(new DefaultQueryFactory());
}
 
Example #6
Source File: BsonParserTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * write with BSON read with jackson.
 * inverse of {@link #jacksonThenBson(String)}
 */
private void bsonThenJackson(String json) throws IOException {
  ObjectNode toWrite = maybeWrap(mapper.readTree(json));

  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);

  // write with BSON
  BsonDocument expected = BsonDocument.parse(toWrite.toString());
  MongoClientSettings.getDefaultCodecRegistry().get(BsonDocument.class)
          .encode(writer, expected, EncoderContext.builder().build());

  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
  IOContext ioContext = new IOContext(new BufferRecycler(), null, false);
  BsonParser parser = new BsonParser(ioContext, 0, reader);

  // read with jackson
  BsonDocument actual = BsonDocument.parse(mapper.readValue(parser, JsonNode.class).toString());

  if (!actual.equals(expected)) {
     check(maybeUnwrap(actual)).is(maybeUnwrap(expected));
     Assertions.fail("Should have failed before");
  }
}
 
Example #7
Source File: BsonParserTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * write with Jackson read with Bson.
 * Inverse of {@link #bsonThenJackson(String)}
 */
private void jacksonThenBson(String json) throws IOException {
  ObjectNode toWrite = maybeWrap(mapper.readTree(json));

  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);
  BsonGenerator generator = new BsonGenerator(0, writer);
  // write with jackson
  mapper.writeValue(generator, toWrite);
  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));

  // read with BSON
  BsonDocument actual = MongoClientSettings.getDefaultCodecRegistry()
          .get(BsonDocument.class)
          .decode(reader, DecoderContext.builder().build());

  // compare results
  BsonDocument expected = BsonDocument.parse(toWrite.toString());
  if (!expected.equals(actual)) {
    check(maybeUnwrap(actual)).is(maybeUnwrap(expected));
    Assertions.fail("Should have failed before");
  }
}
 
Example #8
Source File: MongoDriverConnectInterceptor3_7.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private List<String> getHostList(Object arg) {
    if (!(arg instanceof MongoClientSettings)) {
        return Collections.emptyList();
    }

    final MongoClientSettings mongoClientSettings = (MongoClientSettings) arg;

    List<ServerAddress> lists = mongoClientSettings.getClusterSettings().getHosts();

    final List<String> hostList = new ArrayList<String>();
    for (ServerAddress sa : lists) {
        final String hostAddress = HostAndPort.toHostAndPortString(sa.getHost(), sa.getPort());
        hostList.add(hostAddress);
    }

    return hostList;
}
 
Example #9
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 #10
Source File: Mongo.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Get default mongodb database reference or initiate it if not initialized.
 *
 * @param connectionString MongoDB standard connection string
 * @param database         mongodb database name
 * @return MongoDB mongodb client database reference.
 */
public static MongoDatabase getOrInitDefaultDatabase(String connectionString, String database) {
    if (DEFAULT_DATABASE == null) {
        synchronized (LOCK) {
            if (DEFAULT_DATABASE == null) {
                if (!StringUtil.isEmpty(connectionString)) {
                    DEFAULT_CLIENT = MongoClients.create(connectionString);
                    CodecRegistry pojoCodecRegistry = fromRegistries(
                            /*fromCodecs(new StringCodecExt()),*/
                            MongoClientSettings.getDefaultCodecRegistry(),
                            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
                    DEFAULT_DATABASE = DEFAULT_CLIENT.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
                } else {
                    throw new RuntimeException("No datasource configuration found for mongodb.");
                }
            }
        }
    }
    return DEFAULT_DATABASE;
}
 
Example #11
Source File: BsonLogParamTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void append() {
    var param = new BsonLogParam(Filters.eq("field", "value"), MongoClientSettings.getDefaultCodecRegistry());
    var builder = new StringBuilder();
    param.append(builder, Set.of(), 1000);
    assertThat(builder.toString()).isEqualTo("{\"field\": \"value\"}");
}
 
Example #12
Source File: ParsingSSLOptionsTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void ssl_should_be_disabled_by_default() {
  // given
  final JsonObject configWithoutSSLInfo = new JsonObject().put(
    "connection_string", "mongodb://localhost:27017/mydb?replicaSet=myRs"
  );

  // when
  final MongoClientSettings parsedSettings = new MongoClientOptionsParser(vertx, configWithoutSSLInfo).settings();

  // then
  assertFalse(parsedSettings.getSslSettings().isEnabled());
  assertFalse(parsedSettings.getSslSettings().isInvalidHostNameAllowed());
}
 
Example #13
Source File: ParsingStreamTypeTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_include_any_stream_type_by_default_for_backwards_compatibility() {
  // given
  final JsonObject noStreamTypeProvided = new JsonObject().put(
    "connection_string", "mongodb://localhost:27017/mydb?replicaSet=myRs"
  );

  // when
  final MongoClientSettings parsedSettings = new MongoClientOptionsParser(vertx, noStreamTypeProvided).settings();

  // then
  assertNull(parsedSettings.getStreamFactoryFactory());
}
 
Example #14
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
synchronized com.mongodb.reactivestreams.client.MongoClient mongo(Vertx vertx, MongoClientSettings settings) {
  if (mongo == null) {
    MongoClientOptionsParser parser = new MongoClientOptionsParser(vertx, config);
    mongo = MongoClients.create(settings);
    db = mongo.getDatabase(parser.database());
  }
  return mongo;
}
 
Example #15
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
public MongoClientImpl(Vertx vertx, JsonObject config, String dataSourceName, MongoClientSettings settings) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(config);
  Objects.requireNonNull(dataSourceName);
  Objects.requireNonNull(settings);
  this.vertx = (VertxInternal) vertx;
  this.creatingContext = this.vertx.getOrCreateContext();
  this.holder = lookupHolder(dataSourceName, config);
  this.mongo = holder.mongo(vertx, settings);
  this.useObjectId = config.getBoolean("useObjectId", false);

  creatingContext.addCloseHook(this);
}
 
Example #16
Source File: ParsingStreamTypeTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Parameters(method = "validSteamTypes")
@Test
public void should_parse_stream_type_from_config_property(String streamTypeString, Class<StreamFactoryFactory> streamType) {
  // given
  final JsonObject cfgWithStreamTypeProvided = new JsonObject().put("streamType", streamTypeString);

  // when
  final MongoClientSettings parsedSettings = new MongoClientOptionsParser(vertx, cfgWithStreamTypeProvided).settings();

  // then
  assertThat(parsedSettings.getStreamFactoryFactory(), instanceOf(streamType));
}
 
Example #17
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 #18
Source File: MongoDriverConnectInterceptor3_7.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private String getReadPreference(Object arg) {
    if (!(arg instanceof MongoClientSettings)) {
        return null;
    }

    final MongoClientSettings mongoClientSettings = (MongoClientSettings) arg;

    return mongoClientSettings.getReadPreference().getName();
}
 
Example #19
Source File: MongoDriverConnectInterceptor3_7.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private String getWriteConcern(Object arg) {
    if (!(arg instanceof MongoClientSettings)) {
        return null;
    }

    final MongoClientSettings mongoClientSettings = (MongoClientSettings) arg;

    return MongoUtil.getWriteConcern0(mongoClientSettings.getWriteConcern());
}
 
Example #20
Source File: Parsers.java    From immutables with Apache License 2.0 5 votes vote down vote up
static BsonParser createParser(BsonDocument bson) {
  BasicOutputBuffer buffer = new BasicOutputBuffer();
  CodecRegistry registry = MongoClientSettings.getDefaultCodecRegistry();
  registry.get(BsonDocument.class)
          .encode(new BsonBinaryWriter(buffer), bson, EncoderContext.builder().build());

  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
  IOContext ioContext = new IOContext(new BufferRecycler(), null, false);
  return new BsonParser(ioContext, 0, reader);
}
 
Example #21
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 #22
Source File: MongoConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Override
@Bean
public com.mongodb.client.MongoClient mongoClient() {
	final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
			fromProviders(PojoCodecProvider.builder().automatic(true).build()));

	final String connectionsString = String.format("mongodb://%s:%s@%s:%s", this.username, this.password, this.host, this.port);
	final MongoClientSettings settings = MongoClientSettings.builder()
			.codecRegistry(pojoCodecRegistry)
			.applyConnectionString(new ConnectionString(
					connectionsString))
			.build();

	return MongoClients.create(settings);
}
 
Example #23
Source File: MongoImpl.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private MongoDatabase createDatabase(CodecRegistry registry) {
    if (uri == null) throw new Error("uri must not be null");
    String database = uri.getDatabase();
    if (database == null) throw new Error("uri must have database, uri=" + uri);
    var watch = new StopWatch();
    try {
        connectionPoolSettings.maxWaitTime(timeoutInMs, TimeUnit.MILLISECONDS); // pool checkout timeout
        var socketSettings = SocketSettings.builder()
                                           .connectTimeout((int) timeoutInMs, TimeUnit.MILLISECONDS)
                                           .readTimeout((int) timeoutInMs, TimeUnit.MILLISECONDS)
                                           .build();
        var clusterSettings = ClusterSettings.builder()
                                             .serverSelectionTimeout(timeoutInMs * 3, TimeUnit.MILLISECONDS)    // able to try 3 servers
                                             .build();
        var settings = MongoClientSettings.builder()
                                          .applicationName(LogManager.APP_NAME)
                                          .codecRegistry(registry)
                                          .applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings.build()))
                                          .applyToSocketSettings(builder -> builder.applySettings(socketSettings))
                                          .applyToClusterSettings(builder -> builder.applySettings(clusterSettings))
                                          .applyConnectionString(uri)
                                          .build();
        mongoClient = MongoClients.create(settings);
        return mongoClient.getDatabase(database);
    } finally {
        logger.info("create mongo client, uri={}, elapsed={}", uri, watch.elapsed());
    }
}
 
Example #24
Source File: MongoClientWrapper.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private MongoClientWrapperBuilder() {
    mongoClientSettingsBuilder = MongoClientSettings.builder();
    mongoClientSettingsBuilder.readPreference(ReadPreference.primaryPreferred());
    dittoMongoClientSettingsBuilder = DittoMongoClientSettings.getBuilder();
    connectionString = null;
    defaultDatabaseName = null;
    sslEnabled = false;
    eventLoopGroup = null;
}
 
Example #25
Source File: MongoReactiveInitializer.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean(MongoClientSettingsBuilderCustomizer.class, () -> new MongoReactiveAutoConfiguration.NettyDriverConfiguration().nettyDriverCustomizer(context.getDefaultListableBeanFactory().getBeanProvider(MongoClientSettings.class)));

	MongoReactiveAutoConfiguration configuration = new MongoReactiveAutoConfiguration();
	context.registerBean(MongoClient.class, () -> configuration.reactiveStreamsMongoClient(this.properties, context.getEnvironment(), context.getBeanProvider(MongoClientSettingsBuilderCustomizer.class), context.getBeanProvider(MongoClientSettings.class)), (definition) -> {
		if (embeddedServer) {
			definition.setDependsOn("embeddedMongoServer");
		}
	});
}
 
Example #26
Source File: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the local collection representing the given namespace for raw document operations.
 *
 * @param namespace the namespace referring to the local collection.
 * @return the local collection representing the given namespace for raw document operations.
 */
MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {
  return getLocalCollection(
      namespace,
      BsonDocument.class,
      MongoClientSettings.getDefaultCodecRegistry());
}
 
Example #27
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 #28
Source File: MongoDBSourceTest.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
static MongoClient mongoClient(String connectionString, int connectionTimeoutSeconds) {
    MongoClientSettings settings = MongoClientSettings
            .builder()
            .applyConnectionString(new ConnectionString(connectionString))
            .applyToClusterSettings(b -> {
                b.serverSelectionTimeout(connectionTimeoutSeconds, SECONDS);
            })
            .build();

    return MongoClients.create(settings);
}
 
Example #29
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 #30
Source File: MongoWithReplicasTestBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void initializeReplicaSet(final List<IMongodConfig> mongodConfigList) throws UnknownHostException {
    final String arbitrerAddress = "mongodb://" + mongodConfigList.get(0).net().getServerAddress().getHostName() + ":"
            + mongodConfigList.get(0).net().getPort();
    final MongoClientSettings mo = MongoClientSettings.builder()
            .applyConnectionString(new ConnectionString(arbitrerAddress)).build();

    try (MongoClient mongo = MongoClients.create(mo)) {
        final MongoDatabase mongoAdminDB = mongo.getDatabase("admin");

        Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1));
        LOGGER.infof("isMaster: %s", cr);

        // Build replica set configuration settings
        final Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList);
        LOGGER.infof("replSetSettings: %s", rsConfiguration);

        // Initialize replica set
        cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration));
        LOGGER.infof("replSetInitiate: %s", cr);

        // Check replica set status before to proceed
        await()
                .pollInterval(100, TimeUnit.MILLISECONDS)
                .atMost(1, TimeUnit.MINUTES)
                .until(() -> {
                    Document result = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1));
                    LOGGER.infof("replSetGetStatus: %s", result);
                    return !isReplicaSetStarted(result);
                });
    }
}