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:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 *  Insert an object's field with only one level of nesting. The object's class should  only
 *  have public data fields when calling this function. For example, create a class A{String b; Integer b},
 *  assign values after instantiating the object and pass it to the function
 * @param record Object from which to extract fields and values
 * @param database Database name/*from  w  w  w.j a  v  a 2  s  . c om*/
 * @param collection Collection name
 * @throws TotalADSDBMSException,
 * @throws IllegalAccessException
 * @throws IllegalAccessException
 */
public void insert(Object record, String database, String collection)
        throws TotalADSDBMSException, IllegalAccessException, IllegalAccessException {

    WriteResult writeRes = null;
    String exception = "";
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject document = new BasicDBObject();
    extractKeysAndValuesfromTheObject(record, document);

    try {
        writeRes = coll.insert(document);
    } catch (MongoException e) {
        exception = "Caught MongoException cause: " + e.getMessage();
    }

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        exception += "\n error : " + cmdResult.getErrorMessage();

    if (!exception.isEmpty())
        throw new TotalADSDBMSException(exception);

}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 * Inserts or updates (if already exists) an object in the form of JSON representation into the database. Any kind of complex
 *  data structure can be converted to JSON using gson library and passed to this function 
 * @param database Database name/*from   w w w.ja  v a 2  s  . c o m*/
 * @param jsonObject JSON Object
 * @param collection collection name
 */
public void insertOrUpdateUsingJSON(String database, JsonObject keytoSearch, JsonObject jsonObjectToUpdate,
        String collection) throws TotalADSDBMSException {
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject docToUpdate = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString());

    BasicDBObject keyToSearch = (BasicDBObject) JSON.parse(keytoSearch.toString());

    WriteResult writeRes = coll.update(keyToSearch, docToUpdate, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage());

}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 * This function is used to update the values of individual fields--specified by the replacementFieldsAndValue object--
 *  in documents--specified by the searchFieldsandValues object. Pass two objects of  classes that only has primitive data types
 *   as fields--no methods. Each object's fields' values  and their data types will be automatically extracted and used
 *   in the update. If no document matches the criteria then new document will be inserted
 * @param searchKeyAndItsValue Search fields
 * @param replacementFieldsAndValues Replacement fields
 * @param database Database name//  w  w w.j a  va  2 s. c om
 * @param collection Collection name
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public void replaceFields(Object searchKeyAndItsValue, Object replacementFieldsAndValues, String database,
        String collection) throws IllegalArgumentException, IllegalAccessException, TotalADSDBMSException {

    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject replacementDocument = new BasicDBObject();
    BasicDBObject setFieldValDocument = new BasicDBObject();

    extractKeysAndValuesfromTheObject(replacementFieldsAndValues, setFieldValDocument);

    replacementDocument.append("$set", setFieldValDocument);

    BasicDBObject searchQueryDocument = new BasicDBObject();
    //.append("hosting", "hostB");
    extractKeysAndValuesfromTheObject(searchKeyAndItsValue, searchQueryDocument);

    WriteResult writeRes = coll.update(searchQueryDocument, replacementDocument, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage());

}

From source file:org.eclipse.tracecompass.totalads.dbms.MongoDBMS.java

License:Open Source License

@Override
public void insertOrUpdateUsingJSON(String database, JsonObject keytoSearch, JsonObject jsonObjectToUpdate,
        String collection) throws TotalADSDBMSException {
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject docToUpdate = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString());

    BasicDBObject keyToSearch = (BasicDBObject) JSON.parse(keytoSearch.toString());

    WriteResult writeRes = coll.update(keyToSearch, docToUpdate, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok()) {
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage()); //$NON-NLS-1$
    }//  ww w  .  ja  v  a 2s.co m

}

From source file:org.greenmongoquery.db.service.impl.MongoServiceImpl.java

License:Open Source License

@Override
public void updatetDb(String db, String updateDb, Mongo mongo) {
    DB dbs = mongo.getDB("admin");
    DBObject cmd = new BasicDBObject();
    DBObject key = new BasicDBObject();
    logger.info("host " + mongo.getAddress().getHost() + " from db " + db + " updte db " + updateDb);

    cmd.put("copydb", 1);

    cmd.put("fromhost", mongo.getAddress().getHost());
    cmd.put("todb", updateDb);
    cmd.put("fromdb", db);

    CommandResult result = dbs.command(cmd);

    DB dbsDop = mongo.getDB(db);/* w  ww. java 2  s  .com*/
    dbsDop.dropDatabase();
    logger.info(result.getErrorMessage() + result.getException());
}

