Example usage for com.mongodb CommandResult get

List of usage examples for com.mongodb CommandResult get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:org.Cherry.Modules.Mongo.Middleware.MongoRepositoryService.java

License:LGPL

public void setup() {
    setMongo(new MongoClient(getServerAddresses()));

    info("Using Mongo connector version [{}].", getMongo().getVersion());

    final DB db = getMongo().getDB(DEFAULT_DB_NAME);

    assert null != db;

    try {/*from w w  w.j ava2 s.  com*/
        final CommandResult dbStats = db.getStats();

        final Set<?> keys = dbStats.keySet();
        Object entry;

        info("Executing & listing 'dbStats' for [{}].", db.getName());
        for (final Object key : keys) {
            entry = dbStats.get(key);

            info("{'key':'{}', 'value':'{}'}", key, entry);
        }
    } catch (final MongoServerSelectionException t) {
        error("\n-----------------------------------------------------------------------------------------------\n!Error [{}] occured when testing connectivity to [{}] database!\n-----------------------------------------------------------------------------------------------",
                t.getMessage(), db.getName());
    } catch (final Throwable t) {
        error(t, t.getMessage());
    }
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
protected Object generateIdentifier(final PersistentEntity persistentEntity, final DBObject nativeEntry) {
    return mongoTemplate.execute(new DbCallback<Object>() {
        public Object doInDB(DB con) throws MongoException, DataAccessException {

            @SuppressWarnings("hiding")
            String collectionName = getCollectionName(persistentEntity, nativeEntry);

            DBCollection dbCollection = con.getCollection(collectionName + NEXT_ID_SUFFIX);

            // If there is a numeric identifier then we need to rely on optimistic concurrency controls to obtain a unique identifer
            // sequence. If the identifier is not numeric then we assume BSON ObjectIds.
            if (hasNumericalIdentifier) {
                while (true) {
                    DBCursor result = dbCollection.find().sort(new BasicDBObject(MONGO_ID_FIELD, -1)).limit(1);

                    long nextId;
                    if (result.hasNext()) {
                        final Long current = getMappingContext().getConversionService()
                                .convert(result.next().get(MONGO_ID_FIELD), Long.class);
                        nextId = current + 1;
                    } else {
                        nextId = 1;//from w  ww .  j av  a 2 s .  c o m
                    }

                    nativeEntry.put(MONGO_ID_FIELD, nextId);
                    final WriteResult writeResult = dbCollection.insert(nativeEntry);
                    final CommandResult lastError = writeResult.getLastError();
                    if (lastError.ok()) {
                        break;
                    }

                    final Object code = lastError.get("code");
                    // duplicate key error try again
                    if (code != null && code.equals(11000)) {
                        continue;
                    }
                    break;
                }

                return nativeEntry.get(MONGO_ID_FIELD);
            }

            ObjectId objectId = ObjectId.get();
            if (ObjectId.class.isAssignableFrom(persistentEntity.getIdentity().getType())) {
                nativeEntry.put(MONGO_ID_FIELD, objectId);
                return objectId;
            }

            String stringId = objectId.toString();
            nativeEntry.put(MONGO_ID_FIELD, stringId);
            return stringId;
        }
    });
}

From source file:org.graylog2.system.stats.mongo.MongoProbe.java

License:Open Source License

private HostInfo createHostInfo() {
    final HostInfo hostInfo;
    final CommandResult hostInfoResult = adminDb.command("hostInfo");
    if (hostInfoResult.ok()) {
        final BasicDBObject systemMap = (BasicDBObject) hostInfoResult.get("system");
        final HostInfo.System system = HostInfo.System.create(new DateTime(systemMap.getDate("currentTime")),
                systemMap.getString("hostname"), systemMap.getInt("cpuAddrSize"),
                systemMap.getLong("memSizeMB"), systemMap.getInt("numCores"), systemMap.getString("cpuArch"),
                systemMap.getBoolean("numaEnabled"));
        final BasicDBObject osMap = (BasicDBObject) hostInfoResult.get("os");
        final HostInfo.Os os = HostInfo.Os.create(osMap.getString("type"), osMap.getString("name"),
                osMap.getString("version"));

        final BasicDBObject extraMap = (BasicDBObject) hostInfoResult.get("extra");
        final HostInfo.Extra extra = HostInfo.Extra.create(extraMap.getString("versionString"),
                extraMap.getString("libcVersion"), extraMap.getString("kernelVersion"),
                extraMap.getString("cpuFrequencyMHz"), extraMap.getString("cpuFeatures"),
                extraMap.getString("scheduler"), extraMap.getLong("pageSize", -1l),
                extraMap.getLong("numPages", -1l), extraMap.getLong("maxOpenFiles", -1l));

        hostInfo = HostInfo.create(system, os, extra);
    } else {// www  . ja v a2s  .c om
        hostInfo = null;
    }

    return hostInfo;
}

From source file:org.graylog2.system.stats.mongo.MongoProbe.java

License:Open Source License

private BuildInfo createBuildInfo() {
    final BuildInfo buildInfo;
    final CommandResult buildInfoResult = adminDb.command("buildInfo");
    if (buildInfoResult.ok()) {
        buildInfo = BuildInfo.create(buildInfoResult.getString("version"),
                buildInfoResult.getString("gitVersion"), buildInfoResult.getString("sysInfo"),
                buildInfoResult.getString("loaderFlags"), buildInfoResult.getString("compilerFlags"),
                buildInfoResult.getString("allocator"), (List<Integer>) buildInfoResult.get("versionArray"),
                buildInfoResult.getString("javascriptEngine"), buildInfoResult.getInt("bits"),
                buildInfoResult.getBoolean("debug"), buildInfoResult.getLong("maxBsonObjectSize")

        );/*ww  w .  j a  va 2 s  . c  o m*/
    } else {
        buildInfo = null;
    }

    return buildInfo;
}

From source file:org.graylog2.system.stats.mongo.MongoProbe.java

License:Open Source License

public MongoStats mongoStats() {
    final List<ServerAddress> serverAddresses = mongoClient.getServerAddressList();
    final List<HostAndPort> servers = Lists.newArrayListWithCapacity(serverAddresses.size());
    for (ServerAddress serverAddress : serverAddresses) {
        servers.add(HostAndPort.fromParts(serverAddress.getHost(), serverAddress.getPort()));
    }//from   ww  w .  jav a 2s .com

    final DatabaseStats dbStats;
    final CommandResult dbStatsResult = db.command("dbStats");
    if (dbStatsResult.ok()) {
        final BasicDBObject extentFreeListMap = (BasicDBObject) dbStatsResult.get("extentFreeList");
        final DatabaseStats.ExtentFreeList extentFreeList = DatabaseStats.ExtentFreeList
                .create(extentFreeListMap.getInt("num"), extentFreeListMap.getInt("totalSize"));

        final BasicDBObject dataFileVersionMap = (BasicDBObject) dbStatsResult.get("dataFileVersion");
        final DatabaseStats.DataFileVersion dataFileVersion = DatabaseStats.DataFileVersion
                .create(dataFileVersionMap.getInt("major"), dataFileVersionMap.getInt("minor"));

        dbStats = DatabaseStats.create(dbStatsResult.getString("db"), dbStatsResult.getLong("collections"),
                dbStatsResult.getLong("objects"), dbStatsResult.getDouble("avgObjSize"),
                dbStatsResult.getLong("dataSize"), dbStatsResult.getLong("storageSize"),
                dbStatsResult.getLong("numExtents"), dbStatsResult.getLong("indexes"),
                dbStatsResult.getLong("indexSize"), dbStatsResult.getLong("fileSize"),
                dbStatsResult.getLong("nsSizeMB"), extentFreeList, dataFileVersion);
    } else {
        dbStats = null;
    }

    final ServerStatus serverStatus;
    final CommandResult serverStatusResult = adminDb.command("serverStatus");
    if (serverStatusResult.ok()) {
        final BasicDBObject connectionsMap = (BasicDBObject) serverStatusResult.get("connections");
        final ServerStatus.Connections connections = ServerStatus.Connections.create(
                connectionsMap.getInt("current"), connectionsMap.getInt("available"),
                connectionsMap.getLong("totalCreated"));

        final BasicDBObject networkMap = (BasicDBObject) serverStatusResult.get("network");
        final ServerStatus.Network network = ServerStatus.Network.create(networkMap.getInt("bytesIn"),
                networkMap.getInt("bytesOut"), networkMap.getInt("numRequests"));

        final BasicDBObject memoryMap = (BasicDBObject) serverStatusResult.get("mem");
        final ServerStatus.Memory memory = ServerStatus.Memory.create(memoryMap.getInt("bits"),
                memoryMap.getInt("resident"), memoryMap.getInt("virtual"), memoryMap.getBoolean("supported"),
                memoryMap.getInt("mapped"), memoryMap.getInt("mappedWithJournal"));

        serverStatus = ServerStatus.create(serverStatusResult.getString("host"),
                serverStatusResult.getString("version"), serverStatusResult.getString("process"),
                serverStatusResult.getLong("pid"), serverStatusResult.getInt("uptime"),
                serverStatusResult.getLong("uptimeMillis"), serverStatusResult.getInt("uptimeEstimate"),
                new DateTime(serverStatusResult.getDate("localTime")), connections, network, memory);
    } else {
        serverStatus = null;
    }

    // TODO Collection stats? http://docs.mongodb.org/manual/reference/command/collStats/

    return MongoStats.create(servers, buildInfo, hostInfo, serverStatus, dbStats);
}

From source file:org.jongo.util.JongoTestBase.java

License:Apache License

protected void assumeThatMongoVersionIsGreaterThan(String expectedVersion) throws UnknownHostException {
    int expectedVersionAsInt = Integer.valueOf(expectedVersion.replaceAll("\\.", ""));
    CommandResult buildInfo = getDatabase().command("buildInfo");
    String version = (String) buildInfo.get("version");
    int currentVersion = Integer.valueOf(version.replaceAll("\\.", ""));
    assumeTrue(currentVersion >= expectedVersionAsInt);
}

From source file:org.mule.modules.morphia.MorphiaConnector.java

License:Open Source License

/**
 * Calculates aggregates values without the need for complex map-reduce operations
 *
 * <p/>//  w  ww .  j a v a2s.  c om
 * {@sample.xml ../../../doc/mule-module-morphia.xml.sample morphia:aggregate}
 *
 * @param collection collection name
 * @param pipeline list of pipeline operators
 * @param exception The exception that needs to be thrown if there is an error executing the aggregation query
 * @param username the username to use in case authentication is required
 * @param password the password to use in case authentication is required, null
 *                 if no authentication is desired
 * @param host     The host of the Mongo server. If the host is part of a replica set then you can specify all the hosts
 *                 separated by comma.
 * @param port     The port of the Mongo server
 * @param database The database name of the Mongo server
 * @return the aggregation result
 * @throws Exception if there is an exception while aggregating
 */
@Processor
public BasicDBList aggregate(String collection, List<Pipeline> pipeline, @Optional String exception,
        @Optional String username, @Optional @Password String password, @Optional String host,
        @Optional Integer port, @Optional String database) throws Exception {
    if (!pipeline.isEmpty()) {
        Datastore datastore = getDatastore(username, password, database, host, port);
        List<DBObject> dbObjects = new ArrayList<DBObject>();
        for (Pipeline pipelineOperator : pipeline) {
            Object dbObject = JSON.parse(pipelineOperator.toJson());
            if (dbObject == null || !(dbObject instanceof DBObject)) {
                throw new IllegalArgumentException("Illegal pipeline operator '" + pipelineOperator + "'");
            }
            dbObjects.add((DBObject) dbObject);
        }
        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("aggregate", collection);
        builder.append("pipeline", dbObjects.toArray());
        CommandResult result = datastore.getDB().command(builder.get());
        if (result.ok()) {
            return (BasicDBList) result.get("result");
        }
        if (exception != null) {
            throw getExceptionFromClassName(exception);
        }
    }
    // Return an empty list
    return new BasicDBList();
}

From source file:org.restheart.db.MongoDBClientSingleton.java

License:Open Source License

private void setup() throws UnknownHostException {
    if (isInitialized()) {
        mongoClient = new MongoClient(mongoUri);
    }//from   w  w  w .  j  a  va  2s. c  om

    try {
        CommandResult res = mongoClient.getDB("admin").command("buildInfo");
        Object _version = res.get("version");

        if (_version != null && _version instanceof String) {
            serverVersion = (String) _version;
        } else {
            LOGGER.warn("Cannot get the MongoDb version.");
            serverVersion = "3.x?";
        }
    } catch (Throwable t) {
        LOGGER.warn("Cannot get the MongoDb version.");
        serverVersion = "?";
    }
}

From source file:org.search.system.models.MongoInstance.java

License:Open Source License

public int getSize() {
    int size;//w ww  .  ja  v a 2 s . c om
    MongoClient mongo = new MongoClient(host, port);
    DB synonyms = mongo.getDB("synonyms");
    DB pages = mongo.getDB("pages");
    CommandResult result = synonyms.getStats();
    size = (int) result.get("objects");
    result = pages.getStats();
    size += (int) result.get("objects");
    mongo.close();
    return size;
}

From source file:org.sglover.alfrescoextensions.common.MongoDbFactory.java

License:Open Source License

public DB createInstance() throws Exception {
    DB db = null;/*from w w  w.  ja va2 s . co  m*/

    try {
        if (enabled) {
            if (embedded) {
                Mongo mongo = newMongo();
                //                    Mongo mongo = mongoFactory.newMongo();
                if (dbName != null) {
                    db = mongo.getDB(dbName);
                } else {
                    db = mongo.getDB(UUID.randomUUID().toString());
                }
            } else {
                if (mongoURI == null || dbName == null) {
                    throw new RuntimeException("Must provide mongoURI and dbName or a mongo object");
                }
                MongoClientURI uri = new MongoClientURI(mongoURI);
                MongoClient mongoClient = new MongoClient(uri);
                db = mongoClient.getDB(dbName);
            }

            if (db == null) {
                throw new InstantiationException("Could not instantiate a Mongo DB instance");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Instatiated DB object for dbName '" + db.getName() + "'");
            }
            CommandResult stats = db.getStats();
            if (logger.isTraceEnabled()) {
                stats = db.getStats();
                for (String key : stats.keySet()) {
                    logger.trace("\t" + key + " = " + stats.get(key).toString());
                }
            }
        }
    } catch (MongoException.Network e) {
        throw new MongoDbUnavailableException("Mongo network exception, database down?", e);
    } catch (UnknownHostException e) {
        throw new MongoDbUnavailableException("Mongo host not found", e);
    }
    return db;
}