Example usage for com.mongodb CommandResult ok

List of usage examples for com.mongodb CommandResult ok

Introduction

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

Prototype

public boolean ok() 

Source Link

Document

Gets the "ok" field, which is whether this command executed correctly or not.

Usage

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()));
                }/* w ww  .  ja  va2 s .c om*/
            } else {
                // single node shard
                shardResult.add(shards);
            }
        }
    }
    return shardResult;
}

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;//  w  w  w. j  a  v a2 s.  co  m
    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.ShardCluster.java

License:Open Source License

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

    BasicBSONObject parsed = null;//  w ww  .  j a  v a2s. co  m

    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.edgytech.umongo.DbJob.java

License:Apache License

public void wrapUp(Object res) {
    UMongo.instance.removeJob(this);

    if (node != null)
        UMongo.instance.addNodeToRefresh(node);

    if (res == null) {
        return;//from ww  w .  j av  a 2s .c o  m
    }

    String title = getTitle();

    boolean log = UMongo.instance.isLoggingOn();
    boolean logRes = UMongo.instance.isLoggingFirstResultOn();

    BasicDBObject sroot = getDescription(getRoot(res));

    BasicDBObject logObj = null;
    if (log) {
        logObj = new BasicDBObject("_id", new ObjectId());
        logObj.put("ns", getNS());
        logObj.put("name", getShortName());
        logObj.put("details", getRoot(res));
    }

    if (res instanceof Iterator) {
        new DocView(null, title, this, sroot, (Iterator) res).addToTabbedDiv();
        if (logRes && res instanceof DBCursor) {
            logObj.put("firstResult", ((DBCursor) res).curr());
        }
    } else if (res instanceof WriteResult) {
        WriteResult wres = (WriteResult) res;
        DBObject lasterr = wres.getCachedLastError();
        if (lasterr != null) {
            new DocView(null, title, this, sroot, lasterr).addToTabbedDiv();
        }
        if (logRes) {
            logObj.put("firstResult", lasterr);
        }
    } else if (res instanceof CommandResult) {
        CommandResult cres = (CommandResult) res;
        if (!cres.ok()) {
            UMongo.instance.showError(title, (Exception) cres.getException());
        }
        new DocView(null, title, this, sroot, (DBObject) res).addToTabbedDiv();
        if (logRes) {
            logObj.put("firstResult", res.toString());
        }
    } else if (res instanceof List) {
        List list = (List) res;
        new DocView(null, title, this, sroot, list.iterator()).addToTabbedDiv();
        if (logRes && list.size() > 0) {
            logObj.put("firstResult", list.get(0));
        }
    } else if (res instanceof DBObject) {
        new DocView(null, title, this, sroot, (DBObject) res).addToTabbedDiv();
        if (logRes) {
            logObj.put("firstResult", res);
        }
    } else if (res instanceof String) {
        new TextView(null, title, this, (String) res).addToTabbedDiv();
        // string may be large
        if (logRes) {
            logObj.put("firstResult", MongoUtils.limitString((String) res, 0));
        }
    } else if (res instanceof Exception) {
        UMongo.instance.showError(title, (Exception) res);
        if (logRes) {
            logObj.put("firstResult", res.toString());
        }
    } else {
        DBObject obj = new BasicDBObject("result", res.toString());
        new DocView(null, title, this, sroot, obj).addToTabbedDiv();
        if (logRes) {
            logObj.put("firstResult", res.toString());
        }
    }

    if (log) {
        UMongo.instance.logActivity(logObj);
    }

    _progress = null;
    _pbw = null;
}

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

License:Apache License

