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.stratio.connector.mongodb.core.engine.metadata.ShardUtils.java

License:Apache License

/**
 * Enable sharding in the database.//from www.  j  a  v a 2  s  . c  o m
 *
 * @param mongoClient
 *            the mongo client
 * @param databaseName
 *            the database name
 * @throws ExecutionException
 *             if an error exist when enabling sharding
 */
private static void enableSharding(MongoClient mongoClient, String databaseName) throws ExecutionException {

    DB db;

    db = mongoClient.getDB("admin");
    DBObject enableShardingCommand = new BasicDBObject("enableSharding", databaseName);
    CommandResult result = db.command(enableShardingCommand);
    if (!result.ok() && !result.getErrorMessage().equals("already enabled")) {
        LOGGER.error("Error executing" + enableShardingCommand + " :" + result.getErrorMessage());
        throw new ExecutionException(result.getErrorMessage());
    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

License:Open Source Community License

private void processScriptFile(final DB db, final File scriptFile) throws MojoExecutionException {
    Scanner scanner = null;/*w  w  w .j a  v a  2  s .co m*/
    final StringBuilder instructions = new StringBuilder();
    try {
        scanner = new Scanner(scriptFile);
        while (scanner.hasNextLine()) {
            instructions.append(scanner.nextLine()).append("\n");
        }
    } catch (final FileNotFoundException e) {
        throw new MojoExecutionException("Unable to find file with name '" + scriptFile.getName() + "'", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    final CommandResult result;
    try {
        final String evalString = "(function() {" + instructions.toString() + "})();";
        result = db.doEval(evalString, new Object[0]);
    } catch (final MongoException e) {
        throw new MojoExecutionException("Unable to execute file with name '" + scriptFile.getName() + "'", e);
    }
    if (!result.ok()) {
        getLog().error("- file " + scriptFile.getName() + " parsed with error: " + result.getErrorMessage());
        throw new MojoExecutionException("Error while executing instructions from file '" + scriptFile.getName()
                + "': " + result.getErrorMessage(), result.getException());
    }
    getLog().info("- file " + scriptFile.getName() + " parsed successfully");
}

From source file:de.otto.mongodb.profiler.collection.DefaultCollectionProfiler.java

License:Apache License

protected void newSample(DefaultCollectionProfile profile) {

    final DBCollection collection = database.getCollection(profile.getCollectionName());
    final CommandResult result = collection.getStats();
    if (result.ok()) {
        profile.add(result);//from   w  ww  . j a  va2s .  co m
    } else {
        if ("ns not found".equals(result.getErrorMessage())) {
            profile.reset();
        }
    }
}

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 {//  ww w.  j  a  v a2 s  .co  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:net.handle.server.MongoDBHandleStorage.java

License:Open Source License

/**
 * Copies the database to another://from  w w  w  .  ja v a  2 s.  c o  m
 * checkpoint_[database name]
 *
 * @throws HandleException
 */
public void checkpointDatabase() throws HandleException {

    final String checkpoint = database + "_checkpoint_" + new Date().getTime();
    final BasicDBObject command = new BasicDBObject();
    command.put("copydb", 1);
    command.put("fromdb", database);
    command.put("todb", checkpoint);

    final DB db = mongo.getDB("admin");
    final CommandResult result = db.command(command);
    if (!result.ok()) {
        throw new HandleException(HandleException.SERVER_ERROR,
                "The checkpoint action failed:\n" + result.getErrorMessage());
    }
}

From source file:net.tooan.ynpay.third.mongodb.BuguAggregation.java

License:Apache License

public Iterable<DBObject> results() throws AggregationException {
    int size = pipeline.size();
    if (size <= 0) {
        throw new AggregationException("Empty pipeline in aggregation!");
    }/*w w  w.j av  a 2  s .c  o m*/
    AggregationOutput output = null;
    if (size == 1) {
        output = coll.aggregate(pipeline.get(0));
    } else {
        DBObject firstOp = pipeline.get(0);
        List<DBObject> subList = pipeline.subList(1, size);
        DBObject[] arr = subList.toArray(new DBObject[size - 1]);
        output = coll.aggregate(firstOp, arr);
    }
    CommandResult cr = output.getCommandResult();
    if (!cr.ok()) {
        throw new AggregationException(cr.getErrorMessage());
    }
    return output.results();
}

From source file:net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java

License:Apache License

public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, DBObject query)
        throws OperatorException {
    MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, null, OutputType.INLINE,
            query);//from   ww w .  j a  va2s .  c o m
    CommandResult _result = _output.getCommandResult();
    if (!_result.ok()) {
        throw new OperatorException(_result.getErrorMessage());
    }
    return _output.results();
}

From source file:net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java

License:Apache License

public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, String outputTarget,
        OutputType type, OrderBy order, int pageNumber, int pageSize, DBObject query) throws OperatorException {
    MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, outputTarget, type, query);
    CommandResult _result = _output.getCommandResult();
    if (!_result.ok()) {
        throw new OperatorException(_result.getErrorMessage());
    }/*w w w .  ja v a 2 s .c  o  m*/
    DBCollection _collection = _output.getOutputCollection();
    DBCursor _cursor = null;
    if (order != null) {
        _cursor = _collection.find().sort(order.toDBObject());
    } else {
        _cursor = _collection.find();
    }
    if (pageNumber > 0 && pageSize > 0) {
        _cursor.skip((pageNumber - 1) * pageSize).limit(pageSize);
    }
    List<DBObject> _results = new ArrayList<DBObject>();
    for (Iterator<DBObject> _it = _cursor.iterator(); _it.hasNext();) {
        _results.add(_it.next());
    }
    return _results;
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java

License:Apache License

@Override
public long determineServerTimeDifferenceMillis() {
    // the assumption is that the network delay from this instance
    // to the server, and from the server back to this instance
    // are (more or less) equal.
    // taking this assumption into account allows to remove
    // the network delays from the picture: the difference
    // between end and start time is exactly this network
    // delay (plus some server time, but that's neglected).
    // so if the clocks are in perfect sync and the above
    // mentioned assumption holds, then the server time should
    // be exactly at the midPoint between start and end.
    // this should allow a more accurate picture of the diff.
    final long start = System.currentTimeMillis();
    // assumption here: server returns UTC - ie the returned
    // date object is correctly taking care of time zones.
    final CommandResult serverStatus = db.command("serverStatus");
    if (serverStatus == null) {
        // OAK-4107 / OAK-4515 : extra safety
        LOG.warn(/*  w ww. j a  va2 s .co  m*/
                "determineServerTimeDifferenceMillis: db.serverStatus returned null - cannot determine time difference - assuming 0ms.");
        return 0;
    }
    final Date serverLocalTime = serverStatus.getDate("localTime");
    if (serverLocalTime == null) {
        // OAK-4107 / OAK-4515 : looks like this can happen - at least
        // has been seen once on mongo 3.0.9
        // let's handle this gently and issue a log.warn
        // instead of throwing a NPE
        LOG.warn(
                "determineServerTimeDifferenceMillis: db.serverStatus.localTime returned null - cannot determine time difference - assuming 0ms. "
                        + "(Result details: server exception=" + serverStatus.getException()
                        + ", server error message=" + serverStatus.getErrorMessage() + ")",
                serverStatus.getException());
        return 0;
    }
    final long end = System.currentTimeMillis();

    final long midPoint = (start + end) / 2;
    final long serverLocalTimeMillis = serverLocalTime.getTime();

    // the difference should be
    // * positive when local instance is ahead
    // * and negative when the local instance is behind
    final long diff = midPoint - serverLocalTimeMillis;

    return diff;
}

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

License:Open Source License

static void authenticateDB(DB mongoDb, Properties connProps) throws OdaException {
    if (mongoDb.isAuthenticated())
        return; // already authenticated

    String username = MongoDBDriver.getUserName(connProps);
    if (username == null || username.isEmpty())
        return; // nothing to authenticate

    String passwd = MongoDBDriver.getPassword(connProps);
    char[] passwdChars = passwd != null ? passwd.toCharArray() : new char[0];

    CommandResult result = null;
    try {/*from  ww  w.ja va 2  s.  c  o  m*/
        result = mongoDb.authenticateCommand(username, passwdChars);
    } catch (Exception ex) {
        OdaException odaEx = null;
        if (result != null) {
            odaEx = new OdaException(result.getErrorMessage());
            odaEx.initCause(ex);
        } else
            odaEx = new OdaException(ex);

        MongoDBDriver.getLogger()
                .info(Messages.bind("Unable to authenticate user (${0}) in database (${1}).\n ${2}", //$NON-NLS-1$
                        new Object[] { username, mongoDb, odaEx.getCause().getMessage() }));
        throw odaEx;
    }
}