Example usage for com.mongodb DBCursor length

List of usage examples for com.mongodb DBCursor length

Introduction

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

Prototype

public int length() 

Source Link

Document

Pulls back all items into an array and returns the number of objects.

Usage

From source file:bhl.pages.database.MongoConnection.java

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @param key the document key to retrieve by
 * @return a String array of document keys
 * @throws DbException //w  ww  . ja  v a2s .  c  om
 */
@Override
public String[] listCollectionByKey(String collName, String key) throws DbException {
    try {
        connect();
    } catch (Exception e) {
        throw new DbException(e);
    }
    DBCollection coll = getCollectionFromName(collName);
    BasicDBObject keys = new BasicDBObject();
    keys.put(key, 1);
    DBCursor cursor = coll.find(new BasicDBObject(), keys);
    if (cursor.length() > 0) {
        String[] docs = new String[cursor.length()];
        Iterator<DBObject> iter = cursor.iterator();
        int i = 0;
        while (iter.hasNext()) {
            Object obj = iter.next().get(key);
            docs[i++] = obj.toString();
        }
        return docs;
    } else
        throw new DbException("no docs in collection " + collName);
}

From source file:bhl.pages.database.MongoConnection.java

License:Open Source License

/**
 * Make a subset of the documents by a given subkey and value, 
 * then retrieve all the values of the field
 * @param collection the collection to search
 * @param subKey the subKey to make the initial choice
 * @param subValue the value of the subKey to search for
 * @param fields the field names to retrieve
 * @return and array of field values as JSON object strings
 * @throws DbException //from  ww w .  j av a2s.co  m
 */
@Override
public String[] listCollectionBySubKey(String collection, String subKey, String subValue, String[] fields)
        throws DbException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collection);
        DBObject query = new BasicDBObject(subKey, subValue);
        BasicDBObject keys = new BasicDBObject();
        for (int i = 0; i < fields.length; i++)
            keys.put(fields[i], 1);
        DBCursor cursor = coll.find(query, keys);
        if (cursor.length() > 0) {
            String[] array = new String[cursor.length()];
            Iterator iter = cursor.iterator();
            int i = 0;
            while (iter.hasNext()) {
                DBObject bson = (DBObject) iter.next();
                JSONObject jobj = new JSONObject();
                for (int j = 0; j < fields.length; j++)
                    jobj.put(fields[j], bson.get(fields[j]));
                array[i++] = jobj.toJSONString();
            }
            return array;
        } else
            return new String[0];
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @param key the document key to retrieve by
 * @return a String array of document keys
 * @throws DbException /*from w  ww  . ja  va  2  s.co m*/
 */
@Override
public String[] listCollectionByKey(String collName, String key) throws DbException {
    try {
        connect();
    } catch (Exception e) {
        throw new DbException(e);
    }
    DBCollection coll = getCollectionFromName(collName);
    BasicDBObject keys = new BasicDBObject();
    keys.put(key, 1);
    DBCursor cursor = coll.find(new BasicDBObject(), keys);
    if (cursor.length() > 0) {
        String[] docs = new String[cursor.length()];
        Iterator<DBObject> iter = cursor.iterator();
        int i = 0;
        while (iter.hasNext()) {
            DBObject dbObj = iter.next();
            Object obj = dbObj.get(key);
            if (key.equals(JSONKeys._ID)) {
                ObjectId id = (ObjectId) dbObj.get(JSONKeys._ID);
                obj = id.toStringMongod();
                docs[i++] = (String) obj;
            } else
                docs[i++] = obj.toString();
        }
        return docs;
    } else
        return new String[0];
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @return a String array of document keys
 * @throws DbException //from w  w w . ja v  a 2  s .c  om
 */
@Override
public String[] listCollection(String collName) throws DbException {
    try {
        connect();
    } catch (Exception e) {
        throw new DbException(e);
    }
    DBCollection coll = getCollectionFromName(collName);
    BasicDBObject keys = new BasicDBObject();
    keys.put(JSONKeys.DOCID, 1);
    DBCursor cursor = coll.find(new BasicDBObject(), keys);
    if (cursor.length() > 0) {
        String[] docs = new String[cursor.length()];
        Iterator<DBObject> iter = cursor.iterator();
        int i = 0;
        while (iter.hasNext())
            docs[i++] = (String) iter.next().get(JSONKeys.DOCID);
        return docs;
    } else
        return new String[0];
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @return a String array of document keys
 * @throws AeseException /*from   www . j  av  a2s. c  o m*/
 */
@Override
public String[] listCollection(String collName) throws AeseException {
    if (!collName.equals(Database.CORPIX)) {
        try {
            connect();
        } catch (Exception e) {
            throw new AeseException(e);
        }
        DBCollection coll = getCollectionFromName(collName);
        BasicDBObject keys = new BasicDBObject();
        keys.put(JSONKeys.DOCID, 1);
        DBCursor cursor = coll.find(new BasicDBObject(), keys);
        System.out.println("Found " + cursor.count() + " documents");
        cursor.count();
        if (cursor.length() > 0) {
            String[] docs = new String[cursor.length()];
            Iterator<DBObject> iter = cursor.iterator();
            int i = 0;
            while (iter.hasNext())
                docs[i++] = (String) iter.next().get(JSONKeys.DOCID);
            return docs;
        } else {
            return new String[0];
        }
    } else {
        GridFS gfs = new GridFS(db, collName);
        DBCursor curs = gfs.getFileList();
        int i = 0;
        List<DBObject> list = curs.toArray();
        HashSet<String> set = new HashSet<String>();
        Iterator<DBObject> iter = list.iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next().get("filename");
            set.add(name);
        }
        String[] docs = new String[set.size()];
        set.toArray(docs);
        return docs;
    }
}

From source file:com.bbc.remarc.ws.ThemeServiceImpl.java

License:Apache License

@GET
@Produces("application/json")
public Response find() {

    List<DBObject> results = new ArrayList<DBObject>();

    DB db = MongoClient.getDB();//from   ww  w . j ava 2s . co  m
    db.requestStart();

    DBCollection theme = db.getCollection(COLLECTION_NAME);
    DBCursor cursor = theme.find().limit(NUM_THEMES);

    if (cursor.length() != NUM_THEMES) {
        throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR)
                .entity("unexpected number of themes returned").build());
    }

    results = cursor.toArray();

    db.requestDone();

    return Response.ok(String.format("%s", results)).build();
}

