Example usage for com.mongodb CommandResult getErrorMessage

List of usage examples for com.mongodb CommandResult getErrorMessage

Introduction

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

Prototype

@Nullable
public String getErrorMessage() 

Source Link

Document

Gets the error message associated with a failed command.

Usage

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()));
    }/*  w  ww  . ja  va  2  s  . c o  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.  j av  a2 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

/**
 * top//from w w w  . j a v a 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.icoin.trading.tradeengine.query.tradeexecuted.repositories.TradeExecutedQueryRepositoryImpl.java

License:Apache License

/**
 * Inspects the given {@link CommandResult} for erros and potentially throws an
 * {@link org.springframework.dao.InvalidDataAccessApiUsageException} for that error.
 *
 * @param result must not be {@literal null}.
 * @param source must not be {@literal null}.
 *//*from   w  w w .  j av a2s  .co  m*/
private void handleCommandError(CommandResult result, DBObject source) {

    try {
        result.throwOnError();
    } catch (MongoException ex) {

        String error = result.getErrorMessage();
        error = error == null ? "NO MESSAGE" : error;

        throw new InvalidDataAccessApiUsageException(
                "Command execution failed:  Error [" + error + "], Command = " + source, ex);
    }
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private void runCommand(Object commandValue) throws JRException {
    if (!(commandValue instanceof DBObject)) {
        throw new JRException("Command must be a valid BSON object");
    }/*  w w  w .j a  v  a  2 s  .  c o  m*/
    DBObject commandObject = (DBObject) commandValue;
    if (logger.isDebugEnabled()) {
        logger.debug("Command object: " + commandObject);
    }
    CommandResult commandResult = connection.getMongoDatabase().command(commandObject);
    if (!commandResult.ok()) {
        throw new JRException(commandResult.getErrorMessage());
    }
    Object resultObject = commandResult.get(RESULT_KEY);
    if (resultObject == null) {
        throw new JRException("No results");
    }
    commandResults = (List<?>) resultObject;
}

From source file:com.jhkt.playgroundArena.shared.tasks.MongoDBTaskRunner.java

License:Apache License

private void processWriteResult(WriteResult wr) {
    CommandResult result = wr.getLastError();
    if (!result.ok()) {
        throw new RuntimeException(result.getErrorMessage(), result.getException());
    }//from  ww  w  .  j a  v  a2  s.c o  m
}

From source file:com.nec.strudel.tkvs.store.tokumx.TokumxTransaction.java

License:Apache License

public TokumxTransaction(String gName, Key gKey, String dbname, DB db, TokumxReader kvs, DBCollection coll,
        TransactionProfiler prof) {//from  www.ja v a  2 s  .c  om
    super(gName, gKey, kvs, prof);
    db.requestStart();
    this.db = db;
    //this.coll = coll;
    this.kvs = kvs;
    this.gName = gName;
    this.prof = prof;
    this.bulkwriter = coll.initializeOrderedBulkOperation();

    DBObject cmd = new BasicDBObject("beginTransaction", 1).append("isolation", "serializable");
    //Default is MVCC snapshot isolation level.
    //       DBObject cmd = new BasicDBObject("beginTransaction", 1);
    CommandResult res = runCommand(db, cmd);
    if (!res.ok()) {
        LOGGER.warn("failed to begin transaction: " + res.getErrorMessage());
    }
}

From source file:com.nec.strudel.tkvs.store.tokumx.TokumxTransaction.java

License:Apache License

@Override
public boolean commit() {
    prof.commitStart(gName);//from www .j ava2 s. c om
    if (kvs.isAborted()) {
        prof.commitFail(gName);
        return false;
    }
    boolean noop = true;
    for (CollectionBuffer b : buffers()) {
        Map<Key, Record> writes = b.getWrites();
        String name = b.getName();
        for (Map.Entry<Key, Record> e : writes.entrySet()) {
            Key key = e.getKey();
            Record r = e.getValue();
            String docName = key.toStringKey(name);
            //for put
            if (r != null) {
                //bulk or update? Tested: almost the same performance
                if (noop) {
                    noop = false;
                }
                bulkwriter.find(new BasicDBObject(TokumxDbServer.DOCNAME, docName)).upsert().update(
                        new BasicDBObject("$set", new BasicDBObject(TokumxDbServer.VALUENAME, r.toBytes())));
                //               coll.update(new
                //                      BasicDBObject(TokumxDbServer.docname, docName),
                //                  new BasicDBObject("$set",
                //                       new BasicDBObject(TokumxDbServer.valuename,
                //                       SerDeUtil.toBytes(r))),
                //                     true,
                //                     false);

            } else { // for delete
                if (noop) {
                    noop = false;
                }
                bulkwriter.find(new BasicDBObject(TokumxDbServer.DOCNAME, docName)).remove();
                //coll.remove(new BasicDBObject(
                //TokumxDbServer.docname, docName));
            }
        }
    }
    if (!noop) {
        try {
            bulkwriter.execute();
        } catch (com.mongodb.BulkWriteException e) {
            //This is tested to happen when
            //running multi-row transactions,
            //error message is: lock can not be granted
            LOGGER.warn("transaction failed due to BulkWriteException: " + e.getMessage());
            prof.commitFail(gName);
            return false;
        } catch (@SuppressWarnings("deprecation") MongoException.Network e) {
            LOGGER.warn("transaction failed due to mongo network exception: " + e.getMessage());
            prof.commitFail(gName);
            return false;
        } catch (MongoException e) {
            LOGGER.warn("transaction failed due to mongo exception: " + e.getMessage());
            prof.commitFail(gName);
            return false;

        }
    }

    DBObject cmd = new BasicDBObject("commitTransaction", 1);
    CommandResult res = runCommand(db, cmd);
    if (res.ok()) {
        prof.commitSuccess(gName);
        db.requestDone();
        return true;
    } else {
        prof.commitFail(gName);
        LOGGER.info("commit failed :" + res.getErrorMessage());
        cmd = new BasicDBObject("rollbackTransaction", 1);
        runCommand(db, cmd);
        db.requestDone();
        return false;
    }
}

From source file:com.nesscomputing.mongo.MongoWriter.java

License:Apache License

protected void flushToMongo(final List<Callable<DBObject>> dbObjects) {
    LOG.trace("Starting write of %d elements...", dbObjects.size());

    final DBCollection collection = dbCollection.get();
    if (collection != null) {
        final WriteResult writeResult = collection.insert(Lists.transform(dbObjects, CALLABLE_FUNCTION),
                WriteConcern.NORMAL);//from   ww  w.  j  a v  a 2s . c om
        final CommandResult cmdResult = writeResult.getLastError();
        if (cmdResult.ok()) {
            opsSent.addAndGet(dbObjects.size());
        } else {
            LOG.warn("Command returned %s", cmdResult.getErrorMessage());
            opsLost.addAndGet(dbObjects.size());
        }
        LOG.trace("Wrote %d put ops to Mongo dbCollection %s.", dbObjects.size(), collectionName);
    } else {
        LOG.warn("dbCollection is null, probably shutting down!");
    }
}

From source file:com.stratio.connector.mongodb.core.engine.metadata.ShardUtils.java

License:Apache License

/**
 * Shard a collection./*from w w  w.  ja va 2s  . c  o m*/
 *
 * @param mongoClient
 *            the mongo client
 * @param tableMetadata
 *            the table metadata
 * @throws ExecutionException
 *             if an error exist when sharding the collection
 */
public static void shardCollection(MongoClient mongoClient, TableMetadata tableMetadata)
        throws ExecutionException {

    final String catalogName = tableMetadata.getName().getCatalogName().getName();
    enableSharding(mongoClient, catalogName);

    DBObject shardKey = new BasicDBObject();
    Map<String, Selector> options = SelectorOptionsUtils.processOptions(tableMetadata.getOptions());

    ShardKeyType shardKeyType = getShardKeyType(options);
    String[] shardKeyFields = getShardKeyFields(options, shardKeyType);

    switch (shardKeyType) {
    case ASC:
        for (String field : shardKeyFields) {
            shardKey.put(field, 1);
        }
        break;
    case HASHED:
        shardKey.put(shardKeyFields[0], "hashed");
        break;
    }

    // shard the collection with the key
    final DBObject cmd = new BasicDBObject("shardCollection",
            catalogName + "." + tableMetadata.getName().getName());
    cmd.put("key", shardKey);

    CommandResult result = mongoClient.getDB("admin").command(cmd);
    if (!result.ok()) {
        LOGGER.error("Error executing" + cmd + " :" + result.getErrorMessage());
        throw new ExecutionException(result.getErrorMessage());
    }

}