Java Code Examples for com.mongodb.reactivestreams.client.MongoClients#create()

The following examples show how to use com.mongodb.reactivestreams.client.MongoClients#create() . 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: MongoInstance.java    From immutables with Apache License 2.0 6 votes vote down vote up
static MongoInstance create() {
  final String uri = System.getProperty("mongo");


  if (uri != null) {
    // connect to remote mongo server
    return new MongoInstance(MongoClients.create(uri));
  }

  final MongoServer server = new MongoServer(new MemoryBackend());
  final InetSocketAddress address = server.bind();
  final Closer closer = Closer.create();
  closer.register(server::shutdownNow);

  final MongoClient client = MongoClients.create(String.format("mongodb://127.0.0.1:%d", address.getPort()));
  return new MongoInstance(client, closer);
}
 
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: MongoSink.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void open(Map<String, Object> config, SinkContext sinkContext) throws Exception {
    log.info("Open MongoDB Sink");

    mongoConfig = MongoConfig.load(config);
    mongoConfig.validate(true, true);

    if (clientProvider != null) {
        mongoClient = clientProvider.get();
    } else {
        mongoClient = MongoClients.create(mongoConfig.getMongoUri());
    }

    final MongoDatabase db = mongoClient.getDatabase(mongoConfig.getDatabase());
    collection = db.getCollection(mongoConfig.getCollection());

    incomingList = Lists.newArrayList();
    flushExecutor = Executors.newScheduledThreadPool(1);
    flushExecutor.scheduleAtFixedRate(() -> flush(),
            mongoConfig.getBatchTimeMs(), mongoConfig.getBatchTimeMs(), TimeUnit.MILLISECONDS);
}
 
Example 4
Source File: MongoClientWrapper.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public MongoClientWrapper build() {
    buildAndApplySslSettings();

    return new MongoClientWrapper(MongoClients.create(mongoClientSettingsBuilder.build()), defaultDatabaseName,
            dittoMongoClientSettingsBuilder.build(), eventLoopGroup);
}
 
Example 5
Source File: MongoClientTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  JsonObject config = getConfig();
  mongoClient = MongoClient.create(vertx, config);
  CountDownLatch latch = new CountDownLatch(1);
  dropCollections(mongoClient, latch);
  awaitLatch(latch);


  actualMongo = MongoClients.create("mongodb://localhost:27018");
  db = actualMongo.getDatabase(io.vertx.ext.mongo.MongoClient.DEFAULT_DB_NAME);
}
 
Example 6
Source File: ReactiveMongoClientTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void init() {
    client = new ReactiveMongoClientImpl(MongoClients.create(getConnectionString()));
}
 
Example 7
Source File: MongoConfig.java    From spring-reactive-sample with GNU General Public License v3.0 4 votes vote down vote up
@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create(mongoUri);
}
 
Example 8
Source File: ChangeStreamsTests.java    From spring-data-examples with Apache License 2.0 4 votes vote down vote up
/**
 * Configure {@link SimpleReactiveMongoDatabaseFactory} pointing to the embedded MongoDB connection.
 *
 * @return a new {@link SimpleReactiveMongoDatabaseFactory}.
 */
@Bean
SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory() {
	return new SimpleReactiveMongoDatabaseFactory(MongoClients.create(replSet.getConnectionString()),
			"changestreams");
}
 
Example 9
Source File: ReactiveMongoConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Bean
public MongoClient reactiveMongoClient() {
    LoggerFactory.getLogger(getClass()).info("Connecting to mongo url: {}/{}", url, name);
    return MongoClients.create(url);
}
 
Example 10
Source File: MongoConfig.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public MongoClient mongoClient() {
	return MongoClients.create();
}
 
Example 11
Source File: BasicInteractionTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void init() {
    client = new ReactiveMongoClientImpl(MongoClients.create(getConnectionString()));
}
 
Example 12
Source File: MongoConfig.java    From spring-reactive-sample with GNU General Public License v3.0 4 votes vote down vote up
@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create(mongoUri);
}
 
Example 13
Source File: DatabaseRunCommandTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void init() {
    client = new ReactiveMongoClientImpl(MongoClients.create(getConnectionString()));
}
 
Example 14
Source File: QuickTourAdmin.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 * @throws Throwable if an operation fails
 */
