org.piotr.apollo.service.AnswerService.java Source code

Java tutorial

Introduction

Here is the source code for org.piotr.apollo.service.AnswerService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.piotr.apollo.service;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.piotr.apollo.database.mongoDB;
import org.piotr.apollo.model.Answer;
import org.piotr.apollo.model.Lesson;
import org.piotr.apollo.model.Question;
import org.piotr.apollo.model.Section;

/**
 *
 * @author Leniwiec
 */
public class AnswerService {

    private final String answerCollection = "answerCollection";
    mongoDB db = new mongoDB();

    public void addAnswer(Answer answer, ObjectId questionId) {
        MongoCollection collection = db.getCollection(answerCollection);

        Document objInsert = new Document();

        objInsert.put("answer", answer.getAnswer());
        objInsert.put("correct", answer.getCorrect());
        objInsert.put("question_id", questionId);

        collection.insertOne(objInsert);
    }

    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);
        }

        return answersList;
    }
}