Example usage for com.mongodb.client MongoDatabase runCommand

List of usage examples for com.mongodb.client MongoDatabase runCommand

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase runCommand.

Prototype

Document runCommand(Bson command);

Source Link

Document

Executes the given command in the context of the current database with a read preference of ReadPreference#primary() .

Usage

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

License:Apache License

private DBObject executeMongoCommand(MongoDatabase db, Document command) {
    DBObject dbObject = null;// w  w w  .j  a va 2 s . c o  m
    try {
        dbObject = (DBObject) JSON.parse(db.runCommand(command).toJson());
        /*if (dbStats != null && !dbStats.getOk().toString().equals(OK_RESPONSE)) {
        logger.error("Error retrieving db stats. Invalid permissions set for this user.DB= " + db.getName());
        }*/
    } catch (MongoCommandException e) {
        logger.error("Error while executing " + command + " for db " + db, e);
    }
    return dbObject;
}

From source file:com.bluedragon.mongo.MongoCollectionStats.java

License:Open Source License

@SuppressWarnings("rawtypes")
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    try {// w  w  w  .j  av  a 2  s  . c  o  m
        Document result = db.runCommand(new Document("collection", collection).append("verbose", true));
        return tagUtils.convertToCfData((Map) result);
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }

}

From source file:com.bluedragon.mongo.MongoDatabaseRunCmd.java

License:Open Source License

@SuppressWarnings("rawtypes")
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);
    cfData cmdData = getNamedParam(argStruct, "cmd", null);
    if (cmdData == null)
        throwException(_session, "please specify the cmd parameter");

    try {//from   w w  w.j a  va2s .  c  o  m
        Document cmr;

        if (cmdData.getDataType() == cfData.CFSTRUCTDATA)
            cmr = db.runCommand(getDocument((cfStructData) cmdData));
        else
            cmr = db.runCommand(new Document(cmdData.getString(), true));

        return tagUtils.convertToCfData((Map) cmr);
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.bluedragon.mongo.MongoDatabaseStats.java

License:Open Source License

@SuppressWarnings("rawtypes")
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    try {//  w  w w.j av a2s  .c o  m
        Document result = db.runCommand(new Document("dbStats", 1));
        return tagUtils.convertToCfData((Map) result);
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.gs.obevo.mongodb.impl.MongoDeployBehavior.java

License:Apache License

@Override
public void deploy(Change change, CommandExecutionContext cec) {
    MongoDatabase database = mongoClient.getDatabase(change.getPhysicalSchema(env).getPhysicalName());
    final BasicDBObject command = new BasicDBObject();
    command.put("eval", change.getConvertedContent());
    Document result = database.runCommand(command);
    LOG.info("Result: {}", result);
}

From source file:com.imaginea.mongodb.controllers.GraphController.java

License:Apache License

/**
 * Process <opcounters> query request made after each second by Front end
 *
 * @param db : Db Name to egt Server Stats <admin>
 * @return Server stats of <opcounters> key
 * @throws IOException//from  w w w .  j a  v  a2 s . c om
 * @throws JSONException
 */
private JSONArray processQuery(MongoDatabase db) throws IOException, JSONException {

    Document cr = db.runCommand(new Document("serverStatus", 1));

    Document obj = (Document) cr.get("opcounters");
    int currentValue;
    JSONObject temp = new JSONObject();

    num = num + jump;
    temp.put("TimeStamp", num);
    currentValue = (Integer) obj.get("query");
    temp.put("QueryValue", currentValue - lastNoOfQueries);
    lastNoOfQueries = currentValue;
    currentValue = (Integer) obj.get("insert");
    temp.put("InsertValue", currentValue - lastNoOfInserts);
    lastNoOfInserts = currentValue;
    currentValue = (Integer) obj.get("update");
    temp.put("UpdateValue", currentValue - lastNoOfUpdates);
    lastNoOfUpdates = currentValue;
    currentValue = (Integer) obj.get("delete");
    temp.put("DeleteValue", currentValue - lastNoOfDeletes);
    lastNoOfDeletes = currentValue;

    if (array.length() == maxLen) {
        JSONArray tempArray = new JSONArray();
        for (int i = 1; i < maxLen; i++) {
            tempArray.put(array.get(i));
        }
        array = tempArray;
    }
    array.put(temp);
    return array;
}

From source file:com.imaginea.mongodb.controllers.GraphController.java

License:Apache License

/**
 * Initialize by previous <opcounter> value.
 *
 * @param db : Name of Database/*from  w w  w .ja v a  2s .  co  m*/
 * @return : Status of Initialization
 * @throws RuntimeException
 */

private JSONObject processInitiate(MongoDatabase db) throws RuntimeException, JSONException {

    JSONObject respObj = new JSONObject();
    array = new JSONArray();
    num = 0;
    try {

        Document cr = db.runCommand(new Document("serverStatus", 1));

        Document obj = (Document) cr.get("opcounters");

        lastNoOfQueries = (Integer) obj.get("query");
        lastNoOfInserts = (Integer) obj.get("insert");
        lastNoOfUpdates = (Integer) obj.get("update");
        lastNoOfDeletes = (Integer) obj.get("delete");

        respObj.put("result", "Initiated");
    } catch (Exception e) {
        // Invalid User
        JSONObject error = new JSONObject();
        error.put("message", e.getMessage());
        error.put("code", ErrorCodes.ERROR_INITIATING_GRAPH);

        respObj.put("error", error);
        logger.info(respObj);
    }
    return respObj;
}

From source file:com.imaginea.mongodb.services.impl.DatabaseServiceImpl.java

License:Apache License

/**
 * Return Stats of a particular Database in mongo to which user is connected to.
 *
 * @param dbName Name of Database//from   ww  w. j a v a2 s .c  o  m
 * @return Array of JSON Objects each containing a key value pair in Db Stats.
 * @throws JSONException While parsing JSON
 * @throws DatabaseException Error while performing this operation
 * @throws ValidationException throw super type of EmptyDatabaseNameException
 */

public JSONArray getDbStats(String dbName) throws DatabaseException, ValidationException, JSONException {
    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null");
    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }

    JSONArray dbStats = new JSONArray();
    try {
        List<String> dbList = getDbList();
        boolean dbPresent = dbList.contains(dbName);
        if (!dbPresent) {
            throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
                    "DB with name '" + dbName + "'  DOES NOT EXIST");
        }

        MongoDatabase db = mongoInstance.getDatabase(dbName);
        Document stats = db.runCommand(new Document("dbStats", "1"));

        Set<String> keys = stats.keySet();

        Iterator<String> keyIterator = keys.iterator();

        while (keyIterator.hasNext()) {
            JSONObject temp = new JSONObject();
            String key = keyIterator.next();
            temp.put("Key", key);
            String value = stats.get(key).toString();
            temp.put("Value", value);
            String type = stats.get(key).getClass().toString();
            temp.put("Type", type.substring(type.lastIndexOf('.') + 1));
            dbStats.put(temp);
        }
    } catch (MongoException m) {
        throw new DatabaseException(ErrorCodes.GET_DB_STATS_EXCEPTION, m.getMessage());
    }

    return dbStats;
}

