public Vote saveVote(Vote vote) throws Exception { // totalRate = (((answer1 calculated rate)/q1 total rate)+(((answer2 calculated rate)/q2 total // rate)+...)/(sum of all template question's wight) // MultipleChoice answer rate and "total rate" will be evaluated according to selected options // Rating answer rate is "value/maxRate" vote.setTotalRate(calculateVoteTotalRate(vote)); return (Vote) voteDao.save(vote); }
private int calculateVoteTotalRate(Vote vote) { BibliographicPollingTemplate template = (BibliographicPollingTemplate) vote.getPollingTemplate(); template = (BibliographicPollingTemplate) voteDao.getById(AbstractPollingTemplate.class, template.getId()); List<AbstractTemplateQuestion> templateQuestions = template.getQuestionList(); int totalWeight = 0; for (int i = 0; i < templateQuestions.size(); i++) { totalWeight += templateQuestions.get(i).getWeight(); } float totalRate = 0; List<AbstractQuestionAnswer> questionAnswers = vote.getQuestionAnswer(); for (int i = 0; i < questionAnswers.size(); i++) { int questionWeight = 0; int questionTotalRate = 0; int answerTotalRate = 0; AbstractQuestionAnswer questionAnswer = questionAnswers.get(i); questionWeight = questionAnswer.getQuestion().getWeight(); if (questionAnswer instanceof MultipleChoiceQuestionAnswer) { questionTotalRate = calculateOptionsTotalRate( (MultipleChoicePollingQuestion) questionAnswer.getQuestion().getQuestion()); answerTotalRate = 0; List<PollingAnswerOption> optionList = ((MultipleChoiceQuestionAnswer) questionAnswers.get(i)).getOptionList(); for (int j = 0; j < optionList.size(); j++) { PollingAnswerOption pollingAnswerOption = optionList.get(j); answerTotalRate += pollingAnswerOption.getPollingOption().getWeight(); } } else if (questionAnswer instanceof RatingQuestionAnswer) { questionTotalRate = ((RatingTemplateQuestion) ((RatingQuestionAnswer) questionAnswer).getQuestion()) .getMaxValue(); answerTotalRate = ((RatingQuestionAnswer) questionAnswer).getValue(); } totalRate += ((new Integer(answerTotalRate)).floatValue() / (new Integer(questionTotalRate)).floatValue()) * questionWeight; } return Math.round(((totalRate / totalWeight) * 100)); }