com.mongodb.reactivestreams.client.MongoClient Java Examples

The following examples show how to use com.mongodb.reactivestreams.client.MongoClient. 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: MongoSinkTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() {

    map = TestHelper.createMap(true);

    mockRecord = mock(Record.class);
    mockSinkContext = mock(SinkContext.class);
    mockMongoClient = mock(MongoClient.class);
    mockMongoDb = mock(MongoDatabase.class);
    mockMongoColl = mock(MongoCollection.class);
    mockPublisher = mock(Publisher.class);
    sink = new MongoSink(() -> mockMongoClient);


    when(mockMongoClient.getDatabase(anyString())).thenReturn(mockMongoDb);
    when(mockMongoDb.getCollection(anyString())).thenReturn(mockMongoColl);
    when(mockMongoDb.getCollection(anyString()).insertMany(any())).thenReturn(mockPublisher);
}
 
Example #3
Source File: MongoInstance.java    From immutables with Apache License 2.0 6 votes vote down vote up
private MongoInstance(MongoClient client, Closer closer) {
  Objects.requireNonNull(closer, "closer");
  this.client = Objects.requireNonNull(client, "client");
  closer.register(client);

  // drop database if exists (to have a clean test)
  if (Flowable.fromPublisher(client.listDatabaseNames()).toList().blockingGet().contains(DBNAME)) {
    Success success = Flowable.fromPublisher(client.getDatabase(DBNAME).drop()).blockingFirst();
  }

  this.database = client.getDatabase(DBNAME);

  closer.register(database::drop);

  this.closer = closer;
}
 
Example #4
Source File: MongoSourceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() {

    map = TestHelper.createMap(true);

    mockSourceContext = mock(SourceContext.class);
    mockMongoClient = mock(MongoClient.class);
    mockMongoDb = mock(MongoDatabase.class);
    mockMongoColl = mock(MongoCollection.class);
    mockPublisher = mock(ChangeStreamPublisher.class);

    source = new MongoSource(() -> mockMongoClient);

    when(mockMongoClient.getDatabase(anyString())).thenReturn(mockMongoDb);
    when(mockMongoDb.getCollection(anyString())).thenReturn(mockMongoColl);
    when(mockMongoColl.watch()).thenReturn(mockPublisher);
    when(mockPublisher.batchSize(anyInt())).thenReturn(mockPublisher);
    when(mockPublisher.fullDocument(any())).thenReturn(mockPublisher);

    doAnswer((invocation) -> {
        subscriber = invocation.getArgument(0, Subscriber.class);
        return null;
    }).when(mockPublisher).subscribe(any());
}
 
Example #5
Source File: NewsServicePublisher.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
public NewsServicePublisher(MongoClient client, String categoryOfInterests) {
	ScheduledPublisher<NewsLetter> scheduler = new ScheduledPublisher<>(
			() -> new NewsPreparationOperator(
					new DBPublisher(
							client.getDatabase("news")
							      .getCollection("news", News.class),
							categoryOfInterests
					),
					"Some Digest"
			),
			1, TimeUnit.DAYS
	);

	SmartMulticastProcessor processor = new SmartMulticastProcessor();
	scheduler.subscribe(processor);

	this.processor = processor;
}
 
Example #6
Source File: MongoClientWrapper.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private MongoClientWrapper(final MongoClient theMongoClient,
        final String defaultDatabaseName,
        final DittoMongoClientSettings theDittoMongoClientSettings,
        @Nullable final EventLoopGroup theEventLoopGroup) {

    mongoClient = theMongoClient;
    defaultDatabase = theMongoClient.getDatabase(defaultDatabaseName);
    dittoMongoClientSettings = theDittoMongoClientSettings;
    eventLoopGroup = theEventLoopGroup;
}
 
Example #7
Source File: ReactiveMongoClientTestConfiguration.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClient mongoClient() throws IOException {
  ServerAddress serverAddress = getServerAddress();
  MongoClientSettings settings = MongoClientSettings.builder()
                                                    .clusterSettings(ClusterSettings.builder()
                                                                                    .hosts(singletonList(serverAddress))
                                                                                    .requiredClusterType(STANDALONE)
                                                                                    .build()).build();
  return MongoClients.create(settings);
}
 
