Example usage for com.mongodb CommandResult getString

List of usage examples for com.mongodb CommandResult getString

Introduction

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

Prototype

public String getString(final String key) 

Source Link

Document

Returns the value of a field as a string

Usage

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

License:Open Source License

private boolean isInShardCluster(final CommandResult cr) throws Exception {

    MongoServer ms = new MongoServer(getMyself(cr));
    final String host = ms.getHost();
    final int port = ms.getPort();

    boolean sharded = false;

    final String msg = cr.getString("msg");
    if ((msg != null) && msg.contains("isdbgrid")) {
        sharded = true;//from w  w  w.  j  a v  a 2s.  c om
    } else if (cr.getBoolean("ismaster")) {
        final CommandResult shardState = dbAdminCmd(host, port, "shardingState");
        // shardingState command only returns OK when server is in a sharded
        // cluster
        if (shardState.ok()) {
            if (shardState.getBoolean("enabled")) {
                sharded = true;
            }
        }
    } else if (cr.containsField("primary")) {
        // we are in a replica set but not the primary,
        // check the primary to see if it is a shard member
        final String primary = cr.getString("primary");
        ms = new MongoServer(primary);
        final CommandResult priIsMaster = dbAdminCmd(ms.getHost(), ms.getPort(), "isMaster");
        sharded = isInShardCluster(priIsMaster);
    }
    return sharded;
}

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

License:Open Source License

private String getClusterNodeType() throws Exception {

    final String host = getStringProp(DB_HOST_PROP);
    final int port = getIntProp(DB_PORT_PROP);

    String nodeType = null;/*  w w  w  .j  a  v a2  s  . co m*/

    final CommandResult isMaster = dbAdminCmd(host, port, "isMaster");
    if (isMaster.getBoolean("ismaster")) {
        final String msg = isMaster.getString("msg");
        if (msg != null && msg.contains("isdbgrid")) {
            nodeType = "shardRouter";
        } else {
            final CommandResult shardState = dbAdminCmd(host, port, "shardingState");
            if (shardState.ok() && shardState.getBoolean("enabled")) {
                if (isConfigServer(host, port)) {
                    nodeType = "shardConfigServer";
                } else {
                    nodeType = "shardMember";
                }
            }
        }
    } else if (isReplicaMember(isMaster)) {
        nodeType = "shardMember";
    }

    return nodeType;
}

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

License:Open Source License

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

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

    String cHost = host;/*from  ww  w  .ja va  2 s  .c om*/
    int cPort = port;

    final CommandResult isMaster = dbAdminCmd(cHost, cPort, "isMaster");

    // we can't run the DB command "shardingState" from a node
    // which isn't a master.  This should only apply to non-primary
    // replica members, so find the primary and run the command on it.
    if (!isMaster.getBoolean("ismaster")) {
        if (isMaster.containsField("primary")) {
            final String primary = isMaster.getString("primary");
            final MongoServer ms = new MongoServer(primary);
            cHost = ms.getHost();
            cPort = ms.getPort();
        }
    }

    CommandResult shardState = dbAdminCmd(cHost, cPort, "shardingState");

    if (shardState.ok()) {
        final String cfgSrvs = shardState.getString("configServer");
        addCommaSeparatedHosts(cfgServers, cfgSrvs);
    }
    return cfgServers;
}

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  .  j a va 2 s  . c  om*/
    // 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.hangum.tadpole.mongodb.core.editors.dbInfos.comosites.InstanceInformationComposite.java

License:Open Source License

/**
 * Show Mongodb System Information//from  w w w .  j av a 2 s  . c  om
 * 
 * @param commandResult
 */
public void initMongoDBInfoData(CommandResult commandResult) {
    String strHost = StringUtils.trimToEmpty(commandResult.getString("host"));
    String version = StringUtils.trimToEmpty(commandResult.getString("version"));
    String process = StringUtils.trimToEmpty(commandResult.getString("process"));
    String pid = StringUtils.trimToEmpty(commandResult.getString("pid"));
    String uptime = StringUtils.trimToEmpty(commandResult.getString("uptime"));

    String uptimeMillis = StringUtils.trimToEmpty(
            TimeUtils.getHoureMinSecString(ENumberUtils.toInt(commandResult.getString("uptimeMillis"))));
    String uptimeEstimate = StringUtils.trimToEmpty(commandResult.getString("uptimeEstimate"));
    String localTime = StringUtils.trimToEmpty(commandResult.getString("localTime"));

    textHost.setText(strHost);
    textVersion.setText(version);
    textProcess.setText(process);
    textPID.setText(pid);
    textUptime.setText(uptime);
    textUptimeMillis.setText(uptimeMillis);
    textUpTimeEstimate.setText(uptimeEstimate);
    textLocalTime.setText(localTime);
}

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

