Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

In this page you can find the example usage for com.mongodb Mongo getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:net.cit.tetrad.rrd.dao.MongoStatusToMonitorImpl.java

License:Open Source License

public CommandResult getCommandResult(Mongo mongo, Device device, String command, String databaseName)
        throws MongoException, Exception {
    CommandResult commandResult = null;//from  w  w  w . j av  a 2  s. c om
    try {
        DB db = mongo.getDB(databaseName);
        commandResult = db.command(command);
    } catch (DataAccessResourceFailureException e) {
        e.printStackTrace();
        throw new MongoException(e.getMessage());
    } catch (MongoException e) {
        // alarm  ?
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {

    }

    return commandResult;
}

From source file:net.cit.tetrad.rrd.dao.MongoStatusToMonitorImpl.java

License:Open Source License

public String getAllServerStatus(Mongo mongo, Device device, String command, String databaseName)
        throws MongoException, Exception {
    String objtoString;//  ww  w .j  ava 2  s .c  o  m
    try {
        DB db = mongo.getDB(databaseName);
        CommandResult commandResult = db.command(command);
        objtoString = commandResult.toString();
    } catch (DataAccessResourceFailureException e) {
        e.printStackTrace();
        throw new MongoException(e.getMessage());
    } catch (MongoException e) {
        // alarm  ?
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {

    }
    return objtoString;
}

From source file:no.pritest.restapi.MongoDBProvider.java

License:Open Source License

private MongoDBProvider() throws MongoException, UnknownHostException {
    Configuration config = new Configuration(PropertiesHolder.getInstance());
    Mongo mongo = new Mongo(config.getDatabaseURL(), config.getDatabasePort());
    db = mongo.getDB(config.getDatabaseName());
}

From source file:org.apache.camel.processor.idempotent.mongodb.MongoDbIdempotentRepository.java

License:Apache License

public void init() {
    try {/* ww w .  jav  a  2 s.  co m*/
        Mongo mongo = new Mongo(host, port);
        db = mongo.getDB(dbName);
        coll = db.getCollection(collectionName);

        // create a unique index on event id key
        coll.ensureIndex(new BasicDBObject(EVENTID, 1), "repo_index", true);

        log.debug("unique index constraint --> " + coll.getIndexInfo());

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.cassandra.db.engine.MongoConfigure.java

License:Apache License

public DB connect(String dbName, String host, int port, String user, String pass) {
    try {/*from w w w .  j  av  a  2s. c  om*/
        Mongo mongo = new Mongo(host, port);
        DB db = mongo.getDB(dbName);
        if (user != null && pass != null)
            if (!db.authenticate(user, pass.toCharArray()))
                throw new Exception("authentication error!!");
        return db;
    } catch (Exception e) {
        System.err.println("can't connect MongoDB [host: " + host + " port:" + port + " user:" + user + "]");
        System.exit(1);
    }
    return null;
}

From source file:org.apache.felix.useradmin.mongodb.MongoDB.java

License:Apache License

/**
 * Connects to the MongoDB with the supplied credentials.
 * //from  w w w.j a va2s .  c o m
 * @param userName the optional user name to use;
 * @param password the optional password to use.
 * @return <code>true</code> if the connection was succesful, <code>false</code> otherwise.
 */
public boolean connect(String userName, String password) {
    Mongo newMongo = new Mongo(m_servers);

    Mongo oldMongo;
    do {
        oldMongo = m_mongoRef.get();
    } while (!m_mongoRef.compareAndSet(oldMongo, newMongo));

    DB db = newMongo.getDB(m_dbName);
    if ((userName != null) && (password != null)) {
        if (!db.authenticate(userName, password.toCharArray())) {
            return false;
        }
    }

    return true;
}

From source file:org.apache.felix.useradmin.mongodb.MongoDB.java

License:Apache License

/**
 * Returns the database collection to work in.
 * /*from   w  w  w. ja v  a  2  s.  com*/
 * @return the {@link DBCollection}, never <code>null</code>.
 * @throws MongoException in case no connection to Mongo exists.
 */
public DBCollection getCollection() {
    Mongo mongo = m_mongoRef.get();
    if (mongo == null) {
        throw new MongoException("Not connected to MongoDB!");
    }
    DB db = mongo.getDB(m_dbName);
    return db.getCollection(m_collectionName);
}

From source file:org.apache.hadoop.contrib.mongoreduce.MongoInputFormat.java

License:Apache License

public static String[] hostsForShard(String shardName, boolean primaryOk)
        throws UnknownHostException, MongoException {

    ArrayList<String> hosts = new ArrayList<String>();

    String[] parts = shardName.split("/");
    if (parts.length == 1) { // no replicas
        hosts.add(shardName);/*from w  w w .  j a va 2 s.  c  o m*/
    } else { // replicas

        // get first or only host listed
        String host = parts[1].split(",")[0];
        Mongo h = new Mongo(host);
        List<ServerAddress> addresses = h.getServerAddressList();
        h.close();
        h = null;

        // only one node in replica set ... - use it
        if (addresses.size() == 1) {
            ServerAddress addr = addresses.get(0);
            hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
        }

        else {
            for (ServerAddress addr : addresses) {

                // use secondaries and primaries
                if (primaryOk) {
                    hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
                }

                // only use secondaries
                else {
                    String haddr = addr.getHost() + ":" + Integer.toString(addr.getPort());
                    h = new Mongo(haddr);
                    if (!(Boolean) h.getDB(h.getDatabaseNames().get(0)).command(cmd).get("ismaster")) {
                        hosts.add(haddr);
                    }
                }
            }
        }
    }

    return hosts.toArray(new String[0]);
}

From source file:org.apache.hadoop.contrib.mongoreduce.MongoInputFormat.java

License:Apache License

@Override
public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {

    Configuration conf = context.getConfiguration();

    ArrayList<InputSplit> splits = new ArrayList<InputSplit>();

    // in single testing mode we just hit the local db
    boolean singleTestingMode = conf.getBoolean("mongo.single.testing", false);
    if (singleTestingMode) {
        String[] hosts = { "localhost:27017" };
        splits.add(new MongoInputSplit(hosts));

        return splits;
    }//from  www. j a v  a  2  s  .co  m

    boolean primaryOk = conf.getBoolean("mongo.input.primary_ok", false);

    // connect to global mongo through a mongos process
    Mongo m = new Mongo("localhost", 27017);

    // get a list of all shards and their hosts
    // TODO: add notification if config db not found / db is not sharded
    DB configdb = m.getDB("config");
    DBCollection shards = configdb.getCollection("shards");

    // we need to query/read/process each shard once
    for (DBObject shard : shards.find()) {

        System.out.println("adding shard" + shard.toString());

        String[] hosts = hostsForShard((String) shard.get("host"), primaryOk);
        for (String host : hosts)
            System.out.print(host + " ");
        System.out.println();

        InputSplit split = new MongoInputSplit(hosts);
        splits.add(split);
    }

    return splits;
}

From source file:org.apache.hadoop.contrib.mongoreduce.MongoOutputCommitter.java

License:Apache License

@Override
public void setupJob(JobContext jobContext) throws IOException {

    /**//from   w  ww .j a  va2s  .c o  m
     * note: we don't really have to do anything here -
     * MongoDB is one of the few systems that don't require you to
     * create a database or collection before writing to it
     * 
     * but in order to ingest a ton of data quickly we have to 
     * pre-split the output collection
     *
     */

    Configuration conf = jobContext.getConfiguration();
    if (conf.getBoolean("mongo.output.skip_splitting", false))
        return;

    String database = conf.get("mongo.output.database");
    String collection = conf.get("mongo.output.collection");

    // connect to global db
    Mongo m = new Mongo("localhost");
    DB db = m.getDB(database);
    DB admindb = m.getDB("admin");
    DB configdb = m.getDB("config");

    // optionally drop the existing collection
    boolean drop = conf.getBoolean("mongo.output.drop", false);
    DBCollection coll = db.getCollection(collection);
    if (drop) {
        coll.drop();
    } else {
        if (coll.count() > 0) {
            // don't shard an existing collection - may already be sharded ...
            return;
        }
    }

    // get a list of shards
    ArrayList<String> shards = new ArrayList<String>();
    for (DBObject s : configdb.getCollection("shards").find()) {
        shards.add((String) s.get("_id"));
    }

    if (shards.size() < 2) {
        // don't let's be silly - nice sharded cluster, no shard
        return;
    }

    // shard the new output collection
    BasicDBObjectBuilder builder = new BasicDBObjectBuilder();
    builder.add("enableSharding", database);
    admindb.command(builder.get());

    builder = new BasicDBObjectBuilder();
    builder.add("shardCollection", database + "." + collection);

    // just shard on _id - but user gets to decide what the _id is
    builder.add("key", new BasicDBObject("_id", 1));
    admindb.command(builder.get());

    // pre-split to get parallel writes
    // this http://www.mongodb.org/display/DOCS/Splitting+Chunks says 
    // balancer moving chunks should take 5 minutes ... too long
    // wonder if moveChunk command is faster
    // well we could do it anyway - the jobs that can benefit from it will

    // check for user-submitted splitPoints
    String[] splits;
    String splitString = conf.get("mongo.output.split_points", "");

    // generate our own split points if necessary
    if (splitString.equals("")) {
        long max = (long) Math.pow(93.0, 5.0);

        long step = max / shards.size();
        splits = new String[shards.size() - 1];

        // assume human readable keys
        for (int i = 0; i < shards.size() - 1; i++) {
            splits[i] = splitPointForLong(step * (i + 1));
        }
    } else {
        splits = splitString.split(",");
    }

    HashMap<String, Object> splitCmd = new HashMap<String, Object>();
    splitCmd.put("split", database + "." + collection);
    splitCmd.put("middle", "");

    HashMap<String, Object> moveCmd = new HashMap<String, Object>();
    moveCmd.put("moveChunk", database + "." + collection);
    moveCmd.put("find", "");
    moveCmd.put("to", "");

    // do the splitting and migrating
    // we assign chunks to shards in a round-robin manner
    int i = 0;
    for (String split : splits) {

        splitCmd.remove("middle");
        splitCmd.put("middle", new BasicDBObject("_id", split));

        // create new chunk
        admindb.command(new BasicDBObject(splitCmd));

        // move to shard
        moveCmd.remove("find");
        moveCmd.put("find", new BasicDBObject("_id", split));
        moveCmd.put("to", shards.get(i));

        admindb.command(new BasicDBObject(moveCmd));

        i = (i + 1) % shards.size();
    }
}