@Override
protected void populateChildren() {
    // first ask list of db, will also trigger discovery of nodes
    List<String> dbnames = new ArrayList<String>();
    try {// ww  w  . j a  v a  2  s.  c om
        dbnames = mongo.getDatabaseNames();
    } catch (Exception e) {
        getLogger().log(Level.WARNING, e.getMessage(), e);
    }

    List<ServerAddress> addrs = mongo.getServerAddressList();

    if (addrs.size() <= 1) {
        // check if mongos
        boolean added = false;
        ServerAddress addr = addrs.get(0);
        ServerNode node = new ServerNode(mongo, false, false);
        try {
            CommandResult res = node.getServerDB().command("isdbgrid");
            if (res.ok()) {
                addChild(new RouterNode(addr, mongo));
                added = true;
            }
        } catch (Exception e) {
            getLogger().log(Level.INFO, e.getMessage(), e);
        }

        if (mongo.getReplicaSetStatus() != null) {
            // could be replset of 1, check
            try {
                CommandResult res = node.getServerDB().command(new BasicDBObject("isMaster", 1),
                        mongo.getOptions());
                if (res.containsField("setName")) {
                    addChild(new ReplSetNode(mongo.getReplicaSetStatus().getName(), mongo, null));
                    added = true;
                }
            } catch (Exception e) {
                getLogger().log(Level.INFO, e.getMessage(), e);
            }
        }

        if (!added)
            addChild(node);
    } else {
        addChild(new ReplSetNode(mongo.getReplicaSetStatus().getName(), mongo, null));
    }

    if (specifiedDb) {
        // user specified list of DB
        dbnames = dbs;
    } else {
        dbs = dbnames;
        if (dbnames.isEmpty()) {
            // could not get any dbs, add test at least
            dbnames.add("test");
        }
    }

    if (dbnames != null) {
        // get all DBs to populate map
        for (String dbname : dbnames) {
            addChild(new DbNode(mongo.getDB(dbname)));
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

License:Apache License

/**
 * Mongo ID generation like it is done in the grails gorm framework
 *
 * @param collectionName/* w  ww. ja  v  a2  s  . com*/
 *            The name of the collection the id should be generated for
 * @param db
 *            The mongodb connection
 * @return a new id
 */
private Long generateIdentifier(String collectionName, DB db) {

    // get or create the Collection for the ID storage
    DBCollection dbCollection = db.getCollection(collectionName + ".next_id");
    // create entry to store the newly generated id
    DBObject nativeEntry = new BasicDBObject();

    while (true) {
        DBCursor result = dbCollection.find().sort(new BasicDBObject("_id", -1)).limit(1);

        long nextId;
        if (result.hasNext()) {
            final Long current = (Long) result.next().get("_id");
            nextId = current + 1;
        } else {
            nextId = 1;
        }

        nativeEntry.put("_id", nextId);
        final WriteResult writeResult = dbCollection.insert(nativeEntry);
        final CommandResult lastError = writeResult.getLastError();
        if (lastError.ok()) {
            break;
        }

        final Object code = lastError.get("code");
        // duplicate key error try again
        if (code != null && code.equals(11000)) {
            continue;
        }
        break;
    }

    return (Long) nativeEntry.get("_id");
}

From source file:com.github.joelittlejohn.embedmongo.MongoScriptsMojo.java

License:Apache License

@Override
public void executeStart() throws MojoExecutionException, MojoFailureException {
    DB db = connectToMongoAndGetDatabase();

    if (scriptsDirectory.isDirectory()) {
        Scanner scanner = null;/*w  w  w.  j a  v a2  s .c o m*/
        StringBuilder instructions = new StringBuilder();
        File[] files = scriptsDirectory.listFiles();

        if (files == null) {
            getLog().info("Can't read scripts directory: " + scriptsDirectory.getAbsolutePath());

        } else {
            getLog().info(
                    "Folder " + scriptsDirectory.getAbsolutePath() + " contains " + files.length + " file(s):");

            for (File file : files) {
                if (file.isFile()) {
                    try {
                        scanner = new Scanner(file);
                        while (scanner.hasNextLine()) {
                            instructions.append(scanner.nextLine()).append("\n");
                        }
                    } catch (FileNotFoundException e) {
                        throw new MojoExecutionException(
                                "Unable to find file with name '" + file.getName() + "'", e);
                    } finally {
                        if (scanner != null) {
                            scanner.close();
                        }
                    }
                    CommandResult result;
                    try {
                        result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]);
                    } catch (MongoException e) {
                        throw new MojoExecutionException(
                                "Unable to execute file with name '" + file.getName() + "'", e);
                    }
                    if (!result.ok()) {
                        getLog().error(
                                "- file " + file.getName() + " parsed with error: " + result.getErrorMessage());
                        throw new MojoExecutionException("Error while executing instructions from file '"
                                + file.getName() + "': " + result.getErrorMessage(), result.getException());
                    }
                    getLog().info("- file " + file.getName() + " parsed successfully");
                }
            }
        }
        getLog().info("Data initialized with success");
    }
}

From source file:com.github.maasdi.di.trans.steps.mongodbdelete.MongoDbDelete.java

License:Apache License

protected void commitDelete(DBObject deleteQuery, Object[] row) throws KettleException {
    int retrys = 0;
    MongoException lastEx = null;//from  w  w w.  j  a  va  2  s. c  om

    while (retrys <= m_writeRetries && !isStopped()) {
        WriteResult result = null;
        CommandResult cmd = null;
        try {
            logDetailed(BaseMessages.getString(PKG, "MongoDbDelete.Message.ExecutingQuery", deleteQuery));
            result = data.getCollection().drop(deleteQuery);

            cmd = result.getLastError();
            if (cmd != null && !cmd.ok()) {
                String message = cmd.getErrorMessage();
                logError(BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.MongoReported", message));

                cmd.throwOnError();
            }
        } catch (MongoException me) {
            lastEx = me;
            retrys++;
            if (retrys <= m_writeRetries) {
                logError(BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.ErrorWritingToMongo",
                        me.toString()));
                logBasic(BaseMessages.getString(PKG, "MongoDbDelete.Message.Retry", m_writeRetryDelay));
                try {
                    Thread.sleep(m_writeRetryDelay * 1000);
                    // CHECKSTYLE:OFF
                } catch (InterruptedException e) {
                    // CHECKSTYLE:ON
                }
            }
        }

        if (cmd != null && cmd.ok()) {
            break;
        }
    }

    if ((retrys > m_writeRetries || isStopped()) && lastEx != null) {

        // Send this one to the error stream if doing error handling
        if (getStepMeta().isDoingErrorHandling()) {
            putError(getInputRowMeta(), row, 1, lastEx.getMessage(), "", "MongoDbDelete");
        } else {
            throw new KettleException(lastEx);
        }
    }
}

From source file:com.github.maasdi.mongo.wrapper.UsernamePasswordMongoClientWrapper.java

License:Apache License

protected void authenticateWithDb(DB db) throws KettleException {
    CommandResult comResult = db.authenticateCommand(user, password.toCharArray());
    if (!comResult.ok()) {
        throw new KettleException(BaseMessages.getString(PKG,
                "MongoUsernamePasswordWrapper.ErrorAuthenticating.Exception", comResult.getErrorMessage()));
    }/*from   w  ww . j av  a2 s.co  m*/
}

From source file:com.github.niltz.maven.plugins.mongodb.AbstractMongoDBMojo.java

License:Open Source License

/**
 * Executes the given script, using the given Mongo.
 * //from   w w  w  .  java  2  s  . c o m
 * @param file
 *            the file to execute
 * @param mongo
 *            the db
 * @throws MojoFailureException
 *             on error
 * @throws MojoExecutionException
 *             on error
 * @throws IOException
 *             on error
 */
protected void executeScript(File file, DB db, BufferedWriter outputFileWriter)
        throws MojoFailureException, MojoExecutionException, IOException {

    // talk a bit :)
    getLog().info("    executing script: " + file.getName());

    // make sure we can read it, and that it's
    // a file and not a directory
    if (!file.exists() || !file.canRead() || file.isDirectory() || !file.isFile()) {
        throw new MojoFailureException(file.getName() + " is not a file");
    }

    // our file reader
    StringBuffer data = new StringBuffer();
    BufferedReader inputFileReader = null;
    try {
        inputFileReader = new BufferedReader(new FileReader(file));

        String line;

        // loop through the statements
        while ((line = inputFileReader.readLine()) != null) {
            // append the line
            line.trim();
            data.append("\n").append(line);
        }
    } finally {
        inputFileReader.close();
    }

    // execute last statement
    try {
        if (this.executeScripts) {
            CommandResult result = db.doEval(data.toString(), new Object[0]);

            if (!result.ok()) {
                getLog().warn("Error executing " + file.getName() + ": " + result.getErrorMessage(),
                        result.getException());
            } else {
                this.appendScriptToFileWriter(outputFileWriter, file, data);
                getLog().info("    " + file.getName() + " executed successfully");
            }
        } else {
            this.appendScriptToFileWriter(outputFileWriter, file, data);
        }
    } catch (Exception e) {
        getLog().error("    error executing " + file.getName(), e);
    }
}