Example usage for com.mongodb DBCollection getStats

List of usage examples for com.mongodb DBCollection getStats

Introduction

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

Prototype

public CommandResult getStats() 

Source Link

Document

The collStats command returns a variety of storage statistics for a given collection

Usage

From source file:com.andreig.jetty.CollectionsServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/* w w  w. j a va  2s. co m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String op = req.getParameter("op");
    if (db_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
        }
        if (db_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    if (op == null)
        op = "list";

    DB db = mongo.getDB(db_name);

    if ("list".equals(op)) {
        Set<String> cols = db.getCollectionNames();
        out_json(req, cols);
        return;
    }

    // requires colname
    String col_name = req.getParameter("colname");
    if (col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    DBCollection col = db.getCollection(col_name);

    if ("count".equals(op)) {
        out_str(req, "{\"count\":" + col.count() + "}", "application/json");
    } else if ("stats".equals(op)) {
        BasicBSONObject o = col.getStats();
        out_str(req, o.toString(), "application/json");
        return;
    } else
        res.sendError(SC_BAD_REQUEST);

}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private void fetchAndPrintCollectionStats() {
    for (String databaseName : mongoClient.listDatabaseNames()) {
        DB db = mongoClient.getDB(databaseName);
        Set<String> collectionNames = db.getCollectionNames();
        if (collectionNames != null && collectionNames.size() > 0) {
            for (String collectionName : collectionNames) {
                DBCollection collection = db.getCollection(collectionName);
                CommandResult collectionStatsResult = collection.getStats();
                if (collectionStatsResult != null && collectionStatsResult.ok()) {
                    DBObject collectionStats = (DBObject) JSON.parse(collectionStatsResult.toString());
                    printCollectionStats(db.getName(), collectionName, collectionStats);
                } else {
                    String errorMessage = "Retrieving stats for collection " + collectionName + " of "
                            + db.getName() + " failed";
                    if (collectionStatsResult != null) {
                        errorMessage = errorMessage
                                .concat(" with error message " + collectionStatsResult.getErrorMessage());
                    }//www  . jav a 2s . co m
                    logger.error(errorMessage);
                }
            }
        }
    }
}

From source file:com.cyslab.craftvm.rest.mongo.CollectionsServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/* www  .  j a  va  2  s.  c o m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String op = req.getParameter("op");
    if (db_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
        }
        if (db_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    if (op == null)
        op = "list";

    DB db = mongo.getDB(db_name);

    if ("list".equals(op)) {
        Set<String> cols = db.getCollectionNames();
        out_json(req, cols);
        return;
    }

    // requires colname
    String col_name = req.getParameter("colname");
    if (col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    DBCollection col = db.getCollection(col_name);

    if ("count".equals(op)) {
        out_str(req, "{\"count\":" + col.count() + "}", "application/json");
    } else if ("stats".equals(op)) {
        BasicBSONObject o = col.getStats();
        out_str(req, o.toString(), "application/json");
        return;
    } else
        res.sendError(SC_BAD_REQUEST);

}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

@Override
public int getCollectionCount(String dbCollectionName) {
    CheckConditions.checkNotNull(dbCollectionName, "Collection name can't be null!");
    Integer count = cacheManager.getCountFromCache(dbCollectionName);
    if (count == null) {
        DBCollection col = this.mongo.getDB(repo.getRepositoryName()).getCollection(dbCollectionName);
        // read from primary only
        col.setReadPreference(ReadPreference.primary());
        col.setWriteConcern(WriteConcern.SAFE);

        count = (Integer) col.getStats().get("count");
        if (count == null) {
            count = 0;/*from  w ww . ja v  a 2 s  . c om*/
        } else {
            cacheManager.putCountToCache(dbCollectionName, count);
        }
    }
    return count;
}

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;//from w  ww . ja  v  a2s.  c  o  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.ReplSetPanel.java

License:Apache License

public void compareReplicas(ButtonBase button) {
    final String stat = getStringFieldValue(Item.crStat);
    new DbJob() {

        @Override//from  ww  w  .java 2s.co  m
        public Object doRun() {
            ReplSetNode node = getReplSetNode();
            if (!node.hasChildren())
                return null;

            ArrayList<MongoClient> svrs = new ArrayList<MongoClient>();
            for (XmlUnit unit : node.getChildren()) {
                ServerNode svr = (ServerNode) unit;
                MongoClient svrm = svr.getServerMongoClient();
                try {
                    svrm.getDatabaseNames();
                } catch (Exception e) {
                    continue;
                }
                svrs.add(svrm);
            }

            BasicDBObject res = new BasicDBObject();
            MongoClient m = getReplSetNode().getMongoClient();
            for (String dbname : m.getDatabaseNames()) {
                DB db = m.getDB(dbname);
                BasicDBObject dbres = new BasicDBObject();
                for (String colname : db.getCollectionNames()) {
                    DBCollection col = db.getCollection(colname);
                    BasicDBObject colres = new BasicDBObject();
                    BasicDBObject values = new BasicDBObject();
                    boolean same = true;
                    long ref = -1;
                    for (MongoClient svrm : svrs) {
                        DBCollection svrcol = svrm.getDB(dbname).getCollection(colname);
                        long value = 0;
                        if (stat.startsWith("Count")) {
                            value = svrcol.count();
                        } else if (stat.startsWith("Data Size")) {
                            CommandResult stats = svrcol.getStats();
                            value = stats.getLong("size");
                        }
                        values.append(svrm.getConnectPoint(), value);
                        if (ref < 0)
                            ref = value;
                        else if (ref != value)
                            same = false;
                    }
                    if (!same) {
                        colres.append("values", values);
                        dbres.append(colname, colres);
                    }
                }
                if (!dbres.isEmpty()) {
                    res.append(dbname, dbres);
                }
            }

            return res;
        }

        @Override
        public String getNS() {
            return "*";
        }

        @Override
        public String getShortName() {
            return "Compare Replicas";
        }
    }.addJob();
}

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

