Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

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

License:Apache License

public void editUser(ButtonBase button) {
    final DB db = getDbNode().getDb();
    final DBCollection col = db.getCollection("system.users");

    final String user = getComponentStringFieldValue(Item.userList);
    if (user == null) {
        return;//from   w ww.jav a 2  s  . c o m
    }

    final BasicDBObject userObj = (BasicDBObject) col.findOne(new BasicDBObject("user", user));
    UserDialog ud = (UserDialog) getBoundUnit(Item.userDialog);
    ud.resetForEdit(userObj);
    if (!ud.show()) {
        return;
    }

    final BasicDBObject newUser = ud.getUser(userObj);

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            return col.save(newUser);
        }

        @Override
        public String getNS() {
            return col.getName();
        }

        @Override
        public String getShortName() {
            return "Edit User";
        }

        @Override
        public void wrapUp(Object res) {
            super.wrapUp(res);
            refreshUserList();
        }
    }.addJob();

}

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

License:Apache License

public static DBObject getReplicaSetInfo(MongoClient mongo) {
    DB db = mongo.getDB("local");
    DBObject result = new BasicDBObject();
    DBCollection namespaces = db.getCollection("system.namespaces");
    String oplogName;// www .j  a  va2  s. co  m
    if (namespaces.findOne(new BasicDBObject("name", "local.oplog.rs")) != null) {
        oplogName = "oplog.rs";
    } else if (namespaces.findOne(new BasicDBObject("name", "local.oplog.$main")) != null) {
        oplogName = "oplog.$main";
    } else {
        return null;
    }
    DBObject olEntry = namespaces.findOne(new BasicDBObject("name", "local." + oplogName));
    if (olEntry != null && olEntry.containsField("options")) {
        BasicDBObject options = (BasicDBObject) olEntry.get("options");
        long size = options.getLong("size");
        result.put("logSizeMB", Float.valueOf(String.format("%.2f", size / 1048576f)));
    } else {
        return null;
    }
    DBCollection oplog = db.getCollection(oplogName);
    int size = oplog.getStats().getInt("size");
    result.put("usedMB", Float.valueOf(String.format("%.2f", size / 1048576f)));

    DBCursor firstc = oplog.find().sort(new BasicDBObject("$natural", 1)).limit(1);
    DBCursor lastc = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);
    if (!firstc.hasNext() || !lastc.hasNext()) {
        return null;
    }
    BasicDBObject first = (BasicDBObject) firstc.next();
    BasicDBObject last = (BasicDBObject) lastc.next();
    BSONTimestamp tsfirst = (BSONTimestamp) first.get("ts");
    BSONTimestamp tslast = (BSONTimestamp) last.get("ts");
    if (tsfirst == null || tslast == null) {
        return null;
    }

    int ftime = tsfirst.getTime();
    int ltime = tslast.getTime();
    int timeDiffSec = ltime - ftime;
    result.put("timeDiff", timeDiffSec);
    result.put("timeDiffHours", Float.valueOf(String.format("%.2f", timeDiffSec / 3600f)));
    result.put("tFirst", new Date(ftime * 1000l));
    result.put("tLast", new Date(ltime * 1000l));
    result.put("now", new Date());
    return result;
}

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

License:Apache License

public static boolean isBalancerOn(MongoClient mongo) {
    final DB config = mongo.getDB("config");
    final DBCollection settings = config.getCollection("settings");
    BasicDBObject res = (BasicDBObject) settings.findOne(new BasicDBObject("_id", "balancer"));
    if (res == null || !res.containsField("stopped"))
        return true;
    return !res.getBoolean("stopped");
}

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

License:Apache License