From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutput.java

License:Open Source License

protected void commitUpdate(DBObject updateQuery, DBObject insertUpdate, Object[] row) throws KettleException {

    int retrys = 0;
    MongoException lastEx = null;/*www.ja v a 2 s. c  o  m*/

    while (retrys <= m_writeRetries && !isStopped()) {
        WriteResult result = null;
        CommandResult cmd = null;
        try {
            // TODO It seems that doing an update() via a secondary node does not
            // generate any sort of exception or error result! (at least via
            // driver version 2.11.1). Transformation completes successfully
            // but no updates are made to the collection.
            // This is unlike doing an insert(), which generates
            // a MongoException if you are not talking to the primary. So we need
            // some logic to check whether or not the connection configuration
            // contains the primary in the replica set and give feedback if it
            // doesnt
            try {
                result = m_data.getCollection().update(updateQuery, insertUpdate, m_meta.getUpsert(),
                        m_meta.getMulti());
            } catch (MongoDbException e) {
                throw new MongoException(e.getMessage(), e);
            }

            cmd = result.getLastError();
            if (cmd != null && !cmd.ok()) {
                String message = cmd.getErrorMessage();
                logError(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.MongoReported", message)); //$NON-NLS-1$

                cmd.throwOnError();
            }
        } catch (MongoException me) {
            lastEx = me;
            retrys++;
            if (retrys <= m_writeRetries) {
                logError(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.ErrorWritingToMongo", //$NON-NLS-1$
                        me.toString()));
                logBasic(
                        BaseMessages.getString(PKG, "MongoDbOutput.Messages.Message.Retry", m_writeRetryDelay)); //$NON-NLS-1$
                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(), "", "MongoDbOutput");
        } else {
            throw new KettleException(lastEx);
        }
    }
}

From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutput.java

License:Open Source License

