Example usage for com.mongodb CommandResult get

List of usage examples for com.mongodb CommandResult get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:example.springdata.mongodb.util.RequiresMongoDB.java

License:Apache License

private void initCurrentVersion() {

    if (currentVersion == null) {
        try {//from w ww.  j a  v a 2 s . co m
            MongoClient client;
            client = new MongoClient(host, port);
            DB db = client.getDB("test");
            CommandResult result = db.command(new BasicDBObjectBuilder().add("buildInfo", 1).get());
            this.currentVersion = Version.parse(result.get("version").toString());
        } catch (com.mongodb.MongoTimeoutException | UnknownHostException e) {
            throw new AssumptionViolatedException("Seems as mongodb server is not running.", e);
        }
    }

}

From source file:ezbake.data.mongo.HandlerForDriverFindCalls.java

License:Apache License

private QueryResultIterator handleDistinctCall(DBObject jsonQuery, ReadPreference readPref,
        EzSecurityToken token, AggregationOptions opts, Object distinct, Object key, List<DBObject> pipeline)
        throws Exception {
    Cursor cursor;//from  w w  w .  j a  va2 s .co  m
    QueryResultIterator qri;// make a agg call to get a QueryResultIterator instance
    cursor = parent_handler.handler.db.getCollection(distinct.toString()).aggregate(pipeline, opts, readPref);
    if (cursor instanceof QueryResultIterator) {
        qri = (QueryResultIterator) cursor;
    } else {
        appLog.info("UNKNOWN CURSOR RETURNED FOR distinct: {}", cursor.toString());
        throw new Exception("distinct converted to Aggregate pipeline did not return a QueryResultIterator: "
                + cursor.toString());
    }

    // add $out to pipeline and call it again
    String outCollectionForDistinct = "out_" + randomAlphanumeric(8);
    pipeline.add(new BasicDBObject("$out", outCollectionForDistinct));
    DBCursor c = (DBCursor) parent_handler.handler.db.getCollection(distinct.toString()).aggregate(pipeline,
            opts, readPref);

    // call distinct on previously redacted result collection
    CommandResult cr = parent_handler.handler.db.getCollection(outCollectionForDistinct)
            .distinct(key.toString(), jsonQuery, true);

    // assemble results as per the driver paradigm
    List<DBObject> l = new ArrayList<>();
    BasicDBObject obj = new BasicDBObject();
    obj.put("values", (cr.get("values")));
    obj.put("stats", (cr.get("stats")));
    obj.put("ok", (cr.get("ok")));

    l.add(obj);
    qri.setIterator(l.iterator());
    qri.setCurSize(1);

    List<Integer> sizes = new ArrayList<>();
    sizes.add(1);
    qri.set_sizes(sizes);

    // drop the tmp output collection
    parent_handler.handler.db.getCollection(outCollectionForDistinct).drop();
    return qri;
}

From source file:flipkart.mongo.node.discovery.mock.model.MockClusterModel.java

License:Apache License

public static void mockForUnknownState(CommandResult commandResult) {
    when(commandResult.get("members")).thenReturn(new MockDBObjects().withPrimaryState("UNKNOWN").mock());
}

From source file:flipkart.mongo.node.discovery.mock.model.MockClusterModel.java

License:Apache License

public static void withShardName(CommandResult commandResult) {
    when(commandResult.get("set")).thenReturn(MockReplicaSetModel.MOCK_SHARD_NAME);
}

From source file:flipkart.mongo.node.discovery.mock.model.MockReplicaSetModel.java

License:Apache License

public static CommandResult mockMongoResult() {
    CommandResult commandResult = mock(CommandResult.class);
    when(commandResult.get("members")).thenReturn(new MockDBObjects().mock());
    return commandResult;
}

From source file:net.cit.tetrad.dao.management.impl.SubDaoImpl.java

License:Open Source License