public void balancer(ButtonBase button) {
    final MongoClient mongo = getRouterNode().getMongoClient();
    final DB config = mongo.getDB("config");
    final DBCollection settings = config.getCollection("settings");

    FormDialog diag = (FormDialog) ((MenuItem) getBoundUnit(Item.balancer)).getDialog();
    diag.xmlLoadCheckpoint();/*w w w .  ja v a 2  s.co m*/

    final BasicDBObject query = new BasicDBObject("_id", "balancer");
    BasicDBObject balDoc = (BasicDBObject) settings.findOne(query);
    if (balDoc != null) {
        if (balDoc.containsField("stopped"))
            setIntFieldValue(Item.balStopped, balDoc.getBoolean("stopped") ? 1 : 2);
        if (balDoc.containsField("_secondaryThrottle"))
            setIntFieldValue(Item.balSecThrottle, balDoc.getBoolean("_secondaryThrottle") ? 1 : 2);
        BasicDBObject window = (BasicDBObject) balDoc.get("activeWindow");
        if (window != null) {
            setStringFieldValue(Item.balStartTime, window.getString("start"));
            setStringFieldValue(Item.balStopTime, window.getString("stop"));
        }
    }

    if (!diag.show())
        return;

    if (balDoc == null)
        balDoc = new BasicDBObject("_id", "balancer");
    int stopped = getIntFieldValue(Item.balStopped);
    if (stopped > 0)
        balDoc.put("stopped", stopped == 1 ? true : false);
    else
        balDoc.removeField("stopped");
    int throttle = getIntFieldValue(Item.balSecThrottle);
    if (throttle > 0)
        balDoc.put("_secondaryThrottle", throttle == 1 ? true : false);
    else
        balDoc.removeField("_secondaryThrottle");

    if (!getStringFieldValue(Item.balStartTime).trim().isEmpty()) {
        BasicDBObject aw = new BasicDBObject();
        aw.put("start", getStringFieldValue(Item.balStartTime).trim());
        aw.put("stop", getStringFieldValue(Item.balStopTime).trim());
        balDoc.put("activeWindow", aw);
    }
    final BasicDBObject newDoc = balDoc;

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            return settings.update(query, newDoc, true, false);
        }

        @Override
        public String getNS() {
            return settings.getFullName();
        }

        @Override
        public String getShortName() {
            return "Balancer";
        }

        @Override
        public void wrapUp(Object res) {
            updateComponent();
            super.wrapUp(res);
        }
    }.addJob();
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void getChunk(Message<JsonObject> message, final JsonObject jsonObject) {

    ObjectId id = getObjectId(message, jsonObject, "files_id");

    Integer n = getRequiredInt("n", message, jsonObject, 0);
    if (n == null) {
        return;//from w w w  .ja v a  2  s  .  c  om
    }

    String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);

    DBCollection collection = db.getCollection(bucket + ".chunks");
    DBObject dbObject = BasicDBObjectBuilder.start("files_id", id).add("n", n).get();

    DBObject result = collection.findOne(dbObject);

    if (result == null) {
        message.reply(new byte[0]);
        return;
    }

    byte[] data = (byte[]) result.get("data");
    boolean reply = jsonObject.getBoolean("reply", false);
    Handler<Message<JsonObject>> replyHandler = null;

    if (reply) {
        replyHandler = new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> reply) {
                int n = jsonObject.getInteger("n") + 1;
                jsonObject.putNumber("n", n);
                getChunk(reply, jsonObject);
            }
        };
    }

    // TODO: Change to reply with a Buffer instead of a byte[]?
    message.reply(data, replyHandler);

}

From source file:com.gigaspaces.persistency.MongoSpaceDataSource.java

License:Open Source License

@Override
public Object getById(DataSourceIdQuery idQuery) {

    if (logger.isDebugEnabled())
        logger.debug("MongoSpaceDataSource.getById(" + idQuery + ")");

    SpaceDocumentMapper<DBObject> mapper = new DefaultSpaceDocumentMapper(idQuery.getTypeDescriptor());

    BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY,
            mapper.toObject(idQuery.getId()));

    DBCollection mongoCollection = mongoClient.getCollection(idQuery.getTypeDescriptor().getTypeName());

    DBObject result = mongoCollection.findOne(documentBuilder.get());

    return mapper.toDocument(result);

}

From source file:com.groupon.jenkins.mongo.MongoRepository.java

License:Open Source License