protected CommandResult batchRetryUsingSave(boolean lastRetry)
        throws MongoException, KettleException, MongoDbException {
    WriteResult result = null;/* w  w  w  . ja v  a 2 s.com*/
    CommandResult cmd = null;
    int count = 0;
    logBasic(BaseMessages.getString(PKG, "MongoDbOutput.Messages.CurrentBatchSize", m_batch.size()));
    for (int i = 0, len = m_batch.size(); i < len; i++) {
        DBObject toTry = m_batch.get(i);
        Object[] correspondingRow = m_batchRows.get(i);
        try {
            result = m_data.getCollection().save(toTry);
            cmd = result.getLastError();

            if (cmd != null && !cmd.ok()) {
                String message = cmd.getErrorMessage();
                logError(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.MongoReported", message)); //$NON-NLS-1$

                cmd.throwOnError();
            }

            count++;
        } catch (MongoException ex) {
            if (!lastRetry) {
                logBasic(BaseMessages.getString(PKG, "MongoDbOutput.Messages.SuccessfullySavedXDocuments",
                        count));
                m_batch = copyExceptFirst(count, m_batch);
                m_batchRows = copyExceptFirst(count, m_batchRows);
                throw ex;
            }

            // Send this one to the error stream if doing error handling
            if (getStepMeta().isDoingErrorHandling()) {
                putError(getInputRowMeta(), correspondingRow, 1, ex.getMessage(), "", "MongoDbOutput");
            } else {
                m_batch = copyExceptFirst(i + 1, m_batch);
                m_batchRows = copyExceptFirst(i + 1, m_batchRows);
                throw ex;
            }
        }
    }

    m_batch.clear();
    m_batchRows.clear();

    logBasic(BaseMessages.getString(PKG, "MongoDbOutput.Messages.SuccessfullySavedXDocuments", count));

    return cmd;
}

From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutput.java

License:Open Source License

protected void doBatch() throws KettleException, MongoDbException {
    int retries = 0;
    MongoException lastEx = null;/*from w ww. j  av  a2  s  . com*/

    while (retries <= m_writeRetries && !isStopped()) {
        WriteResult result = null;
        CommandResult cmd = null;
        try {
            if (retries == 0) {
                result = m_data.getCollection().insert(m_batch);
                cmd = result.getLastError();

                if (cmd != null && !cmd.ok()) {
                    String message = cmd.getErrorMessage();
                    logError(
                            BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.MongoReported", message)); //$NON-NLS-1$

                    cmd.throwOnError();
                }
            } else {
                // fall back to save
                logBasic(BaseMessages.getString(PKG,
                        "MongoDbOutput.Messages.SavingIndividualDocsInCurrentBatch"));
                cmd = batchRetryUsingSave(retries == m_writeRetries);
            }
        } catch (MongoException me) {
            // avoid exception if a timeout issue occurred and it was exactly the first attempt
            boolean shouldNotBeAvoided = !isTimeoutException(me) && (retries == 0);
            if (shouldNotBeAvoided) {
                lastEx = me;
            }
            retries++;
            if (retries <= m_writeRetries) {
                if (shouldNotBeAvoided) {
                    // skip logging error
                    // however do not skip saving elements separately during next attempt to prevent losing data
                    logError(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.ErrorWritingToMongo", //$NON-NLS-1$
                            me.toString()));
                    logBasic(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Message.Retry", //$NON-NLS-1$
                            m_writeRetryDelay));
                }
                try {
                    Thread.sleep(m_writeRetryDelay * 1000);
                    // CHECKSTYLE:OFF
                } catch (InterruptedException e) {
                    // CHECKSTYLE:ON
                }
            }
            // throw new KettleException(me.getMessage(), me);
        }

        if (cmd != null) {
            ServerAddress s = cmd.getServerUsed();
            if (s != null) {
                logDetailed(
                        BaseMessages.getString(PKG, "MongoDbOutput.Messages.WroteBatchToServer", s.toString())); //$NON-NLS-1$
            }
        }

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

    if ((retries > m_writeRetries || isStopped()) && lastEx != null) {
        throw new KettleException(lastEx);
    }

    m_batch.clear();
    m_batchRows.clear();
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Get the set of collections for a MongoDB database.
 * /*ww w.  jav  a  2  s  .co m*/
 * @param meta
 *          Input meta with connection information
 * @param varSpace
 *          Variable space to substitute variables with
 * @param dB
 *          Name of database
 * @param username
 *          Username to request collections on behalf of
 * @param realPass
 *          Password of user
 * @return Set of collections in the database requested.
 * @throws KettleException
 *           If an error occurs.
 */
public static Set<String> getCollectionsNames(final MongoDbInputMeta meta, final TransMeta varSpace,
        final String dB, final String username, final String realPass) throws KettleException {
    try {
        AuthContext context = MongoUtils.createAuthContext(meta, varSpace);
        return context.doAs(new PrivilegedExceptionAction<Set<String>>() {
            @Override
            public Set<String> run() throws Exception {
                MongoClient conn = null;
                try {
                    conn = MongoDbInputData.initConnection(meta, varSpace, null);
                    DB theDB = conn.getDB(dB);

                    if (!Const.isEmpty(username) || !Const.isEmpty(realPass)) {
                        CommandResult comResult = theDB.authenticateCommand(username, realPass.toCharArray());
                        if (!comResult.ok()) {
                            throw new Exception(
                                    BaseMessages.getString(PKG, "MongoDbInput.ErrorAuthenticating.Exception", //$NON-NLS-1$
                                            comResult.getErrorMessage()));
                        }
                    }

                    return theDB.getCollectionNames();
                } finally {
                    if (conn != null) {
                        conn.close();
                    }
                }
            }
        });
    } catch (PrivilegedActionException ex) {
        if (ex.getCause() instanceof KettleException) {
            throw (KettleException) ex.getCause();
        } else {
            throw new KettleException(
                    "Unable to retrieve collection names for database " + dB + " from MongoDB", ex.getCause());
        }
    }
}

From source file:org.slc.sli.ingestion.util.MongoCommander.java

License:Apache License

/**
 * get list of  the shards/*  w  w  w  . ja  v a 2  s .  c  om*/
 * @param dbConn
 * @return
 */
private static List<String> getShards(DB dbConn) {
    List<String> shards = new ArrayList<String>();

    DBObject listShardsCmd = new BasicDBObject("listShards", 1);
    CommandResult res = dbConn.command(listShardsCmd);
    if (!res.ok()) {
        LOG.error("Error getting shards for {}: {}", dbConn, res.getErrorMessage());
    }

    BasicDBList listShards = (BasicDBList) res.get("shards");

    //Only get shards for sharding mongo
    if (listShards != null) {
        ListIterator<Object> iter = listShards.listIterator();

        while (iter.hasNext()) {
            BasicDBObject shard = (BasicDBObject) iter.next();
            shards.add(shard.getString(ID));
        }
    }
    return shards;
}