Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

In this page you can find the example usage for com.mongodb DBCursor count.

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:nosqltools.DBConnection.java

/**
 * Deletes a JSON object from the collection
 * @param obj JSON Objects to delete/*from   ww  w.j  a  v  a  2 s  .  c  o m*/
 * @return True if unsuccessful operation, else false
 */
public boolean deleteFromDatabase(String obj) {
    boolean flag = false;
    try {
        //If the object passed as a parameter is a JSON array, it is rejected
        if (json_util.isArray(obj)) {
            JOptionPane.showMessageDialog(null,
                    "JSON Arrays are not allowed - Change details for only one JSON object!", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else //If the object passed as a parameter is a JSON object
        {
            //Parse the object and find it the collection. The results are stored in a cursor.
            DBObject dbobj = (DBObject) JSON.parse(obj);
            DBCursor cursor = collection.find(dbobj);
            int count = cursor.count();

            //If no  objects were found
            if (cursor.count() == 0) {
                flag = true;
                JOptionPane.showMessageDialog(null, "JSON object " + dbobj + " does not exist in collection!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            } else //if objects were found for deletion
            {
                //Loop on the curser until it is equal to 0
                while (count != 0) {
                    while (cursor.hasNext()) {
                        cursor.next();
                    }

                    //Delete the object from the collection
                    if (count != 0)
                        collection.remove(dbobj);
                    count--;
                }
                JOptionPane.showMessageDialog(null,
                        "JSON Object " + dbobj + " has been removed from Collection!", "Deleted Successfully",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    } catch (MongoException me) {
        JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

    return flag;
}

From source file:nosqltools.DBConnection.java

public boolean findFromDatabase(String obj) {
    boolean flag = false;
    String result = "";
    try {//from  ww  w.j ava2 s.c om
        if (json_util.isArray(obj)) {
            JOptionPane.showMessageDialog(null,
                    "JSON Arrays are not allowed - Change details for only one JSON object!", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {

            DBObject dbobj = (DBObject) JSON.parse(obj);

            DBCursor cursor = collection.find(dbobj);
            int count = cursor.count();
            if (cursor.count() == 0) {
                flag = true;
                JOptionPane.showMessageDialog(null, "JSON object " + dbobj + " does not exist in collection!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                while (count != 0) {
                    while (cursor.hasNext()) {
                        System.out.println(cursor.next());
                    }

                    if (count != 0) {
                        result += dbobj + "\n";
                    }
                    count--;
                }
                ResultForm results = new ResultForm(result, cursor.count());
                results.setVisible(true);
            }
        }
    } catch (MongoException me) {
        JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

    return flag;
}

From source file:org.alfresco.bm.api.v1.StatusAPI.java

License:Open Source License

@GET
@Path("/logs")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w  w .ja  v a  2s  .  c om*/
public String getLogs(@QueryParam("driverId") String driverId, @QueryParam("test") String test,
        @QueryParam("run") String run, @DefaultValue("INFO") @QueryParam("level") String levelStr,
        @DefaultValue("0") @QueryParam("from") Long from,
        @DefaultValue("" + Long.MAX_VALUE) @QueryParam("to") Long to,
        @DefaultValue("0") @QueryParam("skip") int skip, @DefaultValue("50") @QueryParam("count") int count) {
    if (logger.isDebugEnabled()) {
        logger.debug("Inbound: " + "[driverId:" + driverId + ",test:" + test + ",run:" + run + ",level:"
                + levelStr + ",from:" + new Date(from) + ",to:" + new Date(to) + ",skip:" + skip + ",count:"
                + count + "]");
    }
    LogLevel level = LogLevel.INFO;
    try {
        level = LogLevel.valueOf(levelStr);
    } catch (Exception e) {
        // Just allow this
    }

    DBCursor cursor = null;
    try {
        String json = "[]";
        cursor = logService.getLogs(driverId, test, run, level, from, to, skip, count);
        if (cursor.count() > 0) {
            json = JSON.serialize(cursor);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Outbound: " + json);
        }
        return json;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throwAndLogException(Status.INTERNAL_SERVER_ERROR, e);
        return null;
    } finally {
        if (cursor != null) {
            try {
                cursor.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.alfresco.bm.cm.FileFolderService.java

License:Open Source License

/**
 * Turn a cursor into an array of API-friendly objects
 *//*from  ww  w . java 2 s  .c o  m*/
protected List<FolderData> fromDBCursor(DBCursor cursor) {
    int count = cursor.count();
    try {
        List<FolderData> folderDatas = new ArrayList<FolderData>(count);
        while (cursor.hasNext()) {
            DBObject folderDataObj = cursor.next();
            FolderData folderData = fromDBObject(folderDataObj);
            folderDatas.add(folderData);
        }
        // Done
        return folderDatas;
    } finally {
        cursor.close();
    }
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Get registered test drivers/*w w w  .  j a  v  a2s.  c  o m*/
 * 
 * @param release
 *        the release name of the test or <tt>null</tt> for all releases
 * @param schema
 *        the schema number of the driver or <tt>null</tt> for all schemas
 * @param liveOnly
 *        <tt>true</tt> to retrieve only live instances
 */
public DBCursor getDrivers(String release, Integer schema, boolean active) {
    QueryBuilder queryBuilder = QueryBuilder.start();
    if (release != null) {
        queryBuilder.and(FIELD_RELEASE).is(release);
    }
    if (schema != null) {
        queryBuilder.and(FIELD_SCHEMA).is(schema);
    }
    if (active) {
        queryBuilder.and(FIELD_PING + "." + FIELD_EXPIRES).greaterThan(new Date());
    }
    DBObject queryObj = queryBuilder.get();
    DBObject sortObj = BasicDBObjectBuilder.start().add(FIELD_RELEASE, 1).add(FIELD_SCHEMA, 1).get();

    DBCursor cursor = testDrivers.find(queryObj).sort(sortObj);

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved test driver: \n" + "   Release: " + release + "\n" + "   Schema:  " + schema
                + "\n" + "   active:  " + active + "\n" + "   Results: " + cursor.count());
    }
    return cursor;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * @param count/*www.  j a  v a 2  s .  c o  m*/
 *        the number of results to retrieve (must be greater than zero)
 * @return a list of tests, active or all
 */
public DBCursor getTestDefs(boolean active, int skip, int count) {
    if (count < 1) {
        throw new IllegalArgumentException("'count' must be larger than zero.");
    }

    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_RELEASE, true).add(FIELD_SCHEMA, true).get();
    DBObject sortObj = BasicDBObjectBuilder.start().add(FIELD_RELEASE, 1).add(FIELD_SCHEMA, 1).get();

    DBCursor cursor;
    if (active) {
        DBObject queryObj = QueryBuilder.start().put(FIELD_PING + "." + FIELD_EXPIRES)
                .greaterThanEquals(new Date()).get();
        cursor = testDrivers.find(queryObj, fieldsObj).sort(sortObj).skip(skip).limit(count);
    } else {
        cursor = testDefs.find(null, fieldsObj).sort(sortObj).skip(skip).limit(count);
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Fetching test definitions: \n" + "   active:  " + active + "\n" + "   skip:    " + skip
                + "\n" + "   count:   " + count + "\n" + "   Results: " + cursor.count());
    }
    return cursor;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Get a list of all defined tests/*from   w w w.j av  a  2  s. c om*/
 * 
 * @param release
 *        the test definition software release or <tt>null</tt> for all test
 *        releases
 * @param schema
 *        the schema number or <tt>null</tt> for all schemas
 * @return all the currently-defined tests
 */
public DBCursor getTests(String release, Integer schema, int skip, int count) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (release != null && release.length() > 0) {
        queryObjBuilder.add(FIELD_RELEASE, release);
    }
    if (schema != null) {
        queryObjBuilder.add(FIELD_SCHEMA, schema);
    }
    DBObject queryObj = queryObjBuilder.get();

    // We don't want everything just now
    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_NAME, true).add(FIELD_VERSION, true)
            .add(FIELD_DESCRIPTION, true).add(FIELD_RELEASE, true).add(FIELD_SCHEMA, true).get();

    DBCursor dbCursor = tests.find(queryObj, fieldsObj).skip(skip).limit(count);

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Fetched tests: \n" + "   Release: " + release + "\n" + "   Schema:  " + schema + "\n"
                + "   Results: " + dbCursor.count());
    }
    return dbCursor;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Get the test run names associated with a given test
 * /*from   w  w  w.j  av a2 s.  c om*/
 * @param test
 *        the name of the test
 * @return the names of all test runs associated with the given test
 */
public List<String> getTestRunNames(String test) {
    DBObject testObj = getTest(test, false);
    if (testObj == null) {
        // The test no longer exists, so the run effectively doesn't either
        logger.warn("Test not found: " + test);
        return Collections.emptyList();
    }
    ObjectId testObjId = (ObjectId) testObj.get(FIELD_ID);

    DBObject queryObj = QueryBuilder.start().and(FIELD_TEST).is(testObjId).get();
    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_ID, true).add(FIELD_NAME, true).get();
    DBCursor cursor = testRuns.find(queryObj, fieldsObj);
    List<String> testRunNames = new ArrayList<String>(cursor.count());
    try {
        while (cursor.hasNext()) {
            DBObject testRunObj = cursor.next();
            String testRunName = (String) testRunObj.get(FIELD_NAME);
            testRunNames.add(testRunName);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Found and returned " + testRunNames.size() + " test run names for test '" + test + "'");
    }
    return testRunNames;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * @param test/* w  ww  .  ja  v  a2 s .  com*/
 *        only fetch runs for this test or <tt>null</tt> to get all test
 *        runs
 * @param testRunStates
 *        optional states that the test runs must be in or empty for all
 * @return a cursor onto the test runs for the given test
 */
public DBCursor getTestRuns(String test, int skip, int count, TestRunState... testRunStates) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (test != null) {
        ObjectId testObjId = getTestId(test);
        if (testObjId == null) {
            // The test no longer exists, so the run effectively doesn't
            // either
            logger.warn("Test not found: " + test);
            // Use a ficticious ID that will never match
            testObjId = new ObjectId();
        }
        queryObjBuilder.add(FIELD_TEST, testObjId);
    }

    // Build query for the test run states
    if (testRunStates.length > 0) {
        List<String> stateStrs = new ArrayList<String>(testRunStates.length);
        for (int i = 0; i < testRunStates.length; i++) {
            stateStrs.add(testRunStates[i].toString());
        }
        queryObjBuilder.push(FIELD_STATE);
        queryObjBuilder.add("$in", stateStrs);
    }

    DBObject queryObj = queryObjBuilder.get();

    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_NAME, true).add(FIELD_TEST, true)
            .add(FIELD_VERSION, true).add(FIELD_DESCRIPTION, true).add(FIELD_STATE, true)
            .add(FIELD_SCHEDULED, true).add(FIELD_STARTED, true).add(FIELD_STOPPED, true)
            .add(FIELD_COMPLETED, true).add(FIELD_DURATION, true).add(FIELD_PROGRESS, true)
            .add(FIELD_RESULTS_SUCCESS, true).add(FIELD_RESULTS_FAIL, true).add(FIELD_RESULTS_TOTAL, true)
            .add(FIELD_SUCCESS_RATE, true).get();

    DBCursor dbCursor = testRuns.find(queryObj, fieldsObj).skip(skip).limit(count);

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Fetched test runs: \n" + "   Test:    " + test + "\n" + "   Results: " + dbCursor.count());
    }
    return dbCursor;
}

From source file:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

/**
 * Turn a cursor into an array of API-friendly objects
 *//*from w w  w  . ja  va 2  s .c  o  m*/
protected List<UserData> fromDBCursor(DBCursor cursor) {
    int count = cursor.count();
    try {
        List<UserData> userDatas = new ArrayList<UserData>(count);
        while (cursor.hasNext()) {
            DBObject userDataObj = cursor.next();
            UserData userData = fromDBObject(userDataObj);
            userDatas.add(userData);
        }
        // Done
        return userDatas;
    } finally {
        cursor.close();
    }
}