Example usage for com.mongodb MongoClientURI getDatabase

List of usage examples for com.mongodb MongoClientURI getDatabase

Introduction

In this page you can find the example usage for com.mongodb MongoClientURI getDatabase.

Prototype

@Nullable
public String getDatabase() 

Source Link

Document

Gets the database name

Usage

From source file:com.edgytech.umongo.MainMenu.java

License:Apache License

public void connect() {
    try {// www.  j av  a2 s . c o m
        ConnectDialog dialog = (ConnectDialog) getBoundUnit(Item.connectDialog);
        ProgressDialog progress = (ProgressDialog) getBoundUnit(Item.connectProgressDialog);
        MongoClient mongo = null;
        List<String> dbs = new ArrayList<String>();
        String uri = dialog.getStringFieldValue(ConnectDialog.Item.uri);
        if (!uri.trim().isEmpty()) {
            if (!uri.startsWith(MongoURI.MONGODB_PREFIX)) {
                uri = MongoURI.MONGODB_PREFIX + uri;
            }
            MongoClientURI muri = new MongoClientURI(uri);
            mongo = new MongoClient(muri);
            String db = muri.getDatabase();
            if (db != null && !db.trim().isEmpty()) {
                dbs.add(db.trim());
            }
        } else {
            String servers = dialog.getStringFieldValue(ConnectDialog.Item.servers);
            if (servers.trim().isEmpty()) {
                return;
            }
            String[] serverList = servers.split(",");
            ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
            for (String server : serverList) {
                String[] tmp = server.split(":");
                if (tmp.length > 1) {
                    addrs.add(new ServerAddress(tmp[0], Integer.valueOf(tmp[1]).intValue()));
                } else {
                    addrs.add(new ServerAddress(tmp[0]));
                }
            }
            if ("Direct".equals(dialog.getStringFieldValue(ConnectDialog.Item.connectionMode)))
                mongo = new MongoClient(addrs.get(0), dialog.getMongoClientOptions());
            else
                mongo = new MongoClient(addrs, dialog.getMongoClientOptions());

            String sdbs = dialog.getStringFieldValue(ConnectDialog.Item.databases);
            if (!sdbs.trim().isEmpty()) {
                for (String db : sdbs.split(",")) {
                    dbs.add(db.trim());
                }
            }
        }

        if (dbs.size() == 0) {
            dbs = null;
        }

        String user = dialog.getStringFieldValue(ConnectDialog.Item.user).trim();
        String password = dialog.getStringFieldValue(ConnectDialog.Item.password);
        if (!user.isEmpty()) {
            // authenticate against all dbs
            if (dbs != null) {
                for (String db : dbs) {
                    mongo.getDB(db).authenticate(user, password.toCharArray());
                }
            } else {
                mongo.getDB("admin").authenticate(user, password.toCharArray());
            }
        }

        final MongoClient fmongo = mongo;
        final List<String> fdbs = dbs;
        // doing in background can mean concurrent modification, but dialog is modal so unlikely
        progress.show(new ProgressDialogWorker(progress) {
            @Override
            protected void finished() {
            }

            @Override
            protected Object doInBackground() throws Exception {
                UMongo.instance.addMongoClient(fmongo, fdbs);
                return null;
            }
        });

    } catch (Exception ex) {
        UMongo.instance.showError(id, ex);
    }
}

From source file:com.everydots.kafka.connect.mongodb.MongoDbSinkTask.java

License:Apache License

@Override
public void start(Map<String, String> props) {
    logger.info("starting MongoDB sink task");

    sinkConfig = new MongoDbSinkConnectorConfig(props);

    MongoClientURI uri = sinkConfig.buildClientURI();
    mongoClient = new MongoClient(uri);
    database = mongoClient.getDatabase(uri.getDatabase());

    remainingRetries = sinkConfig.getInt(MongoDbSinkConnectorConfig.MONGODB_MAX_NUM_RETRIES_CONF);
    deferRetryMs = sinkConfig.getInt(MongoDbSinkConnectorConfig.MONGODB_RETRIES_DEFER_TIMEOUT_CONF);

    processorChain = sinkConfig.buildPostProcessorChain();

    if (sinkConfig.isUsingCdcHandler()) {
        cdcHandler = sinkConfig.getCdcHandler();
    }/*from w ww .  j a v a  2 s .  com*/
}

