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.opencb.commons.datastore.mongodb.MongoDBCollection.java

License:Apache License

private <T> QueryResult<T> privateFind(Bson query, Bson projection, Class<T> clazz,
        ComplexTypeConverter<T, Document> converter, QueryOptions options) {
    long start = startQuery();

    /**/* w  w  w .  ja  v  a2s  . c o  m*/
     * Getting the cursor and setting the batchSize from options. Default value set to 20.
     */
    FindIterable<Document> findIterable = mongoDBNativeQuery.find(query, projection, options);
    MongoCursor<Document> cursor = findIterable.iterator();

    QueryResult<T> queryResult;
    List<T> list = new LinkedList<>();
    if (cursor != null) {
        if (queryResultWriter != null) {
            try {
                queryResultWriter.open();
                while (cursor.hasNext()) {
                    queryResultWriter.write(cursor.next());
                }
                queryResultWriter.close();
            } catch (IOException e) {
                cursor.close();
                queryResult = endQuery(null, start);
                queryResult.setErrorMsg(e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
                return queryResult;
            }
        } else {
            if (converter != null) {
                while (cursor.hasNext()) {
                    list.add(converter.convertToDataModelType(cursor.next()));
                }
            } else {
                if (clazz != null && !clazz.equals(Document.class)) {
                    Document document;
                    while (cursor.hasNext()) {
                        document = cursor.next();
                        try {
                            list.add(objectMapper.readValue(objectWriter.writeValueAsString(document), clazz));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    while (cursor.hasNext()) {
                        list.add((T) cursor.next());
                    }
                }
            }
        }

        if (options != null && options.getInt(QueryOptions.SKIP) <= 0
                && options.getInt(QueryOptions.LIMIT) > 0) {
            int numTotalResults;
            if (options.getBoolean(QueryOptions.SKIP_COUNT)) {
                numTotalResults = -1;
            } else {
                try {
                    //                        numTotalResults = findIterable.maxTime(options.getInt("countTimeout"), TimeUnit.MILLISECONDS).count();
                    numTotalResults = (int) mongoDBNativeQuery.count(query);
                } catch (MongoExecutionTimeoutException e) {
                    numTotalResults = -1;
                }
            }
            queryResult = endQuery(list, numTotalResults, start);
        } else {
            queryResult = endQuery(list, start);
        }
        cursor.close();
    } else {
        queryResult = endQuery(list, start);
    }

    return queryResult;
}

From source file:org.opencb.commons.datastore.mongodb.MongoDBCollection.java

License:Apache License

public <T> QueryResult<T> aggregate(List<? extends Bson> operations,
        ComplexTypeConverter<T, Document> converter, QueryOptions options) {

    long start = startQuery();

    QueryResult<T> queryResult;//ww  w .j  a  v a2 s. com
    AggregateIterable<Document> output = mongoDBNativeQuery.aggregate(operations, options);
    MongoCursor<Document> iterator = output.iterator();
    List<T> list = new LinkedList<>();
    if (queryResultWriter != null) {
        try {
            queryResultWriter.open();
            while (iterator.hasNext()) {
                queryResultWriter.write(iterator.next());
            }
            queryResultWriter.close();
        } catch (IOException e) {
            queryResult = endQuery(list, start);
            queryResult.setErrorMsg(e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
            return queryResult;
        }
    } else {
        if (converter != null) {
            while (iterator.hasNext()) {
                list.add(converter.convertToDataModelType(iterator.next()));
            }
        } else {
            while (iterator.hasNext()) {
                list.add((T) iterator.next());
            }
        }
    }
    queryResult = endQuery(list, start);
    return queryResult;
}

From source file:org.piotr.apollo.service.AnswerService.java

public List<Answer> getAnswers(ObjectId questionId) {
    MongoCollection collection = db.getCollection(answerCollection);

    List<Answer> answersList = new ArrayList<Answer>();

    Document findAnswers = new Document();

    findAnswers.append("question_id", questionId);

    FindIterable iterable = collection.find(findAnswers);

    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document document = cursor.next();

        Answer answer = new Answer();

        answer.setAnswer(document.getString("answer"));
        answer.setCorrect(document.getBoolean("correct"));
        answer.setQuestion_id((ObjectId) (document.get("question_id")));
        answer.setId(document.get("_id").toString());

        answersList.add(answer);/* w  ww  . ja  v a  2s  . c  o  m*/
    }

    return answersList;
}

From source file:org.piotr.apollo.service.FinishedService.java

public List<Finished> getAllFinishedTest(String lesson) {
    List<Finished> finishedList = new ArrayList<>();
    MongoCollection collection = mongoDb.getCollection(finishedCollection);

    Document doc = new Document();
    doc.append("lesson_id", new ObjectId(lesson));

    FindIterable iterable = collection.find(doc);
    MongoCursor<Document> cursor = iterable.iterator();
    while (cursor.hasNext()) {
        Document temp = cursor.next();

        Finished finished = new Finished();

        ObjectId finishedId = (ObjectId) temp.get("_id");
        ObjectId lessonId = (ObjectId) temp.get("lesson_id");

        finished.set_Id(finishedId);//www.  j  av a  2 s  .  c om
        finished.setLesson_id(lessonId);
        finished.setLessonId(lessonId.toString());
        finished.setId(finishedId.toString());
        finished.setCorrect(temp.getInteger("correct"));
        finished.setWrong(temp.getInteger("wrong"));
        finished.setPercentage(temp.getDouble("percentage"));

        finishedList.add(finished);
    }
    return finishedList;
}

From source file:org.piotr.apollo.service.LessonService.java

private List<Lesson> getLessonBySectionId(String sectionId) {

    List<Lesson> lessonList = new ArrayList<>();
    MongoCollection collection = mongoDB.getCollection(lessonCollection);

    Document doc = new Document();

    doc.append("section_Id", new ObjectId(sectionId));

    FindIterable findIterable = collection.find(doc);
    MongoCursor<Document> cursor = findIterable.iterator();

    while (cursor.hasNext()) {
        Document obj = cursor.next();
        Lesson lesson = new Lesson();
        ObjectId id = (ObjectId) obj.get("_id");

        lesson.set_Id(id);//from w w w  . jav  a  2 s.  c o  m
        lesson.setId(id.toString());
        lesson.setCode(obj.getString("code"));
        lesson.setName(obj.getString("name"));
        lesson.setDescription(obj.getString("description"));
        lesson.setTestCounter(obj.getInteger("testCounter"));
        lesson.setPercentageCorrect(obj.getDouble("percentageCorrect"));
        lesson.setGrade(obj.getDouble("grade"));

        lessonList.add(lesson);
    }

    return lessonList;
}

From source file:org.piotr.apollo.service.LessonService.java

public void updateLessonTest(Finished finished) {

    MongoCollection collection = mongoDB.getCollection(lessonCollection);
    Double gradeToUpdate = 0.0;/*from   w  w  w  .  j  av a2  s  . co m*/

    BasicDBObject toUpdate = new BasicDBObject();
    BasicDBObject oldObject = new BasicDBObject();

    oldObject.append("_id", new ObjectId(finished.getLessonId()));

    Document document = new Document();
    document.append("_id", new ObjectId(finished.getLessonId()));

    FindIterable iterable = collection.find(document);
    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document temp = cursor.next();

        Integer testCounter = temp.getInteger("testCounter");
        Double percentageCorrect = temp.getDouble("percentageCorrect");

        toUpdate.append("testCounter", testCounter + 1);

        if (percentageCorrect != 0.0) {
            toUpdate.append("percentageCorrect", (percentageCorrect + finished.getPercentage()) / 2);
            gradeToUpdate = getProperGrade((percentageCorrect + finished.getPercentage()) / 2);
        } else {
            toUpdate.append("percentageCorrect", finished.getPercentage());
            gradeToUpdate = getProperGrade(finished.getPercentage());
        }

        toUpdate.append("grade", gradeToUpdate);

        collection.updateOne(oldObject, new BasicDBObject("$set", toUpdate));

    }
}

From source file:org.piotr.apollo.service.QuestionService.java

public List<Question> getQuestion(ObjectId testId) {
    MongoCollection collection = db.getCollection(questionCollection);
    List<Question> questionList = new ArrayList<Question>();
    Document findQuestions = new Document();

    findQuestions.append("test_id", testId);

    FindIterable iterable = collection.find(findQuestions);
    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document document = cursor.next();

        Question question = new Question();
        question.setTest_id(testId);/*from  w w  w  .  j a  v a  2s .co m*/
        question.setId(document.get("_id").toString());
        question.set_Id((ObjectId) document.get("_id"));
        question.setQuestion(document.getString("question"));
        question.setNumber(document.getInteger("number"));

        List<Answer> answersList = answerService.getAnswers(question.get_Id());
        question.setAnswersList(answersList);
        questionList.add(question);
    }

    return questionList;
}

From source file:org.radarcns.mongo.data.monitor.application.MongoApplicationStatusWrapper.java

License:Apache License

/**
 * Returns an {@code ApplicationStatus} initialised with the extracted value.
 *
 * @param subject is the subjectID//from w w  w  . ja va  2 s  .c om
 * @param source is the sourceID
 * @param client is the mongoDb client instance
 * @return the last seen status update for the given subject and sourceType, otherwise null
 */
public ApplicationStatus valueByProjectSubjectSource(String project, String subject, String source,
        ApplicationStatus app, MongoClient client) {

    MongoCursor<Document> cursor = MongoHelper.findDocumentBySource(
            MongoHelper.getCollection(client, getCollectionName()), project, subject, source, VALUE + ".time",
            ASCENDING, 1);

    if (!cursor.hasNext()) {
        LOGGER.debug("Empty cursor");
        cursor.close();
        return null;
    }

    Document doc = cursor.next();
    cursor.close();

    if (app == null) {
        return getApplication((Document) doc.get(VALUE), new ApplicationStatus());
    }

    return getApplication((Document) doc.get(VALUE), app);

}

From source file:org.radarcns.mongo.data.passive.SourceDataMongoWrapper.java

License:Apache License

/**
 * Builds the required {@link Dataset}. It adds the {@link TimeFrame} to the given {@link
 * Header}./*from   www  .  j a v  a  2s.  c om*/
 *
 * @param field is the mongodb field that has to be extracted
 * @param stat is the statistical functional represented by the extracted field
 * @param header information to provide the context of the data set
 * @param cursor the mongoD cursor
 * @return data dataset for the given input, otherwise empty dataset
 * @see Dataset
 */
private Dataset getDataSet(String field, DescriptiveStatistic stat, DataSetHeader header,
        MongoCursor<Document> cursor) {

    TimeFrame timeFrame = null;

    List<DataItem> list = new ArrayList<>();

    if (!cursor.hasNext()) {
        LOGGER.debug("Empty cursor");
        return new Dataset(header, list);
    }

    while (cursor.hasNext()) {
        Document doc = cursor.next();
        Document key = (Document) doc.get(KEY);

        TimeFrame currentFrame = new TimeFrame(key.getDate(START), key.getDate(END));
        timeFrame = TimeFrame.span(timeFrame, currentFrame);

        list.add(new DataItem(documentToDataFormat((Document) doc.get(VALUE), field, stat, header),
                currentFrame.getStartDateTime()));
    }

    header.effectiveTimeFrame(timeFrame);

    LOGGER.debug("Found {} value(s)", list.size());

    return new Dataset(header, list);
}

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

License:Open Source License

public List<CounterDTO> retrieveMetrics(long fromTime, long toTime, String key) {
    List<CounterDTO> counters = 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", "$timestamp").append("totalCount", new Document("$sum", "$count"))));
    //define order criteria
    params.add(new Document("$sort", new Document("_id", 1)));

    //exec query//from   www.j  a  v a  2s .co  m
    MongoCursor<Document> result = dbm.getCollection(MetricType.COUNTER.getCollectionName()).aggregate(params)
            .iterator();

    //convert document result into dto
    while (result.hasNext()) {
        Document statsDoc = result.next();
        counters.add(new CounterDTO(statsDoc.getLong("_id"), statsDoc.getInteger("totalCount")));
    }

    return counters;
}