Example usage for com.mongodb.client MongoCursor hasNext

List of usage examples for com.mongodb.client MongoCursor hasNext

Introduction

In this page you can find the example usage for com.mongodb.client MongoCursor hasNext.

Prototype

@Override
    boolean hasNext();

Source Link

Usage

From source file:org.restcom.stats.core.service.TimerService.java

License:Open Source License

public List<TimerDTO> retrieveSumMetrics(long fromTime, long toTime, String key) {
    List<TimerDTO> timers = new ArrayList<>();

    //create params list
    List<Bson> params = new ArrayList<>();

    //define match criteria
    params.add(new Document("$match", new Document("timestamp", new Document("$gte", fromTime))));
    params.add(new Document("$match", new Document("timestamp", new Document("$lte", toTime))));
    params.add(new Document("$match", new Document("key", key)));

    //define grouping criteria
    params.add(new Document("$group",
            new Document("_id", "null").append("totalCount", new Document("$sum", "$count"))));

    //exec query/*from w w w  .j a  va 2  s .  c  o  m*/
    MongoCursor<Document> result = dbm.getCollection(MetricType.TIMER.getCollectionName()).aggregate(params)
            .iterator();

    //convert document result into dto
    while (result.hasNext()) {
        Document statsDoc = result.next();
        timers.add(new TimerDTO(toTime, statsDoc.getInteger("totalCount")));
    }

    return timers;
}

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

License:Open Source License

ArrayList<BsonDocument> getCollectionData(final MongoCollection<BsonDocument> coll, final int page,
        final int pagesize, final BsonDocument sortBy, final BsonDocument filters, final BsonDocument keys,
        CursorPool.EAGER_CURSOR_ALLOCATION_POLICY eager) throws JSONParseException {

    ArrayList<BsonDocument> ret = new ArrayList<>();

    int toskip = pagesize * (page - 1);

    SkippedFindIterable _cursor = null;/*from   w ww. java 2 s  . c om*/

    if (eager != CursorPool.EAGER_CURSOR_ALLOCATION_POLICY.NONE) {

        _cursor = CursorPool.getInstance().get(new CursorPoolEntryKey(coll, sortBy, filters, keys, toskip, 0),
                eager);
    }

    int _pagesize = pagesize;

    // in case there is not cursor in the pool to reuse
    FindIterable<BsonDocument> cursor;

    if (_cursor == null) {
        cursor = getFindIterable(coll, sortBy, filters, keys);
        cursor.skip(toskip);

        MongoCursor<BsonDocument> mc = cursor.iterator();

        while (_pagesize > 0 && mc.hasNext()) {
            ret.add(mc.next());
            _pagesize--;
        }
    } else {
        int alreadySkipped;

        cursor = _cursor.getFindIterable();
        alreadySkipped = _cursor.getAlreadySkipped();

        long startSkipping = 0;
        int cursorSkips = alreadySkipped;

        if (LOGGER.isDebugEnabled()) {
            startSkipping = System.currentTimeMillis();
        }

        LOGGER.debug("got cursor from pool with skips {}. " + "need to reach {} skips.", alreadySkipped,
                toskip);

        MongoCursor<BsonDocument> mc = cursor.iterator();

        while (toskip > alreadySkipped && mc.hasNext()) {
            mc.next();
            alreadySkipped++;
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("skipping {} times took {} msecs", toskip - cursorSkips,
                    System.currentTimeMillis() - startSkipping);
        }

        while (_pagesize > 0 && mc.hasNext()) {
            ret.add(mc.next());
            _pagesize--;
        }
    }

    // the pool is populated here because, skipping with cursor.next() is heavy operation
    // and we want to minimize the chances that pool cursors are allocated in parallel
    CursorPool.getInstance().populateCache(new CursorPoolEntryKey(coll, sortBy, filters, keys, toskip, 0),
            eager);

    return ret;
}

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

License:Open Source License

/**
 * Returns true if the collection exists
 *
 * @param dbName the database name of the collection
 * @param collName the collection name//from  w w  w  . j ava 2  s.co  m
 * @return true if the collection exists
 */
public boolean doesCollectionExist(String dbName, String collName) {
    MongoCursor<String> dbCollections = client.getDatabase(dbName).listCollectionNames().iterator();

    while (dbCollections.hasNext()) {
        String dbCollection = dbCollections.next();

        if (collName.equals(dbCollection)) {
            return true;
        }
    }

    return false;
}

From source file:org.sead.monitoring.engine.SeadMon.java

License:Apache License