From source file:com.icoin.trading.webui.init.SystemController.java

License:Apache License

@RequestMapping(value = "/collection/{id}", method = RequestMethod.GET)
public String collection(@PathVariable("id") String collectionName,
        @RequestParam(value = "page", defaultValue = "1") int pageNumber,
        @RequestParam(value = "itemsperpage", defaultValue = "5") int itemsPerPage, Model model) {
    DBCursor dbCursor = springTemplate.getCollection(collectionName).find();
    List<DBObject> dbObjects = dbCursor.skip((pageNumber - 1) * itemsPerPage).limit(itemsPerPage).toArray();

    List<Map> items = new ArrayList<Map>(dbCursor.length());
    for (DBObject dbObject : dbObjects) {
        items.add(dbObject.toMap());/*from w ww.  j  a va 2  s.c  o  m*/
    }
    model.addAttribute("items", items);

    int totalItems = dbCursor.count();
    int numPages = ((int) Math.floor(totalItems / itemsPerPage)) + 1;
    model.addAttribute("numPages", numPages);
    model.addAttribute("page", pageNumber);
    model.addAttribute("itemsPerPage", itemsPerPage);
    model.addAttribute("collectionName", collectionName);
    return "data/collection";
}

From source file:com.ikanow.infinit.e.api.utils.RESTTools.java

License:Open Source License

/**
 * Creates a new session for a user, adding
 * an entry to our cookie table (maps cookieid
 * to userid) and starts the clock/*from   w  ww. j  a v a2 s .co m*/
 * 
 * @param username
 * @param bMulti if true lets you login from many sources
 * @param bOverride if false will fail if already logged in
 * @return
 */
public static ObjectId createSession(ObjectId userid, boolean bMulti, boolean bOverride) {

    try {
        DBCollection cookieColl = DbManager.getSocial().getCookies();

        if (!bMulti) { // Otherwise allow multiple cookies for this user
            //remove any old cookie for this user
            BasicDBObject dbQuery = new BasicDBObject();
            dbQuery.put("profileId", userid);
            dbQuery.put("apiKey", new BasicDBObject(DbManager.exists_, false));
            DBCursor dbc = cookieColl.find(dbQuery);
            if (bOverride) {
                while (dbc.hasNext()) {
                    cookieColl.remove(dbc.next());
                }
            } //TESTED
            else if (dbc.length() > 0) {
                return null;
            } //TESTED
        }
        //Find user
        //create a new entry
        CookiePojo cp = new CookiePojo();
        ObjectId randomObjectId = generateRandomId();

        cp.set_id(randomObjectId);
        cp.setCookieId(randomObjectId);
        cp.setLastActivity(new Date());
        cp.setProfileId(userid);
        cp.setStartDate(new Date());
        cookieColl.insert(cp.toDb());
        //return cookieid
        return cp.getCookieId();
    } catch (Exception e) {
        logger.error("Line: [" + e.getStackTrace()[2].getLineNumber() + "] " + e.getMessage());
        e.printStackTrace();
    }

    return null;
}

