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:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Converts and saves an annotation to mongoDB
 * @param annotationID/*w  ww  . ja va2s  .  co m*/
 * @param aimXML
 * @param collection
 * @throws Exception
 */
public static void saveAnnotationToMongo(String annotationID, String aimXML, String collection)
        throws Exception {
    try {
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return;
        }
        if (aimXML == null || aimXML.trim().length() == 0)
            return;
        String jsonString = XML.toJSONObject(aimXML).toString(0);
        ;
        if (jsonString == null)
            throw new Exception("Error converting to json");
        DBCollection dbColl = db.getCollection(collection);
        BasicDBObject dbObj = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", 1);
        dbColl.createIndex(dbObj, "uid_idx", true); // Does not create index, if it already exists
        BasicDBObject query = new BasicDBObject();
        query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID);
        DBObject dbObject = (DBObject) JSON.parse(jsonString);
        DBCursor cursor = dbColl.find(query);
        if (cursor.count() > 0) {
            log.info("Updating existing annotation in mongoDB:" + annotationID + " in " + collection);
            dbColl.update(query, dbObject, true, false);
        } else {
            log.info("Creating new annotation in mongoDB:" + annotationID + " in " + collection);
            dbColl.insert(dbObject);
        }
    } catch (Exception e) {
        log.warning("Error saving AIM to mongodb:", e);
        throw e;
    }
}

From source file:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Deletes json annotation from mongoDB//from   ww  w . ja v  a  2  s  .  c om
 * 
 * @param annotationID
 * @param collection
 * @throws Exception
 */
public static void deleteAnotationInMongo(String annotationID, String collection) throws Exception {
    try {
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return;
        }
        DBCollection dbColl = db.getCollection(collection);
        BasicDBObject query = new BasicDBObject();
        query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID);
        DBCursor cursor = dbColl.find(query);
        if (cursor.count() > 0) {
            log.info("Deleting annotation in mongoDB:" + annotationID + " in " + collection);
            DBObject annotation = cursor.next();
            dbColl.remove(annotation);
        } else {
            log.info("Annotation not found in mongoDB:" + annotationID + " in " + collection);
        }
    } catch (Exception e) {
        log.warning("Error deleting AIM from mongodb:", e);
        throw e;
    }
}

From source file:eu.artist.cloud.auditors.AbstractedAvailabilityCalculator.java

License:Open Source License

/**
 * @param args//from  ww w  . j a  v  a 2 s.  co  m
 */

