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:br.com.ezequieljuliano.argos.template.StandardDAO.java

License:Apache License

private Collection<ObjectId> extractSearchResultIds(CommandResult commandResult) {
    Set<ObjectId> objectIds = new HashSet<ObjectId>();
    BasicDBList resultList = (BasicDBList) commandResult.get("results");
    if (resultList == null) {
        System.out.println(mongoFullTextSearchErrorMessage());
        return objectIds;
    }/*from w w  w.j  ava 2  s .  c  o  m*/
    Iterator<Object> it = resultList.iterator();
    while (it.hasNext()) {
        BasicDBObject resultContainer = (BasicDBObject) it.next();
        BasicDBObject resultObject = (BasicDBObject) resultContainer.get("obj");
        ObjectId resultId = (ObjectId) resultObject.get("_id");
        objectIds.add(resultId);
    }
    return objectIds;
}

From source file:brooklyn.entity.nosql.mongodb.MongoDBTestHelper.java

License:Apache License

public static boolean isConfigServer(AbstractMongoDBServer entity) {
    LOG.info("Checking if {} is a config server", entity);
    MongoClient mongoClient = clientForServer(entity);
    try {//from   w  w w . j  ava 2  s. c  o  m
        DB db = mongoClient.getDB(ADMIN_DB);
        CommandResult commandResult = db.command("getCmdLineOpts");
        Map<?, ?> parsedArgs = (Map<?, ?>) commandResult.get("parsed");
        if (parsedArgs == null)
            return false;
        Boolean configServer = (Boolean) parsedArgs.get("configsvr");
        if (configServer != null) {
            // v2.5 format
            return Boolean.TRUE.equals(configServer);
        } else {
            // v2.6 format
            String role = (String) ((Map) parsedArgs.get("sharding")).get("clusterRole");
            return "configsvr".equals(role);
        }
    } finally {
        mongoClient.close();
    }
}

From source file:com.appleframework.monitor.model.Chart.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "null" })
public List findData() {
    logger.debug("find stats  by {}", query);
    CommandResult result = null;//mongoDb.runCmd(query);
    logger.debug("stats mongo result {}", result);
    Object data = result.get("retval");
    return (List) data;
}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Gets split data.//from   ww  w  . ja v  a  2 s.c o m
 *
 * @param collection the collection
 * @return the split data
 */
private BasicDBList getSplitData(DBCollection collection) {

    final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName())
            .add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1)).add("force", false)
            .add("maxChunkSize", splitSize).get();

    CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd);
    return (BasicDBList) splitVectorResult.get(SPLIT_KEYS);

}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getShardsFromMongos(final String host, final int port) throws Exception {

    final List<String> shardResult = new ArrayList<String>();

    final CommandResult cr = dbAdminCmd(host, port, "listShards");

    if (cr.ok()) {
        final BasicDBList shardList = (BasicDBList) cr.get("shards");
        for (Object obj : shardList) {
            final BasicDBObject bdbo = (BasicDBObject) obj;
            String shards = bdbo.getString("host");
            if (shards.indexOf("/") != -1) {
                final String[] shardMembers = shards.split("/")[1].split(",");
                for (String member : shardMembers) {
                    final MongoServer ms = new MongoServer(member);
                    shardResult.addAll(discoverReplicas(ms.getHost(), ms.getPort()));
                }//  ww w . ja va 2s.  c  o  m
            } else {
                // single node shard
                shardResult.add(shards);
            }
        }
    }
    return shardResult;
}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private BasicBSONObject getParsedCmdLineOpts(final String host, final int port) throws Exception {

    BasicBSONObject parsed = null;/*from w w  w  .  j a v a2  s .  c om*/

    final CommandResult clOptions = dbAdminCmd(host, port, "getCmdLineOpts");

    if (clOptions.ok()) {
        parsed = (BasicBSONObject) clOptions.get("parsed");
    } else {
        throw new RuntimeException("Failed to get command line options!");
    }
    return parsed;
}

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected List<String> discoverReplicas(final String host, final int port) throws Exception {

    List<String> replicas = new ArrayList<String>();

    final CommandResult cr = dbAdminCmd(host, port, "isMaster");

    replicas.addAll((List<String>) cr.get("hosts"));
    // hidden replicas are replicas that cannot become primaries and
    // are hidden to the client app
    if (cr.getBoolean("hidden")) {
        // TODO: We can't assume we're the master here....
        replicas.add(cr.getString("me"));
    }/*w w  w  . jav a2  s  .co m*/
    // passives are replicas that cannot become primaries because
    // their priority is set to 0
    if (cr.containsField("passives")) {
        replicas.addAll((List<String>) cr.get("passives"));
    }
    // arbiters exist only to vote in master elections.  They don't
    // actually hold replica data.
    if (cr.containsField("arbiters")) {
        replicas.addAll((List<String>) cr.get("arbiters"));
    }
    return replicas;
}

From source file:com.ebay.cloud.cms.sysmgmt.monitor.metrics.MongoMetric.java

License:Apache License

