Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

Mongo(final MongoClientURI mongoURI) 

Source Link

Usage

From source file:net.joinedminds.masserr.db.MorphiaProvider.java

License:Open Source License

private void startUp() throws UnknownHostException {
    mongo = new Mongo(dbHost);
    morphia = new Morphia();
    morphia.mapPackage("net.joinedminds.masserr.model", true);
    if (dbUser != null && !dbUser.isEmpty() && dbPasswd != null && !dbPasswd.isEmpty()) {
        datastore = morphia.createDatastore(mongo, dbName, dbUser, dbPasswd.toCharArray());
    } else {/* w  w  w .  j  a  v a2  s  .c o m*/
        datastore = morphia.createDatastore(mongo, dbName);
    }
    datastore.ensureIndexes(); //creates indexes from @Index annotations in your entities
    datastore.ensureCaps(); //creates capped collections from @Entity
}

From source file:net.sf.okapi.lib.tmdb.mongodb.Repository.java

License:Open Source License

public Repository(String connStr) {

    String host = "localhost";

    //--parse the url--
    String[] params = connStr.split("/");
    if (params.length == 1) {
        name = params[0];//  w ww.  j av a2s . c  om
    } else if (params.length > 1) {
        host = params[0];
        name = params[1];
    }

    //--verify--
    if (host == null || host.trim().length() == 0) {
        return;
    }
    if (name == null || name.trim().length() == 0) {
        return;
    }

    try {
        connection = new Mongo(host);
        repository = connection.getDB(name);

        DBCollection repo = repository.getCollection(Repository.REPO_COLL);

        BasicDBObject query = new BasicDBObject();
        query.put("name", name);

        DBObject dbObj = repo.findOne(query);
        if (dbObj == null) {
            BasicDBObject doc = new BasicDBObject();
            doc.put("name", name);
            doc.put("description", "Default Description");
            repo.insert(doc);
            //TODO: Unless description is not used this "REPO" table is not needed
        }

    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    } catch (MongoException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.skyebook.betaville.mongosession.MongoSessionTracker.java

License:Open Source License

/**
 * @throws MongoException //  w  w w  .j a  v  a 2 s. c om
 * @throws UnknownHostException 
 * 
 */
public MongoSessionTracker() throws UnknownHostException, MongoException {
    mongo = new Mongo("localhost");
    database = mongo.getDB("betaville-sessions");
    collection = database.getCollection("sessions");
}

From source file:net.skyebook.padloader.database.MongoImplementation.java

License:Open Source License

/**
 * /*from ww w . j a v a 2  s  . c om*/
 */
public MongoImplementation() {
    try {
        mongo = new Mongo("localhost");
        database = mongo.getDB("property-address-directory");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }

    System.out.println("--Collections--");
    for (String s : database.getCollectionNames()) {
        System.out.println(s);
    }
    System.out.println("--End Collections--");
}

From source file:org.alms.DataAccess.MorphiaMapperSetup.java

License:Open Source License

/**
 * //  w  w w .j  a v  a2s .  c  o  m
 * Implemented a authentication on MongoDB
 * Added a property in configuration to switch "true" / "false" in auth is on 
 * This allows local development and flexibility 
 * 
 * @throws Exception
 */

private void Setup() throws Exception {

    ApplicationConfig c = ApplicationConfig.getApplicationConfig();
    this.m = new Mongo(c.getProperty("DatabaseUrl"));

    Morphia morphia = new Morphia();
    morphia.map(org.alms.beans.UserAccount.class).map(org.alms.beans.MessageInfo.class)
            .map(org.alms.beans.PollMessage.class);

    if (c.getProperty("MongoAuthMode").equals("true")) {
        this.ds = morphia.createDatastore(m, c.getProperty("DataBase"), c.getProperty("MongoUsername"),
                c.getProperty("MongoPassword").toCharArray());
    } else {
        this.ds = morphia.createDatastore(m, c.getProperty("DataBase"));
    }

}

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

License:Apache License

/**
 * Connects to the MongoDB with the supplied credentials.
 * // 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.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);// w ww.j a  v  a  2s  . c om
    } 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.MongoOutputCommitter.java

License:Apache License

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

    /**/*  ww  w .  j  ava 2s  .co 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();
    }
}

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

License:Apache License

public void checkOutputSpecs(FileSystem ignored, JobConf conf) throws IOException {

    if (conf.getBoolean("mongo.output.skip_splitting", false))
        return;/*from  w  w  w  . j a  va 2  s.com*/

    String database = conf.get("mongo.output.database", "");
    if (database.equals("")) {
        throw new IOException("must specify a value for mongo.output.database");
    }

    String collection = conf.get("mongo.output.collection", "");
    if (collection.equals("")) {
        throw new IOException("must supply a value for 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
        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();
    }
}

From source file:org.apache.whirr.service.mongodb.integration.MongoDBServiceController.java

License:Apache License

private void getMongo(InetAddress mongoAddr) throws Exception {
    if (mongo == null || mongo.getAddress() != new ServerAddress(mongoAddr))
        mongo = new Mongo(new ServerAddress(mongoAddr));
    /**/*w  w  w.j a v  a2s .c o  m*/
     * Test the connection...
     */
    mongo.getDB("test").getCollection("whirr_conn_validation").save(new BasicDBObject("foo", "bar"),
            WriteConcern.SAFE);

    LOG.info("Connected to MongoDB Server. ");
}