use of com.faforever.api.data.domain.Vote in project faf-java-api by FAForever.
the class VotingService method saveVote.
@Transactional
public void saveVote(Vote vote, Player player) {
vote.setPlayer(player);
Assert.notNull(vote.getVotingSubject(), "You must specify a subject");
List<Error> errors = ableToVote(player, vote.getVotingSubject().getId());
if (vote.getVotingAnswers() == null) {
vote.setVotingAnswers(Collections.emptySet());
}
VotingSubject subject = votingSubjectRepository.findById(vote.getVotingSubject().getId()).orElseThrow(() -> new IllegalArgumentException("Subject of vote not found"));
vote.getVotingAnswers().forEach(votingAnswer -> {
VotingChoice votingChoice = votingAnswer.getVotingChoice();
VotingChoice one = votingChoiceRepository.findById(votingChoice.getId()).orElseThrow(() -> new ApiException(new Error(ErrorCode.VOTING_CHOICE_DOES_NOT_EXIST, votingChoice.getId())));
votingAnswer.setVotingChoice(one);
votingAnswer.setVote(vote);
});
subject.getVotingQuestions().forEach(votingQuestion -> {
List<VotingAnswer> votingAnswers = vote.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getVotingChoice().getVotingQuestion().equals(votingQuestion)).collect(Collectors.toList());
long countOfAnswers = votingAnswers.size();
int maxAnswers = votingQuestion.getMaxAnswers();
if (maxAnswers < countOfAnswers) {
errors.add(new Error(ErrorCode.TOO_MANY_ANSWERS, countOfAnswers, maxAnswers));
}
if (votingQuestion.isAlternativeQuestion()) {
for (int i = 0; i < countOfAnswers; i++) {
int finalI = i;
long answersWithOrdinal = votingAnswers.stream().filter(votingAnswer -> Objects.equals(votingAnswer.getAlternativeOrdinal(), finalI)).count();
if (answersWithOrdinal == 1) {
continue;
}
errors.add(new Error(ErrorCode.MALFORMATTED_ALTERNATIVE_ORDINALS));
}
}
});
if (!errors.isEmpty()) {
throw new ApiException(errors.toArray(new Error[0]));
}
voteRepository.save(vote);
}
Aggregations