public static void main(final String[] args) throws Throwable {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");


    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    ObservableSubscriber subscriber = new ObservableSubscriber<Success>();
    collection.drop().subscribe(subscriber);
    subscriber.await();

    // getting a list of databases
    mongoClient.listDatabaseNames().subscribe(new PrintSubscriber<String>("Database Names: %s"));

    // drop a database
    subscriber = new ObservableSubscriber<Success>();
    mongoClient.getDatabase("databaseToBeDropped").drop().subscribe(subscriber);
    subscriber.await();

    // create a collection
    database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000))
                .subscribe(new PrintSubscriber<Success>("Creation Created!"));


    database.listCollectionNames().subscribe(new PrintSubscriber<String>("Collection Names: %s"));

    // drop a collection:
    subscriber = new ObservableSubscriber<Success>();
    collection.drop().subscribe(subscriber);
    subscriber.await();

    // create an ascending index on the "i" field
    collection.createIndex(new Document("i", 1)).subscribe(new PrintSubscriber<String>("Created an index named: %s"));

    // list the indexes on the collection
    collection.listIndexes().subscribe(new PrintDocumentSubscriber());


    // create a text index on the "content" field
    subscriber = new PrintSubscriber<String>("Created an index named: %s");
    collection.createIndex(new Document("content", "text")).subscribe(subscriber);
    subscriber.await();

    subscriber = new OperationSubscriber();
    collection.insertMany(asList(new Document("_id", 0).append("content", "textual content"),
            new Document("_id", 1).append("content", "additional content"),
            new Document("_id", 2).append("content", "irrelevant content"))).subscribe(subscriber);
    subscriber.await();

    // Find using the text index
    subscriber = new PrintSubscriber("Text search matches: %s");
    collection.countDocuments(text("textual content -irrelevant")).subscribe(subscriber);
    subscriber.await();

    // Find using the $language operator
    subscriber = new PrintSubscriber("Text search matches (english): %s");
    Bson textSearch = text("textual content -irrelevant", new TextSearchOptions().language("english"));
    collection.countDocuments(textSearch).subscribe(subscriber);
    subscriber.await();

    // Find the highest scoring match
    System.out.print("Highest scoring document: ");
    Document projection = new Document("score", new Document("$meta", "textScore"));
    collection.find(textSearch).projection(projection).first().subscribe(new PrintDocumentSubscriber());


    // Run a command
    database.runCommand(new Document("buildInfo", 1)).subscribe(new PrintDocumentSubscriber());

    // release resources
    subscriber = new OperationSubscriber();
    database.drop().subscribe(subscriber);
    subscriber.await();
    mongoClient.close();
}
 
Example 15
Source File: ReactiveTransitionServiceTests.java    From spring-data-examples with Apache License 2.0 4 votes vote down vote up
@Bean
@Override
public MongoClient reactiveMongoClient() {
	return MongoClients.create(replSet.getConnectionString());
}
 
Example 16
Source File: ConnectionToReplicaSetTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
void testConnectionWithReplicaSet() {
    String cs = "mongodb://localhost:27018,localhost:27019/?replicaSet=test001";
    client = new ReactiveMongoClientImpl(MongoClients.create(cs));
    assertThat(client.listDatabases().collectItems().first().await().asOptional().indefinitely()).isNotEmpty();
}
 
Example 17
Source File: ConnectionToReplicaSetTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
void testConnection() {
    String cs = "mongodb://localhost:27018,localhost:27019";
    client = new ReactiveMongoClientImpl(MongoClients.create(cs));
    assertThat(client.listDatabases().collectItems().first().await().asOptional().indefinitely()).isNotEmpty();
}
 
Example 18
Source File: WebfluxTwitterDemoApplication.java    From webflux-twitter-demo with MIT License 4 votes vote down vote up
@Override
public MongoClient mongoClient() {
    // this assumes your MongoDB is running on the default port, i.e. 27017
    return MongoClients.create();
}
 
Example 19
Source File: MongoConfiguration.java    From webFluxTemplate with MIT License 4 votes vote down vote up
@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create();
}
 
Example 20
Source File: EnodeTestDataSourceConfig.java    From enode with MIT License 4 votes vote down vote up
@Bean("enodeMongoClient")
@ConditionalOnProperty(prefix = "spring.enode", name = "eventstore", havingValue = "mongo")
public MongoClient mongoClient() {
    return MongoClients.create();
}