License:Open Source License

/**
 * @param args//from   ww  w .ja v a  2s . 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");

    DBObject queryObj = new BasicDBObject("serverStatus", 0);
    CommandResult cr = db.command(queryObj);

    String strHost = cr.getString("host");
    String version = cr.getString("version");
    String process = cr.getString("process");
    String pid = cr.getString("pid");
    String uptime = cr.getString("uptime");
    String uptimeMillis = cr.getString("uptimeMillis");
    String uptimeEstimate = cr.getString("uptimeEstimate");
    String localTime = cr.getString("localTime");

    System.out.println("[strHost]\t " + strHost);
    System.out.println("[version]\t " + version);

    System.out.println("[process]\t " + process);
    System.out.println("[pid]\t " + pid);
    System.out.println("[uptime]\t " + uptime);
    System.out.println("[uptimeMillis]\t " + uptimeMillis);
    System.out.println("[uptimeEstimate]\t " + uptimeEstimate);
    System.out.println("[localTime]\t " + localTime);

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

    mongo.close();
}

From source file:com.snowstore.mercury.indicator.MongoHealthIndicator.java

License:Apache License

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    if (valid) {/*ww w  .j  a v a  2s.com*/
        CommandResult result = this.mongoTemplate.executeCommand("{ buildInfo: 1 }");
        builder.up().withDetail("version", result.getString("version"));
        builder.withDetail(SERVER, mongoTemplate.getDb().getMongo().getConnectPoint());
        addBuilder(builder);
    } else {
        builder.none();
    }
}

From source file:com.tomtom.speedtools.mongodb.MongoDB.java

License:Apache License

/**
 * Returns server version./*from  w  ww  .j a va2 s  . c o  m*/
 *
 * @return Server version.
 */
@Nonnull
public String getServerVersion() {
    final CommandResult result = db.doEval("db.version()");
    return result.getString("retval");
}

From source file:com.zjy.mongo.splitter.MongoSplitterFactory.java

License:Apache License

public static MongoCollectionSplitter getSplitterByStats(final MongoClientURI uri, final Configuration config) {
    /* Looks at the collection in mongo.input.uri
     * and choose an implementation based on what's in there.  */

    MongoCollectionSplitter returnVal;//  ww w .j  av a 2  s. co m

    // If the split calculation is totally disabled, just make one
    // big split for the whole collection.
    if (!MongoConfigUtil.createInputSplits(config)) {
        returnVal = new SingleMongoSplitter(config);
    } else {
        MongoClientURI authURI = MongoConfigUtil.getAuthURI(config);
        CommandResult stats;
        DBCollection coll = null;
        try {
            if (authURI != null) {
                coll = MongoConfigUtil.getCollectionWithAuth(uri, authURI);
                stats = coll.getStats();
                LOG.info("Retrieved Collection stats:" + stats);
            } else {
                coll = MongoConfigUtil.getCollection(uri);
                stats = coll.getStats();
            }
        } finally {
            if (coll != null) {
                MongoConfigUtil.close(coll.getDB().getMongo());
            }
        }

        if (!stats.getBoolean("ok", false)) {
            throw new RuntimeException(
                    "Unable to calculate input splits from collection stats: " + stats.getString("errmsg"));
        }

        if (!stats.getBoolean("sharded", false)) {
            returnVal = new StandaloneMongoSplitter(config);
        } else {
            // Collection is sharded
            if (MongoConfigUtil.isShardChunkedSplittingEnabled(config)) {
                // Creates one split per chunk. 
                returnVal = new ShardChunkMongoSplitter(config);
            } else if (MongoConfigUtil.canReadSplitsFromShards(config)) {
                // Creates one split per shard, but ignores chunk bounds. 
                // Reads from shards directly (bypassing mongos).
                // Not usually recommended.
                returnVal = new ShardMongoSplitter(config);
            } else {
                //Not configured to use chunks or shards -
                //so treat this the same as if it was an unsharded collection
                returnVal = new StandaloneMongoSplitter(config);
            }
        }
    }
    return returnVal;
}