From source file:eu.project.ttc.models.occstore.MongoDBOccurrenceStore.java

License:Apache License

public MongoDBOccurrenceStore(String mongoDbUri, State state) {
    super();//from w  w  w .ja va 2  s .co m

    Preconditions.checkNotNull(mongoDbUri, "MongoDB dadabase's URI must not be null");
    Preconditions.checkState(state != State.INDEXING, "Invalid occ store state for constructor. Only "
            + State.COLLECTING + " and " + State.INDEXED + " allowed");

    this.mongoDBUri = getMongoDBUri(mongoDbUri);
    this.state = state;

    initThreadExecutor();

    MongoClientURI connectionString = new MongoClientURI(mongoDbUri);
    this.mongoClient = new MongoClient(connectionString);
    MongoDatabase db = mongoClient.getDatabase(this.mongoDBUri.getDatabase())
            .withWriteConcern(WriteConcern.ACKNOWLEDGED);
    db.runCommand(new org.bson.Document("profile", 1));

    if (state == State.COLLECTING)
        db.drop();

    this.termCollection = db.getCollection("terms");
    this.occurrenceCollection = db.getCollection("occurrences");
    this.documentUrlCollection = db.getCollection("documents");

    resetBuffers();
}

From source file:flipkart.mongo.node.discovery.NodeDiscovery.java

License:Apache License

/**
 * will connect to one of the shard in replica set and update and nodes in the replicaSet
 *//*from   ww  w  .j  a va2 s.  c o  m*/
public ReplicaSetConfig discover() throws MongoDiscoveryException {

    List<Node> nodesInReplicaSet = Lists.newArrayList();
    MongoClient client = MongoConnector.getMongoClient(mongoReplicaSet.getNodes());

    MongoDatabase dbConnection = client.getDatabase(DB_FOR_DISCOVERY);
    Document replicaSetCmd = new Document("replSetGetStatus", "1");
    Document replSetGetStatus = dbConnection.runCommand(replicaSetCmd);
    List<Document> memberDocuments = (List<Document>) replSetGetStatus.get("members");

    for (Document member : memberDocuments) {
        Node replicaNodeWithState = getReplicaNodeWithState(member, mongoReplicaSet);
        nodesInReplicaSet.add(replicaNodeWithState);
    }

    ReplicaSetConfig replicaSetConfig = new ReplicaSetConfig(getShardName(replSetGetStatus), nodesInReplicaSet);
    logger.info("ReplicaSet found: " + replicaSetConfig);
    return replicaSetConfig;
}