Example usage for com.mongodb CommandResult getException

List of usage examples for com.mongodb CommandResult getException

Introduction

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

Prototype

@Nullable
public MongoException getException() 

Source Link

Document

Utility method to create an exception from a failed command.

Usage

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  w  w  w  .j a  va  2 s  .  co 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.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 a 2 s.co  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.niltz.maven.plugins.mongodb.AbstractMongoDBMojo.java

License:Open Source License

/**
 * Executes the given script, using the given Mongo.
 * //from  ww w . ja  v a  2  s  .co 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);
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * coll stats/* w ww  .  j  a v  a  2 s.co  m*/
 * 
 * @param userDB
 * @param colName
 * @return
 * @throws Exception
 */
public static String getCollStats(UserDBDAO userDB, String colName) throws Exception {
    DBCollection collection = findCollection(userDB, colName);

    CommandResult cr = collection.getStats();
    if (cr.ok()) {
        return cr.toString();
    } else {
        throw cr.getException();
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * collection validate//  w  ww.  ja v  a  2  s . c  o m
 * 
 * @param userDB
 * @param collName
 * @param isFull
 * @return
 * @throws Exception
 */
public static BasicDBObject collValidate(UserDBDAO userDB, String collName, boolean isFull) throws Exception {

    DBObject queryObj = new BasicDBObject("validate", collName);
    queryObj.put("full", isFull);
    CommandResult cr = findDB(userDB).command(queryObj);

    if (!cr.ok())
        throw cr.getException();
    if (logger.isDebugEnabled())
        logger.debug("[compact] complements" + cr.toString());

    return (BasicDBObject) cr;
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * collection compact//from  w w  w.j ava 2  s .  c o  m
 * 
 * @param userDB
 * @param colName
 * @param force
 * @param paddingFactor
 * @param paddingBytes
 * @return
 * @throws Exception
 */
public static String collCompact(UserDBDAO userDB, String colName, boolean isForct, int paddingFactor,
        int paddingBytes) throws Exception {
    DB mongoDB = findDB(userDB);

    DBObject queryObj = new BasicDBObject("compact", colName);
    if (paddingFactor > 0)
        queryObj.put("paddingFactor", paddingFactor);
    if (paddingBytes > 0)
        queryObj.put("paddingBytes", paddingBytes);

    CommandResult cr = mongoDB.command(queryObj);

    if (!cr.ok())
        throw cr.getException();
    if (logger.isDebugEnabled())
        logger.debug("[compact] complements" + cr.toString());

    return cr.toString();
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * reIndex collection//from   w w  w.j  a  v  a 2 s .  co  m
 * 
 * @param userDB
 * @param colName
 * @throws Exception
 */
public static void reIndexCollection(UserDBDAO userDB, String colName) throws Exception {
    DB mongoDB = findDB(userDB);

    DBObject queryObj = new BasicDBObject("reIndex", colName);
    CommandResult cr = mongoDB.command(queryObj);

    if (!cr.ok())
        throw cr.getException();
    if (logger.isDebugEnabled())
        logger.debug("[reIndex] complements" + colName);
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * Server status, return to String// w  ww  . ja va2  s  .c o m
 * 
 * @param userDB
 * @throws Exception
 */
public static String serverStatus(UserDBDAO userDB) throws Exception {
    DB mongoDB = findDB(userDB);

    DBObject queryObj = new BasicDBObject("serverStatus", 1);
    CommandResult cr = mongoDB.command(queryObj);
    if (cr.ok()) {
        return cr.toString();
    } else {
        throw cr.getException();
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * top//from  w  w w  .ja  va  2s .  c o  m
 * 
 * @param userDB
 * @param top
 * @return
 * @throws Exception
 */
public static String top(UserDBDAO userDB, int top) throws Exception {

    UserDBDAO adminDB = new UserDBDAO();
    adminDB.setHost(userDB.getHost());
    adminDB.setPort(userDB.getPort());
    adminDB.setUsers(userDB.getUsers());
    adminDB.setPasswd(userDB.getPasswd());
    adminDB.setUrl(userDB.getHost() + ":" + userDB.getPort() + "/admin");
    adminDB.setDb("admin");

    DB mongoDB = findDB(adminDB);

    DBObject queryObj = new BasicDBObject("top", top);
    CommandResult cr = mongoDB.command(queryObj);
    if (cr.ok()) {
        return cr.toString();
    } else {

        logger.error("top command" + userDB, cr.getException());
        throw new Exception(cr.getErrorMessage());//cr.getException();
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * db stats// w ww .j  av a2s. c  o  m
 * 
 * @param userDB
 * @throws Exception
 */
public static String dbStats(UserDBDAO userDB) throws Exception {
    DB mongoDB = findDB(userDB);
    CommandResult cr = mongoDB.getStats();

    if (cr.ok()) {
        return cr.toString();
    } else {
        throw cr.getException();
    }
}