public Object getAccumResult(CommonDto dto) {
    dhtmlxLogger.info("start getAccumResult");
    long start = System.currentTimeMillis();
    List<BasicDBObject> pipeline = commonQuery(dto);

    DBObject groupKey = new BasicDBObject("defaultGroupKey", "$groupkey1");
    groupKey.put("groupKey2", "$groupkey2");
    DBObject group = new BasicDBObject("_id", groupKey);

    DBObject colcounter = new BasicDBObject("$sum", 1);
    DBObject colfirst = new BasicDBObject("$first", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject collast = new BasicDBObject("$last", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject regtime = new BasicDBObject("$first", "$regtime");

    group.put("colcounter", colcounter);
    group.put("colfirst", colfirst);
    group.put("collast", collast);
    group.put("regtime", regtime);

    DBObject finalSort = new BasicDBObject("_id", 1);

    DBObject resultProject = new BasicDBObject();
    resultProject.put("couter", "$colcounter");
    resultProject.put("first", "$colfirst");
    resultProject.put("last", "$collast");
    resultProject.put("diff", new BasicDBObject("$subtract", Arrays.asList("$collast", "$colfirst")));
    resultProject.put("regtime", "$regtime");

    DBObject finalProject = new BasicDBObject();
    finalProject.put("avg", new BasicDBObject("$divide", Arrays.asList("$diff", "$couter")));
    finalProject.put("point", "$last");
    finalProject.put("diff", "$diff");
    finalProject.put("regtime", "$regtime");

    pipeline.add(new BasicDBObject("$group", group));
    pipeline.add(new BasicDBObject("$sort", finalSort));
    pipeline.add(new BasicDBObject("$project", resultProject));
    pipeline.add(new BasicDBObject("$project", finalProject));

    DBObject cmdBody = new BasicDBObject("aggregate", dto.getCollname());
    cmdBody.put("pipeline", pipeline);

    CommandResult result = monadService.command(cmdBody);
    long end = System.currentTimeMillis();
    dhtmlxLogger.info("    accum aggregation : " + (end - start));
    dhtmlxLogger.info("    accum aggregation query : " + cmdBody);
    dhtmlxLogger.info("end getAccumResult");
    return result.get("result");
}

From source file:net.cit.tetrad.dao.management.impl.SubDaoImpl.java

License:Open Source License

public Object getCurrentResult(CommonDto dto) {
    dhtmlxLogger.info("start getCurrentResult");
    long start = System.currentTimeMillis();
    List<BasicDBObject> pipeline = commonQuery(dto);

    DBObject groupKey = new BasicDBObject("defaultGroupKey", "$groupkey1");
    groupKey.put("groupKey2", "$groupkey2");

    DBObject group = new BasicDBObject("_id", groupKey);
    DBObject colsum = new BasicDBObject("$sum", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject colavg = new BasicDBObject("$avg", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject colfirst = new BasicDBObject("$first", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject collast = new BasicDBObject("$last", new BasicDBObject("$ifNull", Arrays.asList("$dsname", 0)));
    DBObject regtime = new BasicDBObject("$first", "$regtime");

    group.put("colsum", colsum);
    group.put("colavg", colavg);
    group.put("colfirst", colfirst);
    group.put("collast", collast);
    group.put("regtime", regtime);

    DBObject finalSort = new BasicDBObject("_id", 1);

    DBObject resultProject = new BasicDBObject();
    resultProject.put("avg", "$colavg");
    resultProject.put("point", "$collast");
    resultProject.put("regtime", "$regtime");
    resultProject.put("diff", new BasicDBObject("$subtract", Arrays.asList("$collast", "$colfirst")));

    pipeline.add(new BasicDBObject("$group", group));
    pipeline.add(new BasicDBObject("$sort", finalSort));
    pipeline.add(new BasicDBObject("$project", resultProject));

    DBObject cmdBody = new BasicDBObject("aggregate", dto.getCollname());
    cmdBody.put("pipeline", pipeline);
    CommandResult result = monadService.command(cmdBody);
    long end = System.currentTimeMillis();
    dhtmlxLogger.info("    current aggregation : " + (end - start));
    dhtmlxLogger.info("    current aggregation query : " + cmdBody);
    dhtmlxLogger.info("end getCurrentResult");
    return result.get("result");
}

From source file:net.cit.tetrad.rrd.service.TetradRrdDbServiceImpl.java

License:Open Source License

/**
 * ??? ?  rrdDb?  ?.//w  w w.  j av  a  2 s .c  om
 * @param device
 * @param databaseName
 */
public Map<String, Object> insertTetradRrdDb(Mongo mongo, Device device, String databaseName,
        CommandResult serverResult) throws FileNotFoundException {
    Map<String, Object> dbStatus = new HashMap<String, Object>();

    try {
        // ??? ?  ?
        dbStatus = mongoStatusToMonitor.readMongoStatus(mongo, device, DB_STATUS_COMMAND, databaseName);

        if (serverResult.get("process").equals(PROCESS_MONGOS)) {
            double collCnt = 0;
            Set<String> collNameLst = mongoStatusToMonitor.readMongoCollectionName(mongo, databaseName);
            if (collNameLst != null && collNameLst.size() != 0)
                collCnt = collNameLst.size() + 1;
            dbStatus.put("collections", collCnt);
        }

        dbStatus.put(SERVERSTATUS_REGTIME, TimestampUtil.readCurrentTime());
        dbStatus.put(DBSTATUS_DIFF_DATASIZE, dbStatus.get("dataSize"));
        dbStatus.put(DBSTATUS_DIFF_INDEXSIZE, dbStatus.get("indexSize"));

        DBObject locks = (DBObject) serverResult.get("locks");
        if (locks != null) {
            DBObject dbLocks = (DBObject) locks.get(databaseName);
            JasonUtil.getEntryValue(dbLocks, "locks_", dbStatus);
        }
        DBObject recordStats = (DBObject) serverResult.get("recordStats");
        if (recordStats != null) {
            DBObject dbRecordStats = (DBObject) recordStats.get(databaseName);
            JasonUtil.getEntryValue(dbRecordStats, "recordStats_", dbStatus);
        }

        InitialRrdService rrdSvc = new InitialRrdService();
        rrdSvc.setDataValues(dbStatus);
        rrdSvc.executeDbStatus(device, databaseName);

    } catch (MongoException e) {
        e.printStackTrace();
        insertConnectionTimeoutError(device);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        try {
            createTetradRrdDb(device, databaseName);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dbStatus;
}

From source file:net.cit.tetrad.rrd.service.TetradRrdDbServiceImpl.java

License:Open Source License

/**
 *  ?  rrdDb? ?.//from w  w  w  . j a va  2  s  .co  m
 * @param device
 */
public void insertTetradRrdDb(Mongo mongo, Device device) throws FileNotFoundException {
    logger.info("=====================================");
    logger.info("start insrt rrd, Device Id : " + device.getIdx());
    logger.debug("ip : " + device.getIp() + ", port : " + device.getPort());
    Map<String, Object> dbStatusFromMongo = new HashMap<String, Object>(); // ? ???? status  
    Map<String, Object> serverStatusFromMongo = new HashMap<String, Object>(); // ? ?? status 
    List<DbStatus> dbInfos = new ArrayList<DbStatus>();

    double dbObjects = 0;
    double dbAvgObjSize = 0;
    double dbDataSize = 0;
    double dbStorageSize = 0;
    double dbNumExtents = 0;
    double dbCount = 0;
    double dbIndexes = 0;
    double dbIndexSize = 0;
    double dbFileSize = 0;
    double dbNsSizeMB = 0;
    double dbSumTimeLocked_r = 0;
    double dbSumTimeLocked_w = 0;

    try {
        CommandResult serverResult = mongoStatusToMonitor.getCommandResult(mongo, device, SERVER_STATUS_COMMAND,
                "admin");

        try {
            // ?? ???  ?
            List<String> dbNames = mongo.getDatabaseNames();
            Pattern patt = Pattern.compile(Config.DBNAME_PATTERN);
            for (String databaseName : dbNames) {
                // ?  DB RrdDB ? Mongodb? insert
                Matcher m = patt.matcher(databaseName);
                if (!m.matches()) {
                    continue;
                }

                // ?  ????  RrdDb ??                
                dbStatusFromMongo = insertTetradRrdDb(mongo, device, databaseName, serverResult);
                DbStatus dbstats = new DbStatus();
                BeanUtils.populate(dbstats, dbStatusFromMongo);

                dbstats.setDb(databaseName);
                dbstats.setGroupCode(device.getGroupCode());
                dbstats.setDeviceCode(device.getIdx());
                dbstats.setType(device.getType());

                dbCount++;
                dbObjects += dbstats.getObjects();
                dbAvgObjSize += dbstats.getAvgObjSize();
                dbDataSize += dbstats.getDataSize();
                dbStorageSize += dbstats.getStorageSize();
                dbNumExtents += dbstats.getNumExtents();
                dbIndexes += dbstats.getIndexes();
                dbIndexSize += dbstats.getIndexSize();
                dbFileSize += dbstats.getFileSize();
                dbNsSizeMB += dbstats.getNsSizeMB();
                dbSumTimeLocked_r += dbstats.getLocks_timeLockedMicros_r();
                dbSumTimeLocked_w += dbstats.getLocks_timeLockedMicros_w();

                daoForMongo.insertDbStatusInfo(dbstats);
                dbInfos.add(dbstats);
            }
        } catch (MongoException e) {
            e.printStackTrace();
            logger.error(e, e);
            ReInitializeMongoInMemory.reInit(device, e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e, e);
        }

        try {
            // ? ?  ?
            DBObject locks = (DBObject) serverResult.get("locks");

            serverResult.remove("locks");
            JasonUtil.getEntryValue(serverResult, "", serverStatusFromMongo);

            if (locks != null) {
                DBObject systemLock = (DBObject) locks.get(".");
                JasonUtil.getEntryValue(systemLock, "locks_", serverStatusFromMongo);
            }

            // ??? ?  ?  ?   .
            int groupCode = device.getGroupCode();
            String uid = device.getUid();
            String type = device.getType();
            String key = groupCode + "_" + uid + "_" + type;
            String regtime = TimestampUtil.readCurrentTime();
            serverStatusFromMongo.put(SERVERSTATUS_ID, key);
            serverStatusFromMongo.put(SERVERSTATUS_REGTIME, regtime);
            serverStatusFromMongo.put(DEVICE_GROUPCODE, device.getGroupCode());
            serverStatusFromMongo.put(DEVICECODE, device.getIdx());
            serverStatusFromMongo.put(SERVERSTATUS_TYPE, device.getType());
            serverStatusFromMongo.put(SERVERSTATUS_IP, device.getIp());
            serverStatusFromMongo.put(SERVERSTATUS_PORT, device.getPort());
            serverStatusFromMongo.put(SERVERSTATUS_DBOBJECTS, dbObjects);
            serverStatusFromMongo.put(SERVERSTATUS_DBAVGOBJSIZE, dbAvgObjSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBDATASIZE, dbDataSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBSTORAGESIZE, dbStorageSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBNUMEXTENTS, dbNumExtents);
            serverStatusFromMongo.put(SERVERSTATUS_DBCOUNT, dbCount);
            serverStatusFromMongo.put(SERVERSTATUS_DBINDEXES, dbIndexes);
            serverStatusFromMongo.put(SERVERSTATUS_DBINDEXSIZE, dbIndexSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBFILESIZE, dbFileSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBNSSIZEMB, dbNsSizeMB);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBDATASIZE, dbDataSize);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBINDEXSIZE, dbIndexSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBSUMLOCKSLOCKED_R, dbSumTimeLocked_r);
            serverStatusFromMongo.put(SERVERSTATUS_DBSUMLOCKSLOCKED_W, dbSumTimeLocked_w);

            InitialRrdService rrdSvc = new InitialRrdService();
            rrdSvc.setDataValues(serverStatusFromMongo);
            rrdSvc.executeServerStatus(device);

            daoForMongo.setGloballLockPageFaults(serverStatusFromMongo);
            daoForMongo.setOpcounter(serverStatusFromMongo);

            // main dashboard ?  ?? 
            ServerStatus serverStatusInfo = new ServerStatus();
            BeanUtils.populate(serverStatusInfo, serverStatusFromMongo);

            // main dashboard ? ? ?? 
            serverStatusInfo.setDbInfos(dbInfos);
            serverStatusInfo.setError(1);
            daoForMongo.insertServerStatusInfo(serverStatusInfo);

            //  ?  ?? 
            String detailKey = key + "_" + regtime;
            serverStatusInfo.setId(detailKey);
            daoForMongo.insertDetailServerStatusInfo(serverStatusInfo);

            // main dashboard  /  ??             
            criticalOperation.settingAlarm(device, serverStatusFromMongo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e, e);
        }
        exportXmlIfNecessary(device);
    } catch (MongoException e) {
        e.printStackTrace();
        logger.error(e, e);
        insertConnectionTimeoutError(device);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error(e, e);
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e, e);
        if (mongo == null) {
            insertConnectionTimeoutError(device);
            throw new MongoException("Mongo Object is null");
        }
    }
    logger.info("end insrt rrd");
}

From source file:org.alfresco.cacheserver.dao.mongo.MongoDbFactory.java

License:Open Source License

public DB createInstance() throws Exception {
    DB db = null;//from  ww w .  ja v  a  2 s  .  c  o  m
    //        try
    //        {
    if (enabled) {
        if (mongo != null) {
            if (dbName != null) {
                db = mongo.getDB(dbName);
            } else {
                db = mongo.getDB(UUID.randomUUID().toString());
            }
        } else {
            if (mongoURI == null || dbName == null) {
                throw new RuntimeException("Must provide mongoURI and dbName or a mongo object");
            }
            MongoClientURI uri = new MongoClientURI(mongoURI);
            MongoClient mongoClient = new MongoClient(uri);
            db = mongoClient.getDB(dbName);
        }

        if (db == null) {
            throw new InstantiationException("Could not instantiate a Mongo DB instance");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Instatiated DB object for dbName '" + db.getName() + "'");
        }
        CommandResult stats = db.getStats();
        if (logger.isTraceEnabled()) {
            stats = db.getStats();
            for (String key : stats.keySet()) {
                logger.trace("\t" + key + " = " + stats.get(key).toString());
            }
        }
    }
    //        }
    //        catch(MongoException.Network e)
    //        {
    //            throw new MongoDbUnavailableException("Mongo network exception, database down?", e);
    //        }
    //        catch(UnknownHostException e)
    //        {
    //            throw new MongoDbUnavailableException("Mongo host not found", e);
    //        }
    return db;
}