private static List<LogEvent> queryLog(MongoCollection collection, BasicDBObject query, String countStr,
        int start) {

    int count = 0;
    if (countStr != null && !countStr.equals(Constants.INFINITE))
        count = Integer.parseInt(countStr);
    start = start < 0 ? 0 : start;/*from   www .j  a  v  a  2  s  .com*/

    FindIterable<Document> iter;
    if (countStr == null || (countStr != null && countStr.equals(Constants.INFINITE))) {
        iter = collection.find(query).skip(start).sort(new BasicDBObject("date", 1));
    } else {
        iter = collection.find(query).limit(count).skip(start).sort(new BasicDBObject("date", 1));
    }
    List<LogEvent> logEvents = new ArrayList<LogEvent>();
    MongoCursor<Document> cursor = iter.iterator();
    try {
        while (cursor.hasNext()) {
            Document dbobj = cursor.next();
            //Converting BasicDBObject to a custom Class(LogEvent)
            LogEvent logEvent = (new Gson()).fromJson(dbobj.toJson(), LogEvent.class);
            logEvents.add(logEvent);
        }
    } finally {
        cursor.close();
    }
    return logEvents;
}

From source file:org.sead.monitoring.engine.SeadMon.java

License:Apache License

private static List<DataoneLogEvent> queryDataoneLog(MongoCollection collection, BasicDBObject query,
        String countStr, int start) {

    int count = 0;
    if (countStr != null && !countStr.equals(Constants.INFINITE))
        count = Integer.parseInt(countStr);
    start = start < 0 ? 0 : start;/* w  w  w  .jav a2 s .  c  o m*/

    FindIterable<Document> iter;
    if (countStr == null || (countStr != null && countStr.equals(Constants.INFINITE))) {
        iter = collection.find(query).skip(start).sort(new BasicDBObject("date", 1));
    } else {
        iter = collection.find(query).limit(count).skip(start).sort(new BasicDBObject("date", 1));
    }
    List<DataoneLogEvent> logEvents = new ArrayList<DataoneLogEvent>();
    MongoCursor<Document> cursor = iter.iterator();
    try {
        while (cursor.hasNext()) {
            Document dbobj = cursor.next();
            //Converting BasicDBObject to a custom Class(LogEvent)
            DataoneLogEvent logEvent = (new Gson()).fromJson(dbobj.toJson(), DataoneLogEvent.class);
            logEvents.add(logEvent);
        }
    } finally {
        cursor.close();
    }
    return logEvents;
}

From source file:org.sead.va.dataone.Object.java

License:Apache License

@GET
@Path("/")
@Produces(MediaType.APPLICATION_XML)//from   ww w. ja  va  2  s. c  o m
public String listObjects(@Context HttpServletRequest request, @HeaderParam("user-agent") String userAgent,
        @QueryParam("start") int start, @QueryParam("count") String countStr,
        @QueryParam("formatId") String formatId, @QueryParam("fromDate") String fromDate,
        @QueryParam("toDate") String toDate) throws ParseException, TransformerException, JiBXException {

    int count = MAX_MATCHES;
    boolean countZero = false;
    if (countStr != null) {
        count = Integer.parseInt(countStr);
        if (count <= 0)
            countZero = true;
    }

    ObjectList objectList = new ObjectList();
    int totalMongoCount = Integer.parseInt(countObjects(formatId, fromDate, toDate));
    if (countZero) {
        objectList.setCount(0);
        objectList.setTotal(totalMongoCount);
        objectList.setStart(start);
        return SeadQueryService.marshal(objectList);
    }

    BasicDBObject andQuery = new BasicDBObject();
    List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
    if (formatId != null) {
        String tempFormat = SeadQueryService.d12seadFormat.get(formatId);
        if (tempFormat == null)
            tempFormat = formatId;
        obj.add(new BasicDBObject(Constants.META_INFO + "." + Constants.META_FORMAT, tempFormat));
    }

    if (fromDate != null) {
        fromDate = fromDate.replace("+00:00", "Z");
        obj.add(new BasicDBObject(Constants.META_INFO + "." + Constants.META_UPDATE_DATE,
                new BasicDBObject("$gte", fromDate)));
    }
    if (toDate != null) {
        toDate = toDate.replace("+00:00", "Z");
        obj.add(new BasicDBObject(Constants.META_INFO + "." + Constants.META_UPDATE_DATE,
                new BasicDBObject("$lte", toDate)));
    }

    if (obj.size() != 0) {
        andQuery.put("$and", obj);
    }

    FindIterable<Document> iter = fgdcCollection.find(andQuery).limit(count).skip(start)
            .sort(new Document(Constants.META_INFO + "." + Constants.META_UPDATE_DATE, 1));
    MongoCursor<Document> cursor = iter.iterator();
    int totalResutls = 0;

    while (cursor.hasNext()) {
        JSONObject object = new JSONObject(cursor.next().toJson().toString());
        JSONObject metaInfo = (JSONObject) object.get(Constants.META_INFO);
        String fgdcMetadata = object.get(Constants.METADATA).toString();

        String date = (String) metaInfo.get(Constants.META_UPDATE_DATE);
        ObjectInfo objectInfo = new ObjectInfo();
        Identifier identifier = new Identifier();

        String id = (String) metaInfo.get(Constants.FGDC_ID);
        identifier.setValue(id);//URLEncoder.encode(id));
        objectInfo.setIdentifier(identifier);

        int size = Integer.parseInt(metaInfo.get(Constants.SIZE).toString());
        objectInfo.setSize(BigInteger.valueOf(size < 0 ? 10 : size));

        String lastFormat = "TestFormatId";
        if (SeadQueryService.sead2d1Format.get(metaInfo.get(Constants.META_FORMAT)) != null) {
            ObjectFormatIdentifier formatIdentifier = new ObjectFormatIdentifier();
            formatIdentifier.setValue(SeadQueryService.sead2d1Format.get(metaInfo.get(Constants.META_FORMAT)));
            objectInfo.setFormatId(formatIdentifier);
        }

        if (objectInfo.getFormatId() == null) {
            ObjectFormatIdentifier formatIdentifier = new ObjectFormatIdentifier();
            formatIdentifier.setValue(lastFormat);
            objectInfo.setFormatId(formatIdentifier);
        }

        objectInfo.setDateSysMetadataModified(simpleDateFormat.parse(date));

        Checksum checksum = new Checksum();
        checksum.setAlgorithm("MD5");
        checksum.setValue("testChecksum");

        String fixityFormat = (String) metaInfo.get(Constants.FIXITY_FORMAT);
        String fixityValue = (String) metaInfo.get(Constants.FIXITY_VAL);
        if (fixityFormat.equalsIgnoreCase("MD-5")) {
            checksum.setAlgorithm("MD5");
            checksum.setValue(fixityValue);
        }
        if (fixityFormat.equalsIgnoreCase("SHA-1")) {
            checksum.setAlgorithm("SHA-1");
            checksum.setValue(fixityValue);
        }

        objectInfo.setChecksum(checksum);
        objectList.getObjectInfoList().add(objectInfo);
        totalResutls++;
    }

    objectList.setCount(totalResutls);
    objectList.setTotal(totalMongoCount);
    objectList.setStart(start);
    return SeadQueryService.marshal(objectList);
}