License:Open Source License

/**
 * coll stats// w  w w.j ava 2  s.  com
 * 
 * @param userDB
 * @param colName
 * @return
 * @throws Exception
 */
public static String getCollStats(UserDBDAO userDB, String colName) throws Exception {
    DBCollection collection = findCollection(userDB, colName);

    CommandResult cr = collection.getStats();
    if (cr.ok()) {
        return cr.toString();
    } else {
        throw cr.getException();
    }
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestProfilling.java

License:Open Source License

/**
 * @param args//  w w  w  .j a v  a 2 s  . c om
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    // ??       
    System.out.println("####[profilling  ]######################################################");
    CommandResult cr = db.command(new BasicDBObject("profile", 0));

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + JSONUtil.getPretty(cr.toString()));
    System.out.println("[size]" + cr.size());
    System.out.println("####[profilling  ]######################################################");

    //  ?          
    System.out.println(
            "####[profilling collections  ]######################################################");
    if (db.collectionExists("system.profile")) {
        DBCollection profileColl = db.getCollection("system.profile");
        profileColl.drop();
    }
    System.out.println(
            "####[profilling collections  ]######################################################");
    //  ?     

    // system.profile collection ? 
    System.out.println(
            "####[profilling collections ? ]######################################################");
    DBObject dbObject = (DBObject) JSON.parse("{capped:true, size:8000000}");
    DBCollection dbColl = db.createCollection("system.profile", dbObject);
    BasicDBObject newProfileColl = (BasicDBObject) dbColl.getStats().copy();
    System.out.println(
            "####[profilling collections ? ]######################################################");
    // system.profile collection ? 

    System.out.println("####[profilling ]######################################################");
    cr = db.command(new BasicDBObject("profile", 2));

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + JSONUtil.getPretty(cr.toString()));
    System.out.println("[size]" + cr.size());
    System.out.println("####[profilling ]######################################################");

    //      //#######################################################################################################
    //      //#######################################################################################################
    //      //#######################################################################################################      
    System.out.println("####[start profilling result]######################################################");
    DBCollection myColl = db.getCollection("system.profile");

    BasicDBObject query = new BasicDBObject();
    query.put("millis", new BasicDBObject("$gt", 4));

    DBCursor myCursor = myColl.find();
    while (myCursor.hasNext()) {
        DBObject dbObj = myCursor.next();
        System.out.println(dbObj.get("ts") + " - " + dbObj.get("ns") + " - " + dbObj.get("nscanned") + "/"
                + dbObj.get("nreturned") + " millis :" + dbObj.get("millis"));
    }
    System.out.println("####[end profilling result]######################################################");

    mongo.close();
}

From source file:com.nec.strudel.tkvs.store.mongodb.MongodbLifecycle.java

License:Apache License

@Override
public void prepare() {
    showBalancerLock();//  w  w w. j a v a2s.  c o m
    int sleepSec = getIntOpt(PROP_SLEEP_AFTER_SEC, 0);
    if (sleepSec > 0) {
        LOGGER.info("sleeping " + sleepSec + " seconds...");
        sleep(sleepSec);
        LOGGER.info("sleeping done.");
        showBalancerLock();
    }
    DB db = mongoClient.getDB(dbName);
    LOGGER.info("getting DB stats: " + dbName);
    CommandResult res = db.getStats();
    if (res.ok()) {
        LOGGER.info("DB stats OK: " + res);
    } else {
        LOGGER.warn("DB stats NG: " + res);
    }
    DBCollection coll = db.getCollection(dbName);
    LOGGER.info("getting Collection stats: " + dbName);
    res = coll.getStats();
    if (res.ok()) {
        LOGGER.info("Collection stats OK: " + res);
    } else {
        LOGGER.warn("Collection stats NG: " + res);
    }
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void getCollectionStats(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);

    if (collection == null) {
        return;//ww  w  .ja va 2  s  .c om
    }

    DBCollection coll = db.getCollection(collection);
    CommandResult stats = coll.getStats();

    JsonObject reply = new JsonObject();
    reply.putObject("stats", new JsonObject(stats.toMap()));
    sendOK(message, reply);

}