Example #8
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 #9
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 #10
Source File: RxMongoDriverQueryService.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
public RxMongoDriverQueryService(
   MongoClient mongoClient,
   @Value("${spring.data.mongodb.database}") String dbName
) {
   this.mongoClient = mongoClient;
   this.dbName = dbName;
}
 
Example #11
Source File: MongoReactiveDataInitializer.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	MongoReactiveDataAutoConfiguration configuration = new MongoReactiveDataAutoConfiguration();
	context.registerBean(MappingMongoConverter.class, () -> configuration.mappingMongoConverter(context.getBean(MongoMappingContext.class), context.getBean(MongoCustomConversions.class)));
	context.registerBean(SimpleReactiveMongoDatabaseFactory.class, () -> configuration.reactiveMongoDatabaseFactory(this.properties, context.getBean(MongoClient.class)));
	context.registerBean(ReactiveMongoTemplate.class, () -> configuration.reactiveMongoTemplate(context.getBean(ReactiveMongoDatabaseFactory.class), context.getBean(MongoConverter.class)));
}
 
Example #12
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 #13
Source File: MongoExtension.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
  final Class<?> type = parameterContext.getParameter().getType();
  if (MongoDatabase.class.isAssignableFrom(type)) {
    return getOrCreate(extensionContext).instance.database();
  } else if (MongoClient.class.isAssignableFrom(type)) {
    return getOrCreate(extensionContext).instance.client();
  }

  throw new ExtensionConfigurationException(String.format("%s supports only %s or %s but yours was %s", MongoExtension.class.getSimpleName(),
          MongoDatabase.class.getName(), MongoClient.class.getName(), type.getName()));
}
 
Example #14
Source File: MongoEventStore.java    From enode with MIT License 5 votes vote down vote up
public MongoEventStore(MongoClient mongoClient, MongoConfiguration mongoConfiguration, IEventSerializer eventSerializer) {
    this.mongoClient = mongoClient;
    this.eventSerializer = eventSerializer;
    this.mongoConfiguration = mongoConfiguration;
    this.duplicateCode = mongoConfiguration.getDuplicateCode();
    this.versionIndexName = mongoConfiguration.getEventTableVersionUniqueIndexName();
    this.commandIndexName = mongoConfiguration.getEventTableCommandIdUniqueIndexName();
}
 
Example #15
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 #16
Source File: MongoReactiveConfig.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create();
}
 
Example #17
Source File: MongodbConfig.java    From coditori with Apache License 2.0 4 votes vote down vote up
@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create();
}
 
Example #18
Source File: MongoFactory.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
    return MongoClient.class;
}
 
Example #19
Source File: EmbeddedClient.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
public MongoClient getMongoClient() {
    return mongoClient;
}
 
Example #20
Source File: ReactiveMongoDbTestConfiguration.java    From mongodb-aggregate-query-support with Apache License 2.0 4 votes vote down vote up
@Bean
public ReactiveMongoOperations reactiveMongoOperations(MongoClient mongoClient, String dbName) {
  return new ReactiveMongoTemplate(mongoClient, dbName);
}
 
Example #21
Source File: MongoSink.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public MongoSink(Supplier<MongoClient> clientProvider) {
    this.clientProvider = clientProvider;
}
 
Example #22
Source File: MongoInstance.java    From immutables with Apache License 2.0 4 votes vote down vote up
MongoClient client() {
  return client;
}
 
Example #23
Source File: MongoInstance.java    From immutables with Apache License 2.0 4 votes vote down vote up
private MongoInstance(MongoClient client) {
  this(client, Closer.create());
}
 
Example #24
Source File: MongoConfiguration.java    From vxms with Apache License 2.0 4 votes vote down vote up
@Override
@DependsOn("embeddedMongoServer")
public MongoClient reactiveMongoClient() {
  return MongoClients.create(url);
}
 
Example #25
Source File: MongoConfiguration.java    From spring-reactive-playground with Apache License 2.0 4 votes vote down vote up
@Override
public MongoClient mongoClient() {
    return MongoClients.create();
}
 
Example #26
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 #27
Source File: ReactiveManagedTransitionServiceTests.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 #28
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 #29
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 #30
Source File: MongoExtension.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
  final Class<?> type = parameterContext.getParameter().getType();
  return MongoDatabase.class.isAssignableFrom(type) || MongoClient.class.isAssignableFrom(type);
}