From source file:com.github.nlloyd.hornofmongo.MongoRuntime.java

License:Open Source License

/**
 * Creates a newly initialized {@link MongoScope} instance with a connection
 * to the specified mongodb instance/cluster. This will use
 * {@link MongoRuntime#call(MongoAction)} to initialize the
 * {@link MongoScope} instance, possibly resulting in the global
 * {@link MongoContextFactory} being set.
 * /*from w w w.j a  v  a2s. c  o m*/
 * After the scope is initialized a call via the mongo JS API to the
 * "connect()" method will be made to initialize the global db instance.
 * 
 * @return
 */
public static final MongoScope createMongoScope(final MongoClientURI mongoClientURI,
        boolean useMongoShellWriteConcern, boolean mimicShellExceptionBehavior) throws UnknownHostException {
    if (StringUtils.isBlank(mongoClientURI.getDatabase()))
        throw new IllegalArgumentException("mongo client uri must have a database");
    MongoScope mongoScope = createMongoScope();
    mongoScope.setUseMongoShellWriteConcern(useMongoShellWriteConcern);
    mongoScope.setStdoutMongoErrorMessages(mimicShellExceptionBehavior);

    StringBuilder connectStrBuilder = new StringBuilder("db = connect('");

    if ((mongoClientURI.getHosts().size() == 1) && (mongoClientURI.getHosts().get(0).equals("localhost")
            || mongoClientURI.getHosts().get(0).equals("localhost:27017")))
        connectStrBuilder.append(mongoClientURI.getDatabase());
    else
        connectStrBuilder.append(mongoClientURI.getURI());

    connectStrBuilder.append("', null, null);");

    call(new MongoScriptAction(mongoScope, "connect", connectStrBuilder.toString()));

    return mongoScope;
}

From source file:com.jaeksoft.searchlib.crawler.cache.MongoDbCrawlCache.java

License:Open Source License

@Override
public void init(String configString) throws IOException {
    rwl.w.lock();//from   ww  w .  jav a2  s  .  c o  m
    try {
        closeNoLock();
        final MongoClientURI connectionString = new MongoClientURI(configString);
        mongoClient = new MongoClient(connectionString);
        final MongoDatabase database = mongoClient.getDatabase(
                connectionString.getDatabase() == null ? DEFAULT_DATABASE : connectionString.getDatabase());
        metaCollection = database.getCollection(META_COLLECTION);
        metaCollection.createIndex(Document.parse("{\"uri\":1}"));
        indexedCollection = database.getCollection(INDEXED_COLLECTION);
        indexedCollection.createIndex(Document.parse("{\"uri\":1}"));
        contentGrid = GridFSBuckets.create(database);
    } finally {
        rwl.w.unlock();
    }
}

From source file:com.jive.myco.seyren.mongo.MongoStore.java

License:Apache License

