Example usage for com.mongodb ConnectionString getCollection

List of usage examples for com.mongodb ConnectionString getCollection

Introduction

In this page you can find the example usage for com.mongodb ConnectionString getCollection.

Prototype

@Nullable
public String getCollection() 

Source Link

Document

Gets the collection name

Usage

From source file:org.jooby.mongodb.MongoRx.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//  ww w.j a  va2 s  .c  o  m
public void configure(final Env env, final Config conf, final Binder binder) {
    /** connection string */
    ConnectionString cstr = Try.of(() -> new ConnectionString(db))
            .getOrElse(() -> new ConnectionString(conf.getString(db)));

    log.debug("Starting {}", cstr);

    boolean first = instances.getAndIncrement() == 0;
    Function3<Class, String, Object, Void> bind = (type, name, value) -> {
        binder.bind(Key.get(type, Names.named(name))).toInstance(value);
        if (first) {
            binder.bind(Key.get(type)).toInstance(value);
        }
        return null;
    };

    /** settings */
    MongoClientSettings.Builder settings = settings(cstr, dbconf(db, conf));
    if (configurer != null) {
        configurer.accept(settings, conf);
    }
    MongoClient client = MongoClients.create(settings.build());
    bind.apply(MongoClient.class, db, client);

    /** bind database */
    Optional.ofNullable(cstr.getDatabase()).ifPresent(dbname -> {
        // observable adapter
        MongoDatabase predb = adapter.map(a -> client.getDatabase(dbname).withObservableAdapter(a))
                .orElseGet(() -> client.getDatabase(dbname));
        // codec registry
        MongoDatabase database = codecRegistry.map(predb::withCodecRegistry).orElse(predb);

        bind.apply(MongoDatabase.class, dbname, database);

        /** bind collection */
        Optional.ofNullable(cstr.getCollection()).ifPresent(cname -> {
            MongoCollection<Document> collection = database.getCollection(cname);
            bind.apply(MongoCollection.class, cname, collection);
        });
    });

    /** mapper */
    env.router().map(mapper());

    log.info("Started {}", cstr);

    env.onStop(() -> {
        log.debug("Stopping {}", cstr);
        client.close();
        log.info("Stopped {}", cstr);
    });
}