2
2
3
3
import com .example .polls .exception .BadRequestException ;
4
4
import com .example .polls .exception .ResourceNotFoundException ;
5
- import com .example .polls .model .ChoiceVoteCount ;
6
- import com .example .polls .model .Poll ;
7
- import com .example .polls .model .User ;
8
- import com .example .polls .model .Vote ;
5
+ import com .example .polls .model .*;
9
6
import com .example .polls .payload .PagedResponse ;
7
+ import com .example .polls .payload .PollRequest ;
10
8
import com .example .polls .payload .PollResponse ;
9
+ import com .example .polls .payload .VoteRequest ;
11
10
import com .example .polls .repository .PollRepository ;
12
11
import com .example .polls .repository .UserRepository ;
13
12
import com .example .polls .repository .VoteRepository ;
17
16
import org .slf4j .Logger ;
18
17
import org .slf4j .LoggerFactory ;
19
18
import org .springframework .beans .factory .annotation .Autowired ;
19
+ import org .springframework .dao .DataIntegrityViolationException ;
20
20
import org .springframework .data .domain .Page ;
21
21
import org .springframework .data .domain .PageRequest ;
22
22
import org .springframework .data .domain .Pageable ;
23
23
import org .springframework .data .domain .Sort ;
24
24
import org .springframework .stereotype .Service ;
25
25
26
+ import java .time .Duration ;
27
+ import java .time .Instant ;
26
28
import java .util .Collections ;
27
29
import java .util .List ;
28
30
import java .util .Map ;
@@ -47,7 +49,7 @@ public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int pa
47
49
validatePageNumberAndSize (page , size );
48
50
49
51
// Retrieve Polls
50
- Pageable pageable = new PageRequest (page , size , Sort .Direction .DESC , "createdAt" );
52
+ Pageable pageable = PageRequest . of (page , size , Sort .Direction .DESC , "createdAt" );
51
53
Page <Poll > polls = pollRepository .findAll (pageable );
52
54
53
55
if (polls .getNumberOfElements () == 0 ) {
@@ -79,7 +81,7 @@ public PagedResponse<PollResponse> getPollsCreatedBy(String username, UserPrinci
79
81
.orElseThrow (() -> new ResourceNotFoundException ("User" , "username" , username ));
80
82
81
83
// Retrieve all polls created by the given username
82
- Pageable pageable = new PageRequest (page , size , Sort .Direction .DESC , "createdAt" );
84
+ Pageable pageable = PageRequest . of (page , size , Sort .Direction .DESC , "createdAt" );
83
85
Page <Poll > polls = pollRepository .findByCreatedBy (user .getId (), pageable );
84
86
85
87
if (polls .getNumberOfElements () == 0 ) {
@@ -110,7 +112,7 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
110
112
.orElseThrow (() -> new ResourceNotFoundException ("User" , "username" , username ));
111
113
112
114
// Retrieve all pollIds in which the given username has voted
113
- Pageable pageable = new PageRequest (page , size , Sort .Direction .DESC , "createdAt" );
115
+ Pageable pageable = PageRequest . of (page , size , Sort .Direction .DESC , "createdAt" );
114
116
Page <Long > userVotedPollIds = voteRepository .findVotedPollIdsByUserId (user .getId (), pageable );
115
117
116
118
if (userVotedPollIds .getNumberOfElements () == 0 ) {
@@ -140,6 +142,91 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
140
142
return new PagedResponse <>(pollResponses , userVotedPollIds .getNumber (), userVotedPollIds .getSize (), userVotedPollIds .getTotalElements (), userVotedPollIds .getTotalPages (), userVotedPollIds .isLast ());
141
143
}
142
144
145
+
146
+ public Poll createPoll (PollRequest pollRequest ) {
147
+ Poll poll = new Poll ();
148
+ poll .setQuestion (pollRequest .getQuestion ());
149
+
150
+ pollRequest .getChoices ().forEach (choiceRequest -> {
151
+ poll .addChoice (new Choice (choiceRequest .getText ()));
152
+ });
153
+
154
+ Instant now = Instant .now ();
155
+ Instant expirationDateTime = now .plus (Duration .ofDays (pollRequest .getPollLength ().getDays ()))
156
+ .plus (Duration .ofHours (pollRequest .getPollLength ().getHours ()));
157
+
158
+ poll .setExpirationDateTime (expirationDateTime );
159
+
160
+ return pollRepository .save (poll );
161
+ }
162
+
163
+ public PollResponse getPollById (Long pollId , UserPrincipal currentUser ) {
164
+ Poll poll = pollRepository .findById (pollId ).orElseThrow (
165
+ () -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
166
+
167
+ // Retrieve Vote Counts of every choice belonging to the current poll
168
+ List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (pollId );
169
+
170
+ Map <Long , Long > choiceVotesMap = votes .stream ()
171
+ .collect (Collectors .toMap (ChoiceVoteCount ::getChoiceId , ChoiceVoteCount ::getVoteCount ));
172
+
173
+ // Retrieve poll creator details
174
+ User creator = userRepository .findById (poll .getCreatedBy ())
175
+ .orElseThrow (() -> new ResourceNotFoundException ("User" , "id" , poll .getCreatedBy ()));
176
+
177
+ // Retrieve vote done by logged in user
178
+ Vote userVote = null ;
179
+ if (currentUser != null ) {
180
+ userVote = voteRepository .findByUserIdAndPollId (currentUser .getId (), pollId );
181
+ }
182
+
183
+ return ModelMapper .mapPollToPollResponse (poll , choiceVotesMap ,
184
+ creator , userVote != null ? userVote .getChoice ().getId (): null );
185
+ }
186
+
187
+ public PollResponse castVoteAndGetUpdatedPoll (Long pollId , VoteRequest voteRequest , UserPrincipal currentUser ) {
188
+ Poll poll = pollRepository .findById (pollId )
189
+ .orElseThrow (() -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
190
+
191
+ if (poll .getExpirationDateTime ().isBefore (Instant .now ())) {
192
+ throw new BadRequestException ("Sorry! This Poll has already expired" );
193
+ }
194
+
195
+ User user = userRepository .getOne (currentUser .getId ());
196
+
197
+ Choice selectedChoice = poll .getChoices ().stream ()
198
+ .filter (choice -> choice .getId ().equals (voteRequest .getChoiceId ()))
199
+ .findFirst ()
200
+ .orElseThrow (() -> new ResourceNotFoundException ("Choice" , "id" , voteRequest .getChoiceId ()));
201
+
202
+ Vote vote = new Vote ();
203
+ vote .setPoll (poll );
204
+ vote .setUser (user );
205
+ vote .setChoice (selectedChoice );
206
+
207
+ try {
208
+ vote = voteRepository .save (vote );
209
+ } catch (DataIntegrityViolationException ex ) {
210
+ logger .info ("User {} has already voted in Poll {}" , currentUser .getId (), pollId );
211
+ throw new BadRequestException ("Sorry! You have already cast your vote in this poll" );
212
+ }
213
+
214
+ //-- Vote Saved, Return the updated Poll Response now --
215
+
216
+ // Retrieve Vote Counts of every choice belonging to the current poll
217
+ List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (pollId );
218
+
219
+ Map <Long , Long > choiceVotesMap = votes .stream ()
220
+ .collect (Collectors .toMap (ChoiceVoteCount ::getChoiceId , ChoiceVoteCount ::getVoteCount ));
221
+
222
+ // Retrieve poll creator details
223
+ User creator = userRepository .findById (poll .getCreatedBy ())
224
+ .orElseThrow (() -> new ResourceNotFoundException ("User" , "id" , poll .getCreatedBy ()));
225
+
226
+ return ModelMapper .mapPollToPollResponse (poll , choiceVotesMap , creator , vote .getChoice ().getId ());
227
+ }
228
+
229
+
143
230
private void validatePageNumberAndSize (int page , int size ) {
144
231
if (page < 0 ) {
145
232
throw new BadRequestException ("Page number cannot be less than zero." );
0 commit comments