public double calculateAvailability(String databaseIP, int DefinedQuantumofTimeInSeconds) {// (Date thisDate,
    // String userID,){

    double result = 0;

    //is this correct here?if the entire AWS is down, then it will add all 
    //intervals of all VMs--FIX
    long OVERALL_MONTH_INTERVAL_SECONDS = 0;

    //

    // DB interface part
    Mongo mongoClient;
    try {
        mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address:" + databaseIP);
        Set<String> colls = db.getCollectionNames();
        DBCollection coll = db.getCollection("log_samples");

        // get date and time of interest
        // preparation only once, usage in query for each distinct template
        // ID

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter start year");

        int startYear = reader.nextInt();

        System.out.println("Enter start month");

        int startMonth = reader.nextInt() - 1;//needs +1 since month numbering begins from 0

        System.out.println("Enter start day of month");

        int startDay = reader.nextInt();

        System.out.println("Enter stop year");

        int stopYear = reader.nextInt();

        System.out.println("Enter stop month");
        int stopMonth = reader.nextInt() - 1;//needs +1 since month numbering begins from 0

        System.out.println("Enter stop day of month");

        int stopDay = reader.nextInt();
        Date date = new Date();
        Calendar calendarFrom = Calendar.getInstance();
        calendarFrom.setTime(date);
        calendarFrom.set(startYear, startMonth, startDay, 0, 0, 0);

        Date dateFrom = calendarFrom.getTime();

        Calendar calendarTo = Calendar.getInstance();
        calendarTo.setTime(date);
        calendarTo.set(stopYear, stopMonth, 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);
        // we need a query to get the distinct templateIDs logged
        // in the DB
        // then based on this iteration we can get the actual values

        //get distinct template IDs
        List distinctTemplates = coll.distinct("imageId");

        for (int i = 0; i < distinctTemplates.size(); i++) {

            String index = "-1";

            System.out.println("Distinct template IDs:" + distinctTemplates.get(i).toString());

            // query based on date to filter needed month

            BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$gte", from).append("$lte", to))
                    .append("imageId", distinctTemplates.get(i).toString());

            DBCursor cursor = coll.find(query);

            //here the code to extract actual stats for a given template ID

            //abstraction should be achieved also in the status messages
            //inside MongoDB add the field "reachability" should be REACHABLE OR UNREACHABLE
            //the insertion should be performed with an abstracted method at the auditors side

            try {
                long startID = 0;
                long stopID = 0;
                long diffSeconds = 0;
                long PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS = 500;//interval in which we would logically
                //have at least one sample if the daemon is running

                DBObject thisObject = cursor.next();
                System.out.println("First object:" + thisObject.toString());
                DBObject previousObject = thisObject;
                int k = 0;
                while (k < (cursor.count() + 1)) {

                    System.out.println("Times:" + ((ObjectId) thisObject.get("_id")).getTime());
                    //thisObject=cursor.next();
                    System.out.println("Filtered objects:" + thisObject.get("_id"));

                    // index is a flag to indicate if the unreachable sample is the first of a sequence
                    //of unreachable samples
                    //if -1 it is the first sample in the series
                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && index.equals("-1")) { //if it is the first unavailable sample
                        //index= this db index
                        //ObjectId thisBSON= (ObjectId) thisObject.get("_id");

                        System.out.println("Changing index to 1...");
                        startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id
                        System.out.println("StartID is: " + startID);
                        index = "1";
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && (!(index.equals("-1")))) {
                        //necessary for the case that two consecutive unavailable samples are too far apart (defined in variable 
                        //PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) in time, indicative that the image id
                        //was not in the valid list during this time. Thus this interval should not count in the overall unavailable period

                        long gapstopID = ((ObjectId) thisObject.get("_id")).getTime();
                        long gapstartID = ((ObjectId) previousObject.get("_id")).getTime();
                        //System.out.println("StopID is: "+stopID);
                        long GapdiffSeconds = (gapstopID - gapstartID) / 1000; // 60;
                        if (GapdiffSeconds > PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) {
                            System.out.println("Found gap...");

                            stopID = ((ObjectId) previousObject.get("_id")).getTime();//this line's id to end interval
                            System.out.println("StopID is previous: " + stopID);
                            diffSeconds = (stopID - startID) / 1000; // 60;
                            //System.out.println("Unavailable Interval is:"+diffSeconds);
                            if (diffSeconds > DefinedQuantumofTimeInSeconds) {

                                //needs global variable

                                OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                                System.out.println("Overall month interval in seconds now:"
                                        + OVERALL_MONTH_INTERVAL_SECONDS);
                            }

                            //we must not initialize the index to -1 at this point!!!!!!!we must just reset the startID to point to the current
                            //point
                            startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id

                        } else {
                            //standard logic to cover generic case of consecutive unavailable samples

                        }

                    }

                    if (((((thisObject.get("reachability")).equals("REACHABLE")) || (!(cursor.hasNext()))))
                            && (!(index.equals("-1")))) {
                        //calculate interval from index to (this index-1)
                        if (!(cursor.hasNext())) {
                            System.out.println("FINAL ELEMENT REACHED");
                        }
                        //we always get the previous sample, assuming that in the meantime
                        //up to the available sample
                        //it was available
                        stopID = ((ObjectId) previousObject.get("_id")).getTime();
                        /*
                        long gapstopID=((ObjectId)thisObject.get("_id")).getTime();
                        long gapstartID=((ObjectId)previousObject.get("_id")).getTime();
                        //System.out.println("StopID is: "+stopID);
                        long GapdiffSeconds = (gapstopID-gapstartID) / 1000; // 60;
                        if (GapdiffSeconds>PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS){
                           System.out.println("Found gap...");
                                
                           stopID=((ObjectId)previousObject.get("_id")).getTime();//this line's id to end interval
                           System.out.println("StopID is previous: "+stopID);
                        }else
                        {stopID=((ObjectId)previousObject.get("_id")).getTime();//this line's id to end interval
                        System.out.println("StopID is: "+stopID);}
                        */
                        diffSeconds = (stopID - startID) / 1000; // 60;
                        //System.out.println("final segment Unavailable Interval is:"+diffSeconds);
                        //if interval>Quantum add intervall to OVERALL MONTH interval

                        if (diffSeconds > DefinedQuantumofTimeInSeconds) {

                            //needs global variable

                            OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                            System.out.println(
                                    "Overall month interval in seconds now:" + OVERALL_MONTH_INTERVAL_SECONDS);
                        }

                        //set index=-1
                        System.out.println("Resetting index to -1...");
                        index = "-1";
                    }

                    if ((cursor.hasNext())) {
                        previousObject = thisObject;
                        thisObject = cursor.next();
                    }
                    k++;
                } //end of while for resultset analysis

                System.out.println("Final Overall month unavailable interval in seconds now:"
                        + OVERALL_MONTH_INTERVAL_SECONDS);

                //part for measuring percentage of availability based on provider definition
                double OverallUnavailableIntervalInMinutes = OVERALL_MONTH_INTERVAL_SECONDS / 60;
                System.out
                        .println("OverallUnavailableIntervalInMinutes:" + OverallUnavailableIntervalInMinutes);
                double OverallIntervalInSeconds = (dateTo.getTime() - dateFrom.getTime()) / 1000;
                //System.out.println("OVERALLINTERVAL IN SECONDS:"+OverallIntervalInSeconds);
                double OverallIntervalInMinutes = OverallIntervalInSeconds / 60;

                //System.out.println("OVERALLINTERVAL IN Minutes:"+OverallIntervalInMinutes);
                double finalAvailabilityPercentage = 100.0
                        * ((OverallIntervalInMinutes - OverallUnavailableIntervalInMinutes)
                                / OverallIntervalInMinutes);
                System.out.println(
                        "Final percentage of availability based on provider definition in the given interval:"
                                + finalAvailabilityPercentage);
            } catch (Exception e1) {

                e1.printStackTrace();

            } finally {
                cursor.close();
            }

        } //end of for for distinct template IDs
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MongoException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        System.out.println("No available data for this period...");
    }

    return result;

}

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