From source file:eu.artist.postmigration.nfrvt.strategy.benchmark.AvailabilityCalculator.java

License:Open Source License

public static MultipleDCResults calculateCloudSleuthAvailability(int startYear, int startMonth, int startDay,
        int stopYear, int stopMonth, int stopDay) {

    try {/*from  w  w w  .j  av  a 2 s .c o  m*/
        Properties propertiesFile = BenchmarkConstants.getProperties();
        String databaseIP = propertiesFile.getProperty("3alibIP");
        MultipleDCResults response = new MultipleDCResults();
        double CloudSleuthAvailability = 0;
        double CloudSleuthDowntime = 0;
        Mongo mongoClient;
        mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address:" + databaseIP);
        DBCollection coll = db.getCollection("log_samples");
        Date date = new Date();
        Calendar calendarFrom = Calendar.getInstance();
        calendarFrom.setTime(date);
        calendarFrom.set(startYear, startMonth - 1, startDay, 0, 0, 0);
        Date dateFrom = calendarFrom.getTime();
        Calendar calendarTo = Calendar.getInstance();
        calendarTo.setTime(date);
        calendarTo.set(stopYear, stopMonth - 1, stopDay, 23, 59, 59);
        Date dateTo = calendarTo.getTime();
        System.out.println("Date beginning:" + dateFrom.toString());
        System.out.println("Date ending:" + dateTo.toString());
        ObjectId from = new ObjectId(dateFrom);
        ObjectId to = new ObjectId(dateTo);
        List<?> distinctTemplates = coll.distinct("location.parent.id");

        for (int i = 0; i < distinctTemplates.size(); i++) {
            System.out.println("Region ID:" + distinctTemplates.get(i).toString());
            BasicDBObject queryPerRegionOverall = new BasicDBObject("_id",
                    new BasicDBObject("$gte", from).append("$lte", to)).append("location.parent.id",
                            distinctTemplates.get(i).toString());

            DBCursor cursorOverall;
            cursorOverall = coll.find(queryPerRegionOverall);
            cursorOverall.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);

            System.out.println("Overall records:" + cursorOverall.length());

            BasicDBObject queryUnavailable = new BasicDBObject("_id",
                    new BasicDBObject("$gte", from).append("$lte", to))
                            .append("location.parent.id", distinctTemplates.get(i).toString())
                            .append("reachability", "UNREACHABLE");

            DBCursor cursorUnavailable = coll.find(queryUnavailable);
            cursorUnavailable.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);
            System.out.println("Unavailable records:" + cursorUnavailable.length());

            CloudSleuthAvailability = 100
                    * (((double) cursorOverall.length() - (double) cursorUnavailable.length())
                            / cursorOverall.length());
            System.out.println("Cloudsleuth based availability:" + CloudSleuthAvailability);
            CloudSleuthDowntime = 100.0 - CloudSleuthAvailability;
            response.DC.add(distinctTemplates.get(i).toString());
            response.availability.add((Double) CloudSleuthDowntime);
        }
        return response;

    } catch (UnknownHostException e) {
        e.printStackTrace();
        return null;
    } catch (NoSuchElementException e) {
        System.out.println("No available data for this period...");
        return null;
    } catch (MongoException e) {
        System.out.println("No available data for this period...");
        return null;
    }
}

From source file:ezbake.data.mongo.EzMongoHandler.java

License:Apache License

String getCollNameOfPurgeId(long purgeId) {
    String collectionName = null;
    Set purgeIds = new HashSet();
    purgeIds.add(purgeId);//from   www  .  ja v a 2s.  c o m

    appLog.info("Get Collection Name of Purge Id {} in Purge Tracker Collection", purgeId);
    DBObject query = new BasicDBObject();
    query.put(RedactHelper.APP_ID_FIELD, appId);
    query.put(RedactHelper.PURGE_ID, new BasicDBObject("$in", purgeIds));
    String trackingPurgeCollName = getCollectionName(PURGE_TRACKING_COLL_NAME);
    DBCursor cursor = db.getCollection(trackingPurgeCollName).find(query);
    if (cursor.length() == 1) {
        appLog.info("Found a Record getting collection name");
        collectionName = (String) cursor.one().get(RedactHelper.PURGE_TRACKING_COLL_FIELD);
    }
    appLog.info("getCollNameOfPurgeId, returning Collection Name {}", collectionName);
    return collectionName;
}