@Inject
public MongoStore(SeyrenConfig seyrenConfig) {
    try {/*from  ww w  .  j a va2 s  .c  om*/
        String uri = seyrenConfig.getMongoUrl();
        MongoClientURI mongoClientUri = new MongoClientURI(uri);
        MongoClient mongoClient = new MongoClient(mongoClientUri);
        DB mongo = mongoClient.getDB(mongoClientUri.getDatabase());
        mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        this.mongo = mongo;
        bootstrapMongo();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mysweethome.TemperaturePersisterTimerTask.java

public synchronized void persistDataOnMongolab() {
    //disable console logging
    //Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); 
    //mongoLogger.setLevel(Level.SEVERE);

    iStoredTemperatures = iTemperatureStore.getTemperatures();
    if (iStoredTemperatures.isEmpty()) {
        logger.info("Nothing to persist. Exiting");
        return;/*  www . j av  a  2s  .  c  o m*/
    }
    logger.info("Prepairing to persist [{}] Temps in the cloud", iStoredTemperatures.size());
    MongoCollection<Document> mongoCollection = null;
    MongoClient client = null;
    List<Document> documents = new ArrayList<Document>();

    for (TemperatureMeasure tTemp : iStoredTemperatures) { //Exception in thread "Timer-2" java.util.ConcurrentModificationException
        Document doc = new Document();
        doc.put("Location", tTemp.getLocation()); //Location
        doc.put("Group", tTemp.getGroup()); //Group
        doc.put("Date", Helper.getDateAsString(tTemp.getDate())); //Date
        doc.put("Day", Helper.getDayAsString(tTemp.getDate()));
        doc.put("Time", Helper.getTimeAsString(tTemp.getDate()));
        doc.put("Temp", Helper.getTempAsString(tTemp.getTemp())); //Temp
        documents.add(doc);
        iPersistedTemperatures.add(tTemp);
    }

    try {
        MongoClientURI uri = new MongoClientURI(MySweetHomeProperties.ML_URL);
        client = new MongoClient(uri);
        MongoDatabase database = (MongoDatabase) client.getDatabase(uri.getDatabase());
        mongoCollection = database.getCollection("dailytemps");
        mongoCollection.insertMany(documents);
        //eliminate stored Temps from the collection
        iTemperatureStore.removeAll(iPersistedTemperatures);
        client.close();
        logger.info("Temperatures persisted on mongolab: [{}]. Exiting.", iPersistedTemperatures.size());
        iPersistedTemperatures.clear();
    } catch (Throwable e) {
        logger.error("Failed to store Temps in the cloud. Stacktrace: [{}]. Exiting.", e);
        iPersistedTemperatures.clear();
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.close();
        }
        iPersistedTemperatures.clear();
    }
}

From source file:com.naryx.tagfusion.cfm.application.sessionstorage.SessionStorageMongoImpl.java

License:Open Source License

/**
 * mongodb://[a@b:]server1:port1,server2:port2/db
 * //  w  w  w  .  j  a  v  a 2s  .com
 * @param appName
 * @param connectionUri
 */
public SessionStorageMongoImpl(String appName, String _connectionUri) throws Exception {
    super(appName);

    this.uri = _connectionUri;

    if (_connectionUri.startsWith("mongodb://")) {

        MongoClientURI clientURI = new MongoClientURI(_connectionUri);
        mongo = new MongoClient(clientURI);
        mdb = mongo.getDatabase(clientURI.getDatabase() == null ? "openbd" : clientURI.getDatabase());

    } else {

        // Parse the URL
        String user = null, pass = null, db = "openbd";

        // Are they using a user/pass
        String connectionUri = _connectionUri.substring(_connectionUri.indexOf("//") + 2);
        if (connectionUri.indexOf("@") != -1) {
            int c1 = connectionUri.indexOf("@");
            user = connectionUri.substring(0, c1);

            int c2 = connectionUri.indexOf(":", c1 + 1);
            if (c2 == -1)
                throw new Exception("invalid connection uri: " + _connectionUri);

            pass = connectionUri.substring(c1 + 1, c2);
            connectionUri = connectionUri.substring(c2 + 1);
        }

        // is there a database at the end
        int c1 = connectionUri.indexOf("/");
        if (c1 != -1) {
            db = connectionUri.substring(c1 + 1);
            connectionUri = connectionUri.substring(0, c1);
        }

        mongo = MongoDSN.newClient(connectionUri, user, pass, db);

        mdb = mongo.getDatabase(db);
    }

    // Create the collection
    col = mdb.getCollection("sessions");
    setIndexes();
    cfEngine.log(appName + "; SessionStorageMongo: Created " + _connectionUri);
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException {
    this.properties = conf;

    this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true"));

    WriteConcern writeConcern = WriteConcern.MAJORITY;
    String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase();
    if ("majority".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("unacknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.ACKNOWLEDGED;
    } else if ("journaled".equals(writeConcernType)) {
        writeConcern = WriteConcern.JOURNALED;
    } else if ("replica_acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
    }//from  w  w w .ja  v  a2s  .  c  o  m

    ReadPreference readPreference = null;
    String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase();
    if ("primary".equals(readPreferenceType)) {
        readPreference = ReadPreference.primary();
    } else if ("primary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.primaryPreferred();
    } else if ("secondary".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondary();
    } else if ("secondary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondaryPreferred();
    } else if ("nearest".equals(readPreferenceType)) {
        readPreference = ReadPreference.nearest();
    }

    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.writeConcern(writeConcern);
    options.readPreference(readPreference);
    try {
        options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100")));
    } catch (NumberFormatException e) {
        options.connectionsPerHost(100);
    }

    MongoClientURI mongoClientURI = new MongoClientURI(
            conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options);
    if (!this.properties.containsKey("mongodb.database")) {
        if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) {
            this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase());
        } else {
            this.properties.setProperty("mongodb.database", DEFAULT_DATABASE);
        }
    }
    mongoClient = new MongoClient(mongoClientURI);
}

From source file:com.yahoo.ycsb.db3.MongoDbClient.java

License:Open Source License

/**
 * Initialize any state for this DB. Called once per DB instance; there is one
 * DB instance per client thread./*ww w .j  a va2 s . c  o  m*/
 */
@Override
public void init() throws DBException {
    INIT_COUNT.incrementAndGet();
    synchronized (INCLUDE) {
        if (mongoClient != null) {
            return;
        }

        Properties props = getProperties();

        // Set insert batchsize, default 1 - to be YCSB-original equivalent
        batchSize = Integer.parseInt(props.getProperty("batchsize", "1"));

        // Set is inserts are done as upserts. Defaults to false.
        useUpsert = Boolean.parseBoolean(props.getProperty("mongodb.upsert", "false"));

        // Just use the standard connection format URL
        // http://docs.mongodb.org/manual/reference/connection-string/
        // to configure the client.
        String url = props.getProperty("mongodb.url", null);
        boolean defaultedUrl = false;
        if (url == null) {
            defaultedUrl = true;
            url = "mongodb://localhost:27017/ycsb?w=1";
        }

        url = OptionsSupport.updateUrl(url, props);

        if (!url.startsWith("mongodb://")) {
            System.err.println("ERROR: Invalid URL: '" + url + "'. Must be of the form "
                    + "'mongodb://<host1>:<port1>,<host2>:<port2>/database?options'. "
                    + "http://docs.mongodb.org/manual/reference/connection-string/");
            System.exit(1);
        }

        try {
            MongoClientURI uri = new MongoClientURI(url);

            String uriDb = uri.getDatabase();
            if (!defaultedUrl && (uriDb != null) && !uriDb.isEmpty() && !"admin".equals(uriDb)) {
                databaseName = uriDb;
            } else {
                // If no database is specified in URI, use "ycsb"
                databaseName = "ycsb";

            }

            readPreference = uri.getOptions().getReadPreference();
            writeConcern = uri.getOptions().getWriteConcern();

            mongoClient = new MongoClient(uri);
            database = mongoClient.getDatabase(databaseName).withReadPreference(readPreference)
                    .withWriteConcern(writeConcern);

            System.out.println("mongo client connection created with " + url);
        } catch (Exception e1) {
            System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
            e1.printStackTrace();
            return;
        }
    }
}

From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java

License:Apache License

protected DB getConfigDB() {
    Mongo mongo;//from  w w w  .  j a  v a2 s.  c o  m
    MongoClientURI inputURI = MongoConfigUtil.getInputURI(getConfiguration());
    MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration());

    final DBCollection inputCollection;
    if (authURI != null && authURI.getUsername() != null && authURI.getPassword() != null) {
        inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI);
    } else {
        inputCollection = MongoConfigUtil.getCollection(inputURI);
    }

    DB db = inputCollection.getDB();
    mongo = db.getMongo();
    if (authURI != null) {
        if (authURI.getUsername() != null && authURI.getPassword() != null) {
            authDB = mongo.getDB(authURI.getDatabase());
        }
    }

    return mongo.getDB("config");
}