protected DBObject findOne(BasicDBObject query) {
    MongoClient client = getClient();//  w w w  .  j  av a  2 s . c  o m
    try {
        DBCollection collection = getCollection(client);
        return collection.findOne(query);
    } finally {
        client.close();
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * objectid find document// www .  j  av a 2 s. co  m
 * 
 * @param userDB
 * @param colName
 * @param objectId
 * @throws Exception
 */
public static DBObject findDocument(UserDBDAO userDB, String colName, String objectId) throws Exception {
    DBCollection collection = findCollection(userDB, colName);
    DBObject queryObj = new BasicDBObject("_id", new ObjectId(objectId));

    return collection.findOne(queryObj);
}

From source file:com.ibm.db2j.MongoDB.java

License:Open Source License

/**
 * This method sends a request to a mongoDB instance, reads the data returned by the 
 * web service, and determines which columns  can represent the 
 * associated logical table. It also writes the necessary properties into the 
 * gaian property file in order to query the logical table later on.
 * //from www. ja v  a  2s  .c  o  m
 * @param ltName - Name of the generated logical table.
 * @param url - Url accessing the mongo process. 
 *       Expected format: {user}:{password}@{MongoURL}:{Port}/{Database}/{Collection}
 *       The {user}:{password}@ portion is optional, and implies that authentication is required.           
 * @param fields -    an optional list of fields to be extracted for the logical table.
 * @throws Exception on some sub-method failure.
 */
public static synchronized void setLogicalTableForMongoDB(String ltName, String url, String fields)
        throws Exception {

    ltName = ltName.toUpperCase();

    logger.logInfo("Obtaining tableDef for mongo process: " + url);

    MongoConnectionParams connDetails = new MongoConnectionParams(url);

    DBCollection mongoCollection = MongoConnectionFactory.getMongoCollection(connDetails);

    // If we get this far without exception then the connection parameters must all be valid. Now work out the logical table definition.

    String ltDef = "";

    DBObject mongoResult;
    if (fields == null || fields == "") {
        mongoResult = mongoCollection.findOne(QUERY_ANYTHING); //retrieves just the first row

    } else {
        BasicDBObject keys = new BasicDBObject();
        for (String field : fields.split(",")) {
            keys.put(field.trim(), 1);
        }
        mongoResult = mongoCollection.findOne(QUERY_ANYTHING, keys); //retrieves just the first row matching the "keys"

    }

    if (mongoResult != null) {
        ltDef = generateLTDefFromMongoDocument(mongoResult);
    }

    // Logical Table properties
    Map<String, String> ltProperties = GaianDBConfigProcedures.prepareLogicalTable(ltName, ltDef, "");

    // Data Source Definition properties
    ltProperties.put(ltName + "_DS0_ARGS",
            ltName + "conf, " + connDetails.getDatabaseName() + ", " + connDetails.getCollectionName());
    ltProperties.put(ltName + "_DS0_VTI", MongoDB.class.getName());

    // VTI definition properties
    String vtiPropertiesPrefix = MongoDB.class.getSimpleName() + "." + ltName + "conf.";

    ltProperties.put(vtiPropertiesPrefix + "schema", ltDef);
    ltProperties.put(vtiPropertiesPrefix + PROP_ADDRESS, connDetails.getHostAddress());
    ltProperties.put(vtiPropertiesPrefix + PROP_PORT, connDetails.getHostPort().toString());
    ltProperties.put(vtiPropertiesPrefix + PROP_DB_NAME, "$0"); // $0 is a replacement token to get the config to the DS0_ARGS field
    ltProperties.put(vtiPropertiesPrefix + PROP_COLLECTION_NAME, "$1");// $0 is a replacement token to get the config to the DS0_ARGS field

    // Note that if user or password is null, any existing key will be deleted, which is what we want to happen.
    ltProperties.put(vtiPropertiesPrefix + PROP_USER, connDetails.getUserName());
    ltProperties.put(vtiPropertiesPrefix + PROP_PASSWORD, connDetails.getPassword());

    // Now actually update and save the configuration.
    GaianDBConfigProcedures.setConfigProperties(ltProperties);
    //      GaianDBConfigProcedures.persistAndApplyConfigUpdates(ltProperties);

    // The following call ensures that the configuration is fully loaded 
    // and we are ready to query the table. Without this, an immediate call 
    // to query the table can fail.
    DataSourcesManager.checkUpdateLogicalTableViewsOnAllDBs();

    MongoConnectionFactory.closeMongoCollection(mongoCollection);
}

From source file:com.ijuru.ijambo.dao.PlayerDAO.java

License:Open Source License

/**
 * Gets the specified player/*from ww w .ja  v a  2 s .c  o m*/
 * @param identifier the player identifier
 * @return the player
 */
public Player getPlayer(String identifier) {
    DBCollection players = db.getCollection("players");

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

    BasicDBObject obj = (BasicDBObject) players.findOne(query);
    if (obj != null)
        return new Player(obj.getString("identifier"), obj.getString("prevAnswer"));
    else
        return null;
}