From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java

License:Apache License

@Override
public List<InputSplit> calculateSplits() throws SplitFailedException {
    final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration());
    final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration());
    final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration());
    final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration());
    final MongoClientURI inputURI;
    DBCollection inputCollection = null;
    final ArrayList<InputSplit> returnVal;
    try {/*from w w  w. j a  v  a  2s .com*/
        inputURI = MongoConfigUtil.getInputURI(getConfiguration());
        MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration());
        if (authURI != null) {
            inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI);
        } else {
            inputCollection = MongoConfigUtil.getCollection(inputURI);
        }

        returnVal = new ArrayList<InputSplit>();
        final String ns = inputCollection.getFullName();

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s",
                    inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts()));
        }
        final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey)
                .add("min", splitKeyMin).add("max", splitKeyMax)
                // force:True is misbehaving it seems
                .add("force", false).add("maxChunkSize", splitSize).get();

        CommandResult data;
        boolean ok = true;
        try {
            data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd,
                    ReadPreference.primary());
        } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult
            data = null;
            LOG.info(e.getMessage(), e);
            if (e.getMessage().contains("unrecognized command: splitVector")) {
                ok = false;
            } else {
                throw e;
            }
        }

        if (data != null) {
            if (data.containsField("$err")) {
                throw new SplitFailedException("Error calculating splits: " + data);
            } else if (!data.get("ok").equals(1.0)) {
                ok = false;
            }
        }

        if (!ok) {
            final CommandResult stats = inputCollection.getStats();
            if (stats.containsField("primary")) {
                final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards")
                        .find(new BasicDBObject("_id", stats.getString("primary")));
                try {
                    if (shards.hasNext()) {
                        final DBObject shard = shards.next();
                        final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", "");
                        final MongoClientURI shardHost;
                        if (authURI != null) {
                            shardHost = new MongoClientURIBuilder(authURI).host(host).build();
                        } else {
                            shardHost = new MongoClientURIBuilder(inputURI).host(host).build();
                        }
                        MongoClient shardClient = null;
                        try {
                            shardClient = new MongoClient(shardHost);
                            data = shardClient.getDB(shardHost.getDatabase()).command(cmd,
                                    ReadPreference.primary());
                        } catch (final Exception e) {
                            LOG.error(e.getMessage(), e);
                        } finally {
                            if (shardClient != null) {
                                shardClient.close();
                            }
                        }
                    }
                } finally {
                    shards.close();
                }
            }
            if (data != null && !data.get("ok").equals(1.0)) {
                throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg"));
            }

        }

        // Comes in a format where "min" and "max" are implicit
        // and each entry is just a boundary key; not ranged
        final BasicDBList splitData = (BasicDBList) data.get("splitKeys");

        if (splitData.size() == 0) {
            LOG.warn(
                    "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too"
                            + " small, try lowering 'mongo.input.split_size' if this is undesirable.");
        }

        BasicDBObject lastKey = null; // Lower boundary of the first min split

        // If splitKeyMin was given, use it as first boundary.
        if (!splitKeyMin.toMap().isEmpty()) {
            lastKey = new BasicDBObject(splitKeyMin.toMap());
        }
        for (final Object aSplitData : splitData) {
            final BasicDBObject currentKey = (BasicDBObject) aSplitData;
            returnVal.add(createSplitFromBounds(lastKey, currentKey));
            lastKey = currentKey;
        }

        BasicDBObject maxKey = null;
        // If splitKeyMax was given, use it as last boundary.
        if (!splitKeyMax.toMap().isEmpty()) {
            maxKey = new BasicDBObject(splitKeyMax.toMap());
        }
        // Last max split
        final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey);
        returnVal.add(lastSplit);
    } finally {
        if (inputCollection != null) {
            MongoConfigUtil.close(inputCollection.getDB().getMongo());
        }
    }

    return returnVal;
}