License:Open Source License

public static MultipleDCResults calculateAvailability(int DefinedQuantumofTimeInSeconds, int startYear,
        int startMonth, int startDay, int stopYear, int stopMonth, int stopDay) {// (Date thisDate,

    double OVERALL_MONTH_INTERVAL_SECONDS = 0;

    ////from  ww w.j  a v  a 2 s.c o m
    try {
        Properties propertiesFile = BenchmarkConstants.getProperties();
        String databaseIP = propertiesFile.getProperty("3alibIP");
        MultipleDCResults response = new MultipleDCResults();
        Mongo mongoClient;

        System.out.println("DB NoSQL:" + databaseIP);
        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");//distinct("imageId");

        for (int i = 0; i < distinctTemplates.size(); i++) {

            String index = "-1";

            System.out.println("Distinct Region IDs:" + distinctTemplates.get(i).toString());

            // query based on date to filter needed month

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

            DBCursor cursor = coll.find(query);
            cursor.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);
            cursor.batchSize(100);

            try {
                long startID = 0;
                long stopID = 0;
                long diffSeconds = 0;
                double PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS = 500;//interval in which we would logically
                //have at least one sample if the daemon is running

                DBObject thisObject = cursor.next();
                System.out.println("First object:" + thisObject.toString());
                int cursorCount = cursor.count();
                System.out.println("Cursor count:" + cursor.count());
                DBObject previousObject = thisObject;
                int k = 0;
                while (k < (cursorCount + 1)) {

                    if ((k % 1000) == 0) {
                        System.out.println("Progress:" + k + " from " + cursorCount + " overall records");
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && index.equals("-1")) { //if it is the first unavailable sample
                        System.out.println("Changing index to 1...");
                        startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id
                        System.out.println("StartID is: " + startID);
                        index = "1";
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && (!(index.equals("-1")))) {
                        long gapstopID = ((ObjectId) thisObject.get("_id")).getTime();
                        long gapstartID = ((ObjectId) previousObject.get("_id")).getTime();
                        long GapdiffSeconds = (gapstopID - gapstartID) / 1000; // 60;
                        if (GapdiffSeconds > PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) {
                            System.out.println("Found gap...");

                            stopID = ((ObjectId) previousObject.get("_id")).getTime();//this line's id to end interval
                            System.out.println("StopID is previous: " + stopID);
                            diffSeconds = (stopID - startID) / 1000;

                            if (diffSeconds > DefinedQuantumofTimeInSeconds) {
                                OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                                System.out.println("Overall month interval in seconds now:"
                                        + OVERALL_MONTH_INTERVAL_SECONDS);
                            }
                            startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id

                        } else {
                            //standard logic to cover generic case of consecutive unavailable samples
                        }

                    }

                    if (((((thisObject.get("reachability")).equals("REACHABLE")) || (!(cursor.hasNext()))))
                            && (!(index.equals("-1")))) {
                        if (!(cursor.hasNext())) {
                            System.out.println("FINAL ELEMENT REACHED");
                        }
                        stopID = ((ObjectId) previousObject.get("_id")).getTime();
                        diffSeconds = (stopID - startID) / 1000; // 60;

                        if (diffSeconds > DefinedQuantumofTimeInSeconds) {
                            OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                            System.out.println(
                                    "Overall month interval in seconds now:" + OVERALL_MONTH_INTERVAL_SECONDS);
                        }
                        System.out.println("Resetting index to -1...");
                        index = "-1";
                    }

                    if ((cursor.hasNext())) {
                        previousObject = thisObject;
                        thisObject = cursor.next();
                    }
                    k++;
                }

                System.out.println("Final Overall month unavailable interval in seconds now:"
                        + OVERALL_MONTH_INTERVAL_SECONDS);
                double OverallUnavailableIntervalInMinutes = OVERALL_MONTH_INTERVAL_SECONDS / 60;
                System.out
                        .println("OverallUnavailableIntervalInMinutes:" + OverallUnavailableIntervalInMinutes);
                double OverallIntervalInSeconds = (dateTo.getTime() - dateFrom.getTime()) / 1000;
                double OverallIntervalInMinutes = OverallIntervalInSeconds / 60;
                double finalAvailabilityPercentage = 100.0
                        * ((OverallIntervalInMinutes - OverallUnavailableIntervalInMinutes)
                                / OverallIntervalInMinutes);
                double downtimeInPercent = 100.0 - finalAvailabilityPercentage;
                response.DC.add(distinctTemplates.get(i).toString());
                response.availability.add((Double) downtimeInPercent);
                System.out.println(
                        "Final percentage of availability based on provider definition in the given interval:"
                                + finalAvailabilityPercentage);
            } catch (NoSuchElementException e2) {

                System.out.println("No available data for this period...");

            } catch (Exception e1) {

                e1.printStackTrace();

            } finally {
                cursor.close();
            }

        }
        return response;

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

From source file:eu.delving.services.core.MetaRepoImpl.java

License:EUPL

@Override
public HarvestStep getFirstHarvestStep(PmhVerb verb, String set, Date from, Date until, String metadataPrefix,
        String accessKey) throws DataSetNotFoundException, MappingNotFoundException, AccessKeyException {
    DataSet dataSet = getDataSet(set);//from  ww w  .j  a  va 2 s  .  co m
    if (dataSet == null) {
        String errorMessage = String.format("Cannot find set [%s]", set);
        log.error(errorMessage);
        throw new DataSetNotFoundException(errorMessage);
    }
    // sort by expiration date and get first One
    DBObject step = mob(HarvestStep.PMH_REQUEST,
            mob(PmhRequest.VERB, verb.toString(), PmhRequest.SET, set, PmhRequest.FROM, from, PmhRequest.UNTIL,
                    until, PmhRequest.PREFIX, metadataPrefix),
            HarvestStep.LIST_SIZE, dataSet.getRecordCount(), HarvestStep.NAMESPACES, dataSet.getNamespaces(),
            HarvestStep.EXPIRATION, null, HarvestStep.CURSOR, 0);
    final DBCursor dbCursor = factory().harvestSteps().find(step).sort(mob(MetaRepo.MONGO_ID, 1)).limit(1);
    if (dbCursor.count() == 1) {
        return factory().createHarvestStep(dbCursor.next(), accessKey);
    } else {
        return factory().createHarvestStep(step, accessKey);
    }
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Returns a view of the objects in the collection that contains the specified range. The objects are sorted by the key in ascending order. 
 * Optionally, the number of objects found in the collection is returned to the caller. Also, the returned fields can be filtered.
 * @param sortCriteria - objects in the collection are sorted with this criteria
 * @param collection - collection where the objects are searched
 * @param start - starting index/*  w  ww  . j  a v  a 2 s.  c  o m*/
 * @param size - maximum number of objects returned
 * @param query - the expression to be used to query the collection
 * @param projection - (optional) Specifies the fields to return using projection operators. To return all fields in the matching document, 
 *                     omit this parameter
 * @param count - (optional) is updated with the number of objects in the database
 * @return a view of the objects in the collection that contains the specified range
 */
public List<BasicDBObject> list(final DBObject sortCriteria, final String collection, final int start,
        final int size, final @Nullable DBObject query, final @Nullable DBObject projection,
        final @Nullable MutableLong count) {
    checkArgument(sortCriteria != null, "Uninitialized sort criteria");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final List<BasicDBObject> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    final DBCursor cursor = dbcol.find(query != null ? query : new BasicDBObject(),
            projection != null ? projection : new BasicDBObject());
    cursor.sort(sortCriteria);
    cursor.skip(start).limit(size);
    try {
        while (cursor.hasNext()) {
            list.add((BasicDBObject) cursor.next());
        }
    } finally {
        cursor.close();
    }
    if (count != null) {
        count.setValue(cursor.count());
    }
    return list;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * db.sandflies.find({ "sandfly.location" : { $exists: true }}, { "sandfly.sequence" : 0 }).count()<br>
 * 6330<br>//w ww  .j av  a2 s  .  com
 */
public int countGeoreferred(final String collection, final String dbPrefix,
        final @Nullable DBObject projection) {
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    checkArgument(isNotBlank(dbPrefix), "Uninitialized or invalid db prefix");
    int count = 0;
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    final DBObject query = new BasicDBObject(dbPrefix + "location", new BasicDBObject("$exists", true));
    final DBCursor cursor = dbcol.find(query, projection != null ? projection : new BasicDBObject());
    try {
        count = cursor.count();
    } finally {
        cursor.close();
    }
    return count;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Lists all the files in the specified name space. Only latest versions are included in the list.
 * @param namespace - (optional) name space to be searched for files. When nothing specified, the default bucket is used
 * @param sortCriteria - objects in the collection are sorted with this criteria
 * @param start - starting index/*w  w  w.j av a 2  s  .  c o m*/
 * @param size - maximum number of objects returned
 * @param count - (optional) is updated with the number of objects in the database
 * @return a view of the files stored under the specified name space that contains the specified range.
 */
public List<GridFSDBFile> listFiles(final @Nullable String namespace, final DBObject sortCriteria,
        final int start, final int size, final @Nullable MutableLong count) {
    final List<GridFSDBFile> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace) ? new GridFS(db, namespace.trim()) : new GridFS(db);
    final DBCursor cursor = gfsNs.getFileList(
            new BasicDBObject(FILE_VERSION_PROP, new BasicDBObject("$exists", true)), sortCriteria);
    cursor.skip(start).limit(size);
    try {
        while (cursor.hasNext()) {
            list.add((GridFSDBFile) cursor.next());
        }
    } finally {
        cursor.close();
    }
    if (count != null) {
        count.setValue(cursor.count());
    }
    return list;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

public List<GridFSDBFile> listFileOpenAccess(final @Nullable String namespace, final DBObject sortCriteria,
        final int start, final int size, final @Nullable MutableLong count) {
    final List<GridFSDBFile> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace) ? new GridFS(db, namespace.trim()) : new GridFS(db);
    final DBCursor cursor = gfsNs
            .getFileList(new BasicDBObject(FILE_VERSION_PROP, new BasicDBObject("$exists", true))
                    .append(FILE_OPEN_ACCESS_LINK_PROP, new BasicDBObject("$exists", true)), sortCriteria);
    cursor.skip(start).limit(size);/*  w  ww  .  j  a v  a  2s .c o m*/
    try {
        while (cursor.hasNext()) {
            list.add((GridFSDBFile) cursor.next());
        }
    } finally {
        cursor.close();
    }
    if (count != null) {
        count.setValue(cursor.count());
    }
    return list;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Lists all the versions of the specified file.
 * @param namespace - (optional) name space to be searched for files. When nothing specified, the default bucket is used
 * @param filename - filename to be searched for in the database
 * @param sortCriteria - objects in the collection are sorted with this criteria
 * @param start - starting index//w w  w .  j  a  va  2 s.  co m
 * @param size - maximum number of objects returned
 * @param count - (optional) is updated with the number of objects in the database
 * @return a view of the versions stored of the specified file that contains the specified range.
 */
public List<GridFSDBFile> listFileVersions(final @Nullable String namespace, final String filename,
        final DBObject sortCriteria, final int start, final int size, final @Nullable MutableLong count) {
    checkArgument(isNotBlank(filename), "Uninitialized or invalid filename");
    final List<GridFSDBFile> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace) ? new GridFS(db, namespace.trim()) : new GridFS(db);
    final DBCursor cursor = gfsNs.getFileList(new BasicDBObject("filename", filename.trim()), sortCriteria);
    cursor.skip(start).limit(size);
    try {
        while (cursor.hasNext()) {
            list.add((GridFSDBFile) cursor.next());
        }
    } finally {
        cursor.close();
    }
    if (count != null) {
        count.setValue(cursor.count());
    }
    return list;
}