From source file:org.seadpdt.impl.PeopleServicesImpl.java

License:Apache License

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//w ww . j  av  a2s .com
public Response getPeopleList() {
    FindIterable<Document> iter = peopleCollection.find();
    iter.projection(getBasicPersonProjection());

    MongoCursor<Document> cursor = iter.iterator();
    ArrayList<Object> array = new ArrayList<Object>();
    while (cursor.hasNext()) {
        Document next = cursor.next();
        array.add(next);
    }
    Document peopleDocument = new Document();
    peopleDocument.put("persons", array);
    peopleDocument.put("@context", getPersonContext());
    return Response.ok(peopleDocument.toJson()).cacheControl(control).build();
}

From source file:org.seadpdt.impl.PeopleServicesImpl.java

License:Apache License

@GET
@Path("/list/")
@Produces(MediaType.APPLICATION_JSON)//www .ja v a 2s. c om
public Response getPeopleListAsArray() {
    FindIterable<Document> iter = peopleCollection.find();
    iter.projection(getBasicPersonProjection());

    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        Document next = cursor.next();
        next.put("@context", getPersonContext());
        array.put(next);
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}

From source file:org.seadpdt.impl.RepoServicesImpl.java

License:Apache License

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)/*from www .  j  ava  2  s.  c  o  m*/
public Response getRepositoryList() {
    FindIterable<Document> iter = repositoriesCollection.find();
    iter.projection(new Document("orgidentifier", 1).append("repositoryURL", 1).append("repositoryName", 1)
            .append("lastUpdate", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(new JSONObject(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();

}

From source file:org.seadpdt.impl.RepoServicesImpl.java

License:Apache License

@GET
@Path("/{id}/researchobjects")
@Produces(MediaType.APPLICATION_JSON)//from  ww  w.  j a  va2 s. c o  m
public Response getROsByRepository(@PathParam("id") String id, @QueryParam("Purpose") final String purpose) {
    MongoCollection<Document> publicationsCollection = null;
    publicationsCollection = db.getCollection(MongoDB.researchObjects);
    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection.find(
                Filters.and(Filters.eq("Repository", id), Filters.ne("Preferences.Purpose", "Testing-Only")));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection
                .find(Filters.and(Filters.eq("Repository", id), Filters.eq("Preferences.Purpose", purpose)));
    } else if (purpose != null) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find(Filters.eq("Repository", id));
    }

    iter.projection(new Document("Aggregation.Identifier", 1).append("Aggregation.Title", 1)
            .append("Repository", 1).append("Status", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    Set<Document> array = new HashSet<Document>();
    while (cursor.hasNext()) {
        array.add(cursor.next());
    }
    return Response.ok(array).cacheControl(control).build();
}