-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathPollService.java
More file actions
275 lines (212 loc) · 12.1 KB
/
PollService.java
File metadata and controls
275 lines (212 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package com.example.polls.service;
import com.example.polls.exception.BadRequestException;
import com.example.polls.exception.ResourceNotFoundException;
import com.example.polls.model.*;
import com.example.polls.payload.PagedResponse;
import com.example.polls.payload.PollRequest;
import com.example.polls.payload.PollResponse;
import com.example.polls.payload.VoteRequest;
import com.example.polls.repository.PollRepository;
import com.example.polls.repository.UserRepository;
import com.example.polls.repository.VoteRepository;
import com.example.polls.security.UserPrincipal;
import com.example.polls.util.AppConstants;
import com.example.polls.util.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class PollService {
@Autowired
private PollRepository pollRepository;
@Autowired
private VoteRepository voteRepository;
@Autowired
private UserRepository userRepository;
private static final Logger logger = LoggerFactory.getLogger(PollService.class);
public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int page, int size) {
validatePageNumberAndSize(page, size);
// Retrieve Polls
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
Page<Poll> polls = pollRepository.findAll(pageable);
if(polls.getNumberOfElements() == 0) {
return new PagedResponse<>(Collections.emptyList(), polls.getNumber(),
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
}
// Map Polls to PollResponses containing vote counts and poll creator details
List<Long> pollIds = polls.map(Poll::getId).getContent();
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(currentUser, pollIds);
Map<Long, User> creatorMap = getPollCreatorMap(polls.getContent());
List<PollResponse> pollResponses = polls.map(poll -> {
return ModelMapper.mapPollToPollResponse(poll,
choiceVoteCountMap,
creatorMap.get(poll.getCreatedBy()),
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
}).getContent();
return new PagedResponse<>(pollResponses, polls.getNumber(),
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
}
public PagedResponse<PollResponse> getPollsCreatedBy(String username, UserPrincipal currentUser, int page, int size) {
validatePageNumberAndSize(page, size);
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new ResourceNotFoundException("User", "username", username));
// Retrieve all polls created by the given username
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
Page<Poll> polls = pollRepository.findByCreatedBy(user.getId(), pageable);
if (polls.getNumberOfElements() == 0) {
return new PagedResponse<>(Collections.emptyList(), polls.getNumber(),
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
}
// Map Polls to PollResponses containing vote counts and poll creator details
List<Long> pollIds = polls.map(Poll::getId).getContent();
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(currentUser, pollIds);
List<PollResponse> pollResponses = polls.map(poll -> {
return ModelMapper.mapPollToPollResponse(poll,
choiceVoteCountMap,
user,
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
}).getContent();
return new PagedResponse<>(pollResponses, polls.getNumber(),
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
}
public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipal currentUser, int page, int size) {
validatePageNumberAndSize(page, size);
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new ResourceNotFoundException("User", "username", username));
// Retrieve all pollIds in which the given username has voted
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
Page<Long> userVotedPollIds = voteRepository.findVotedPollIdsByUserId(user.getId(), pageable);
if (userVotedPollIds.getNumberOfElements() == 0) {
return new PagedResponse<>(Collections.emptyList(), userVotedPollIds.getNumber(),
userVotedPollIds.getSize(), userVotedPollIds.getTotalElements(),
userVotedPollIds.getTotalPages(), userVotedPollIds.isLast());
}
// Retrieve all poll details from the voted pollIds.
List<Long> pollIds = userVotedPollIds.getContent();
Sort sort = Sort.by(Sort.Direction.DESC, "createdAt");
List<Poll> polls = pollRepository.findByIdIn(pollIds, sort);
// Map Polls to PollResponses containing vote counts and poll creator details
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(currentUser, pollIds);
Map<Long, User> creatorMap = getPollCreatorMap(polls);
List<PollResponse> pollResponses = polls.stream().map(poll -> {
return ModelMapper.mapPollToPollResponse(poll,
choiceVoteCountMap,
creatorMap.get(poll.getCreatedBy()),
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
}).collect(Collectors.toList());
return new PagedResponse<>(pollResponses, userVotedPollIds.getNumber(), userVotedPollIds.getSize(), userVotedPollIds.getTotalElements(), userVotedPollIds.getTotalPages(), userVotedPollIds.isLast());
}
public Poll createPoll(PollRequest pollRequest) {
Poll poll = new Poll();
poll.setQuestion(pollRequest.getQuestion());
pollRequest.getChoices().forEach(choiceRequest -> {
poll.addChoice(new Choice(choiceRequest.getText()));
});
Instant now = Instant.now();
Instant expirationDateTime = now.plus(Duration.ofDays(pollRequest.getPollLength().getDays()))
.plus(Duration.ofHours(pollRequest.getPollLength().getHours()));
poll.setExpirationDateTime(expirationDateTime);
return pollRepository.save(poll);
}
public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
Poll poll = pollRepository.findById(pollId).orElseThrow(
() -> new ResourceNotFoundException("Poll", "id", pollId));
// Retrieve Vote Counts of every choice belonging to the current poll
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(pollId);
Map<Long, Long> choiceVotesMap = votes.stream()
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
// Retrieve poll creator details
User creator = userRepository.findById(poll.getCreatedBy())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", poll.getCreatedBy()));
// Retrieve vote done by logged in user
Vote userVote = null;
if(currentUser != null) {
userVote = voteRepository.findByUserIdAndPollId(currentUser.getId(), pollId);
}
return ModelMapper.mapPollToPollResponse(poll, choiceVotesMap,
creator, userVote != null ? userVote.getChoice().getId(): null);
}
public PollResponse castVoteAndGetUpdatedPoll(Long pollId, VoteRequest voteRequest, UserPrincipal currentUser) {
Poll poll = pollRepository.findById(pollId)
.orElseThrow(() -> new ResourceNotFoundException("Poll", "id", pollId));
if(poll.getExpirationDateTime().isBefore(Instant.now())) {
throw new BadRequestException("Sorry! This Poll has already expired");
}
User user = userRepository.getById(currentUser.getId());
Choice selectedChoice = poll.getChoices().stream()
.filter(choice -> choice.getId().equals(voteRequest.getChoiceId()))
.findFirst()
.orElseThrow(() -> new ResourceNotFoundException("Choice", "id", voteRequest.getChoiceId()));
Vote vote = new Vote();
vote.setPoll(poll);
vote.setUser(user);
vote.setChoice(selectedChoice);
try {
vote = voteRepository.save(vote);
} catch (DataIntegrityViolationException ex) {
logger.info("User {} has already voted in Poll {}", currentUser.getId(), pollId);
throw new BadRequestException("Sorry! You have already cast your vote in this poll");
}
//-- Vote Saved, Return the updated Poll Response now --
// Retrieve Vote Counts of every choice belonging to the current poll
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(pollId);
Map<Long, Long> choiceVotesMap = votes.stream()
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
// Retrieve poll creator details
User creator = userRepository.findById(poll.getCreatedBy())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", poll.getCreatedBy()));
return ModelMapper.mapPollToPollResponse(poll, choiceVotesMap, creator, vote.getChoice().getId());
}
private void validatePageNumberAndSize(int page, int size) {
if(page < 0) {
throw new BadRequestException("Page number cannot be less than zero.");
}
if(size > AppConstants.MAX_PAGE_SIZE) {
throw new BadRequestException("Page size must not be greater than " + AppConstants.MAX_PAGE_SIZE);
}
}
private Map<Long, Long> getChoiceVoteCountMap(List<Long> pollIds) {
// Retrieve Vote Counts of every Choice belonging to the given pollIds
List<ChoiceVoteCount> votes = voteRepository.countByPollIdInGroupByChoiceId(pollIds);
Map<Long, Long> choiceVotesMap = votes.stream()
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
return choiceVotesMap;
}
private Map<Long, Long> getPollUserVoteMap(UserPrincipal currentUser, List<Long> pollIds) {
// Retrieve Votes done by the logged in user to the given pollIds
Map<Long, Long> pollUserVoteMap = null;
if(currentUser != null) {
List<Vote> userVotes = voteRepository.findByUserIdAndPollIdIn(currentUser.getId(), pollIds);
pollUserVoteMap = userVotes.stream()
.collect(Collectors.toMap(vote -> vote.getPoll().getId(), vote -> vote.getChoice().getId()));
}
return pollUserVoteMap;
}
Map<Long, User> getPollCreatorMap(List<Poll> polls) {
// Get Poll Creator details of the given list of polls
List<Long> creatorIds = polls.stream()
.map(Poll::getCreatedBy)
.distinct()
.collect(Collectors.toList());
List<User> creators = userRepository.findByIdIn(creatorIds);
Map<Long, User> creatorMap = creators.stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
return creatorMap;
}
}