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

Java tutorial

Introduction

Here is the source code for org.piotr.apollo.service.FinishedService.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.Finished;
import org.piotr.apollo.model.Lesson;

/**
 *
 * @author Apollo
 */
public class FinishedService {

    mongoDB mongoDb = new mongoDB();
    LessonService lessonService = new LessonService();
    private final String finishedCollection = "finishedCollection";

    public Finished addFinishedTest(Finished finished) {

        MongoCollection collection = mongoDb.getCollection(finishedCollection);

        Document toInsert = new Document();

        toInsert.append("wrong", finished.getWrong());
        toInsert.append("correct", finished.getCorrect());
        toInsert.append("percentage", finished.getPercentage());
        toInsert.append("lesson_id", new ObjectId(finished.getLessonId()));

        lessonService.updateLessonTest(finished);
        collection.insertOne(toInsert);

        return finished;
    }

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

}