Example usage for com.mongodb CommandResult throwOnError

List of usage examples for com.mongodb CommandResult throwOnError

Introduction

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

Prototype

public void throwOnError() 

Source Link

Document

Throws a CommandFailureException if the command failed.

Usage

From source file:ezbake.deployer.publishers.database.MongoDBDatabaseSetup.java

License:Apache License

@Override
public List<ArtifactDataEntry> setupDatabase(DeploymentArtifact artifact, Properties configuration,
        EzSecurityToken callerToken) throws DeploymentException {
    MongoHelper mongoHelper = new MongoHelper(configuration);
    MongoConfigurationHelper mongoConfiguration = mongoHelper.getMongoConfigurationHelper();

    //Setup new mongo properties
    String databaseName = ArtifactHelpers.getNamespace(artifact);
    String userName = databaseName + "_user";
    String password = new BigInteger(130, random).toString(32);

    //Connect to Mongo DB
    Mongo client = getMongoClient(mongoHelper);
    try {/*from  w ww  .ja  va2s .  c o m*/
        //If user exists, re-generate the password and reset the password
        DBObject cmd = new BasicDBObject("updateUser", userName);
        cmd.put("pwd", password);
        cmd.put("roles", DBRole);
        CommandResult result = client.getDB(databaseName).command(cmd);
        if (!result.ok()) {
            logger.warn("Failed to update mongo user. {}.  Attempting to add", result.getErrorMessage());
            //If user doesn't exist, create new Mongo DB User/Password/Database unique for this application
            cmd = new BasicDBObject("createUser", userName);
            cmd.put("pwd", password);
            cmd.put("roles", DBRole);
            result = client.getDB(databaseName).command(cmd);
            result.throwOnError();
        }
    } finally {
        client.close();
    }

    //Create a mongo.properties file with mongo host, username, password(hashed), and database
    Map<String, String> valuesMap = Maps.newHashMap();
    valuesMap.put(EzBakePropertyConstants.MONGODB_DB_NAME, databaseName);
    valuesMap.put(EzBakePropertyConstants.MONGODB_HOST_NAME, mongoConfiguration.getMongoDBHostName());
    valuesMap.put(EzBakePropertyConstants.MONGODB_USE_SSL,
            Boolean.toString(mongoConfiguration.useMongoDBSSL()));

    Map<String, String> encryptedValuesMap = Maps.newHashMap();
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_USER_NAME, userName);
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_PASSWORD, password);
    String connectionString = String.format("mongodb://%s:%s@%s/%s?ssl=%b", userName, password,
            mongoConfiguration.getMongoDBHostName(), databaseName, mongoConfiguration.useMongoDBSSL());
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_CONNECTION_STRING, connectionString);

    String properties = Joiner.on('\n').withKeyValueSeparator("=").join(valuesMap);
    String encryptedProps = Joiner.on('\n').withKeyValueSeparator("=").join(encryptedValuesMap);
    List<ArtifactDataEntry> entries = Lists.newArrayList();
    entries.add(Utilities.createConfCertDataEntry(MONGODB_PROPERTIES_FILE_NAME, properties.getBytes()));
    entries.add(Utilities.createConfCertDataEntry(ENCRYPTED_MONGODB_PROPERTIES_FILE_NAME,
            encryptedProps.getBytes()));
    return entries;
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java

License:Open Source License

@SuppressWarnings("unchecked")
static Iterable<DBObject> callDBCommand(DB connectedDB, QueryProperties queryProps) throws OdaException {
    if (!queryProps.hasRunCommand())
        return null;
    DBObject command = queryProps.getOperationExprAsParsedObject(false);
    if (command == null)
        return null;

    try {//  w  w  w.ja  va 2 s .com
        CommandResult cmdResult = connectedDB.command(command);
        cmdResult.throwOnError();

        // wrap the commandResult DBObject in an Iterable
        BasicDBList resultList = new BasicDBList();
        resultList.add(cmdResult);
        Object resultObject = resultList;
        return (Iterable<DBObject>) resultObject;
    } catch (RuntimeException ex) {
        OdaException odaEx = new OdaException(
                Messages.bind(Messages.mDbOp_dbCmdFailed, queryProps.getOperationExpression()));
        odaEx.initCause(ex);
        throw odaEx;
    }
}

From source file:org.jongo.async.AsyncCommand.java

License:Apache License

private CommandResult executeCommand() {
    CommandResult commandResult = db.runCommand(query.toDBObject());
    if (throwOnError) {
        commandResult.throwOnError();
    }//from  w w w.ja  v  a  2  s  .c o  m
    return commandResult;
}

From source file:org.jongo.Command.java

License:Apache License

private CommandResult executeCommand() {
    CommandResult commandResult = db.command(query.toDBObject());
    if (throwOnError) {
        commandResult.throwOnError();
    }//from w w  w . j a  va  2  s  . c  om
    return commandResult;
}

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;/*from w w  w.j  ava  2  s  .co 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  .  j a  v a2  s .  c  o  m*/
    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  ava 2 s.c om

    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();
}