hu.bme.iit.quiz.service.QuizServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for hu.bme.iit.quiz.service.QuizServiceImpl.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 hu.bme.iit.quiz.service;

import hu.bme.iit.quiz.dao.QuizDAO;
import hu.bme.iit.quiz.dao.QuizPresentationDAO;
import hu.bme.iit.quiz.dao.UserDAO;
import hu.bme.iit.quiz.model.Quiz;
import hu.bme.iit.quiz.model.QuizPresentation;
import hu.bme.iit.quiz.model.User;
import hu.bme.iit.quiz.xml.ObjectFactory;
import hu.bme.iit.quiz.xml.QuizData;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author ttoth
 */
@Service("quizService")
@Transactional
public class QuizServiceImpl implements QuizService {

    private static final Logger logger = Logger.getLogger(QuizServiceImpl.class);

    @Autowired
    private QuizDAO quizDAO;

    @Autowired
    private QuizPresentationDAO quizPresentationDAO;

    @Autowired
    private UserDAO userDAO;

    public List<Quiz> listQuiz() {
        return quizDAO.listQuiz();
    }

    @Override
    public List<Quiz> listUserQuizzes(String loginName) {
        User user = userDAO.getUser(loginName);
        return new ArrayList(user.getUserQuizzes());
    }

    @Override
    public String validateAndCreateQuizForUserFromFile(MultipartFile file, String quizName, String loginName) {
        String originalFileName = file.getOriginalFilename();
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                //Only XML files, no mime check, basic check
                if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                    return "You failed to upload " + originalFileName + " because it's not an XML file.";
                }

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd-HH-mm-ss");
                Date now = new Date();
                String innerFileLocation = dateFormat.format(now) + "_" + originalFileName;

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath() + File.separator + innerFileLocation);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                //Persist it in db
                Quiz quiz = new Quiz();
                quiz.setName(quizName);
                quiz.setBlobdata(bytes);
                quiz.setLocation(innerFileLocation);
                quiz.setUploaded(new Date());
                quiz.setInnerkey(UUID.randomUUID().toString());
                quiz.setOwner(userDAO.getUser(loginName));

                if (getQuizDataFromXML(quiz) != null) {
                    quizDAO.addQuiz(quiz);
                } else {
                    return "Invalid XML file!";
                }

                logger.info("XML file uploaded: " + originalFileName);
                return "You successfully uploaded '" + originalFileName + "'";
            } catch (Exception e) {
                logger.error(e);
                e.printStackTrace();
                return "You failed to upload " + originalFileName + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + originalFileName + " because the file was empty.";
        }
    }

    @Override
    public int startQuizByInnerKeyForUser(String innerKey, String loginName) {
        User user = userDAO.getUser(loginName);
        Quiz quiz = quizDAO.getQuizByInnerKey(innerKey);

        if (!isQuizStartableByUser(quiz, user)) {
            throw new IllegalArgumentException("This user has no rights to start this Quiz!");
        }

        //Check if already started, if so, do not start again, if not, create a new instance
        QuizPresentation quizPresentation = quizPresentationDAO.findOngoingQuizPresentationByQuizAndUser(quiz,
                user);
        if (quizPresentation == null) {
            quizPresentation = new QuizPresentation();
            quizPresentation.setOwner(user);
            quizPresentation.setQuiz(quiz);
            quizPresentation.setStarted(new Date());

            quizPresentationDAO.addQuizPresentation(quizPresentation);
        }

        return quizPresentation.getId();
    }

    private boolean isQuizStartableByUser(Quiz quiz, User user) {
        if (quiz.getOwner().getId() != user.getId()) {
            return false;
        } else {
            return true;
        }
    }

    public QuizData getQuizDataFromXML(Quiz quiz) {
        try {
            ObjectFactory objectFactory = new ObjectFactory();
            JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(),
                    ObjectFactory.class.getClassLoader());
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream inputStream = new ByteArrayInputStream(quiz.getBlobdata());
            QuizData quizData = (QuizData) unmarshaller.unmarshal(inputStream);

            return quizData;
        } catch (JAXBException ex) {
            logger.error(ex);
        }
        return null;
    }

    @Override
    public QuizData getFullQuizData(int quizPresentationID) {
        QuizPresentation quizPresentation = quizPresentationDAO.getQuizPresentation(quizPresentationID);
        return getQuizDataFromXML(quizPresentation.getQuiz());
    }

    @Override
    public QuizPresentation getQuizPresentation(int quizPresentationID) {
        return quizPresentationDAO.getQuizPresentation(quizPresentationID);
    }

    @Override
    public boolean hasRightToSeeFullQuizPresentationData(int quizPresentationID, String loginName) {
        User user = userDAO.getUser(loginName);
        QuizPresentation quizPresentation = quizPresentationDAO.getQuizPresentation(quizPresentationID);
        if (isQuizStartableByUser(quizPresentation.getQuiz(), user)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void stopQuizByInnerKeyForUser(String innerkey, String username) {
        User user = userDAO.getUser(username);
        Quiz quiz = quizDAO.getQuizByInnerKey(innerkey);

        if (!isQuizStartableByUser(quiz, user)) {
            throw new IllegalArgumentException("This user has no rights to start this Quiz!");
        }

        //Check if already started, if so, do stop it
        QuizPresentation quizPresentation = quizPresentationDAO.findOngoingQuizPresentationByQuizAndUser(quiz,
                user);
        if (quizPresentation != null) {
            quizPresentation.setEnded(new Date());
            quizPresentationDAO.updateQuizPresentation(quizPresentation);
        }
    }

}