private Map<String, Object> listDatabases(final MongoClient client) {
    try {/*from w  ww .ja  v  a  2s.co  m*/
        Future<Map<String, Object>> future = executor.submit(new Callable<Map<String, Object>>() {
            @Override
            public Map<String, Object> call() {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                List<String> databaseNames = client.getDatabaseNames();
                for (String databaseName : databaseNames) {
                    DB db = client.getDB(databaseName);
                    if (db != null) {
                        CommandResult cr = db.getStats();
                        if (cr != null) {
                            Object dataSize = cr.get("dataSize");
                            resultMap.put(databaseName, dataSize);
                        }
                    }
                }
                return resultMap;
            }
        });
        return future.get(listWaitPeroid, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        return Collections.emptyMap();
    }
}

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

License:Apache License

public void analyzeProfilingData(ButtonBase button) {
    new DbJob() {

        @Override//  w  w w  .  j  av  a2s  .  com
        public Object doRun() throws Exception {
            DBCollection prof = getDbNode().getDb().getCollection("system.profile");
            BasicDBObject out = new BasicDBObject();
            CommandResult res = null;
            DocumentDeserializer dd = null;
            BasicDBObject aggCmd = null;

            // response time by operation type
            dd = new DocumentDeserializer(DocumentDeserializer.Format.JSON_SINGLE_DOC, null);
            dd.setInputStream(DbPanel.class.getResourceAsStream("/json/profOperationType.json"));
            aggCmd = (BasicDBObject) dd.readObject();
            res = getDbNode().getDb().command(aggCmd);
            out.put("byOperationType", res.get("result"));
            dd.close();

            // slowest by namespace
            dd = new DocumentDeserializer(DocumentDeserializer.Format.JSON_SINGLE_DOC, null);
            dd.setInputStream(DbPanel.class.getResourceAsStream("/json/profNamespace.json"));
            aggCmd = (BasicDBObject) dd.readObject();
            res = getDbNode().getDb().command(aggCmd);
            out.put("byNamespace", res.get("result"));
            dd.close();

            // slowest by client
            dd = new DocumentDeserializer(DocumentDeserializer.Format.JSON_SINGLE_DOC, null);
            dd.setInputStream(DbPanel.class.getResourceAsStream("/json/profClient.json"));
            aggCmd = (BasicDBObject) dd.readObject();
            res = getDbNode().getDb().command(aggCmd);
            out.put("byClient", res.get("result"));
            dd.close();

            // summary moved vs non-moved
            dd = new DocumentDeserializer(DocumentDeserializer.Format.JSON_SINGLE_DOC, null);
            dd.setInputStream(DbPanel.class.getResourceAsStream("/json/profMoved.json"));
            aggCmd = (BasicDBObject) dd.readObject();
            res = getDbNode().getDb().command(aggCmd);
            out.put("movedVsNonMoved", res.get("result"));
            dd.close();

            // response time analysis
            dd = new DocumentDeserializer(DocumentDeserializer.Format.JSON_SINGLE_DOC, null);
            dd.setInputStream(DbPanel.class.getResourceAsStream("/json/profResponseTimeAnalysis.json"));
            aggCmd = (BasicDBObject) dd.readObject();
            res = getDbNode().getDb().command(aggCmd);
            out.put("responseTimeAnalysis", res.get("result"));
            dd.close();

            return out;
        }

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

        @Override
        public String getShortName() {
            return "Analyze Profiling Data";
        }
    }.addJob();
}

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

License:Apache License

@Override
protected void populateChildren() {
    CommandResult res = mongo.getDB("admin").command("listShards");
    shards = (BasicDBList) res.get("shards");
    if (shards == null) {
        return;/*from ww w. j  a  v a  2 s .c  o  m*/
    }

    for (Object obj : shards) {
        try {
            DBObject shard = (DBObject) obj;
            String shardName = (String) shard.get("_id");
            String hosts = (String) shard.get("host");
            String repl = null;
            int slash = hosts.indexOf('/');
            if (slash >= 0) {
                repl = hosts.substring(0, slash);
                hosts = hosts.substring(slash + 1);
            }

            String[] hostList = hosts.split(",");
            ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
            for (String host : hostList) {
                int colon = host.indexOf(':');
                if (colon >= 0) {
                    addrs.add(new ServerAddress(host.substring(0, colon),
                            Integer.parseInt(host.substring(colon + 1))));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }

            if (repl != null || addrs.size() > 1) {
                addChild(new ReplSetNode(repl, addrs, mongo.getMongoClientOptions(), shardName));
            } else {
                addChild(new ServerNode(addrs.get(0), mongo.getMongoClientOptions(), false, false));
            }
        } catch (Exception e) {
            getLogger().log(Level.WARNING, null, e);
        }
    }

    // add config servers
    try {
        res = mongo.getDB("admin").command("getCmdLineOpts");
        String configStr = (String) ((BasicDBObject) res.get("parsed")).get("configdb");
        String[] configsvrs = configStr.split(",");
        for (String host : configsvrs) {
            int colon = host.indexOf(':');
            ServerAddress addr;
            if (colon >= 0) {
                addr = new ServerAddress(host.substring(0, colon), Integer.parseInt(host.substring(colon + 1)));
            } else {
                addr = new ServerAddress(host);
            }
            addChild(new ServerNode(addr, mongo.getMongoClientOptions(), false, true));
        }
    } catch (Exception e) {
        getLogger().log(Level.WARNING, null, e);
    }
}