Skip to content

Commit cc67355

Browse files
author
Rajeev Kumar Singh
committed
Code Cleanup, DDL-AUTO update
1 parent dcee575 commit cc67355

File tree

4 files changed

+106
-90
lines changed

4 files changed

+106
-90
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.example.polls.controller;
22

3-
import com.example.polls.exception.BadRequestException;
4-
import com.example.polls.exception.ResourceNotFoundException;
53
import com.example.polls.model.*;
64
import com.example.polls.payload.*;
75
import com.example.polls.repository.PollRepository;
@@ -11,21 +9,15 @@
119
import com.example.polls.security.UserPrincipal;
1210
import com.example.polls.service.PollService;
1311
import com.example.polls.util.AppConstants;
14-
import com.example.polls.util.ModelMapper;
1512
import org.slf4j.Logger;
1613
import org.slf4j.LoggerFactory;
1714
import org.springframework.beans.factory.annotation.Autowired;
1815
import org.springframework.http.ResponseEntity;
1916
import org.springframework.security.access.prepost.PreAuthorize;
2017
import org.springframework.web.bind.annotation.*;
2118
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
22-
2319
import javax.validation.Valid;
2420
import java.net.URI;
25-
import java.time.Duration;
26-
import java.time.Instant;
27-
import java.util.*;
28-
import java.util.stream.Collectors;
2921

3022
/**
3123
* Created by rajeevkumarsingh on 20/11/17.
@@ -59,24 +51,11 @@ public PagedResponse<PollResponse> getPolls(@CurrentUser UserPrincipal currentUs
5951
@PostMapping
6052
@PreAuthorize("hasRole('USER')")
6153
public ResponseEntity<?> createPoll(@Valid @RequestBody PollRequest pollRequest) {
62-
Poll poll = new Poll();
63-
poll.setQuestion(pollRequest.getQuestion());
64-
65-
pollRequest.getChoices().forEach(choiceRequest -> {
66-
poll.addChoice(new Choice(choiceRequest.getText()));
67-
});
68-
69-
Instant now = Instant.now();
70-
Instant expirationDateTime = now.plus(Duration.ofDays(pollRequest.getPollLength().getDays()))
71-
.plus(Duration.ofHours(pollRequest.getPollLength().getHours()));
72-
73-
poll.setExpirationDateTime(expirationDateTime);
74-
75-
Poll result = pollRepository.save(poll);
54+
Poll poll = pollService.createPoll(pollRequest);
7655

7756
URI location = ServletUriComponentsBuilder
7857
.fromCurrentRequest().path("/{pollId}")
79-
.buildAndExpand(result.getId()).toUri();
58+
.buildAndExpand(poll.getId()).toUri();
8059

8160
return ResponseEntity.created(location)
8261
.body(new ApiResponse(true, "Poll Created Successfully"));
@@ -86,70 +65,15 @@ public ResponseEntity<?> createPoll(@Valid @RequestBody PollRequest pollRequest)
8665
@GetMapping("/{pollId}")
8766
public PollResponse getPollById(@CurrentUser UserPrincipal currentUser,
8867
@PathVariable Long pollId) {
89-
Poll poll = pollRepository.findById(pollId).orElseThrow(
90-
() -> new ResourceNotFoundException("Poll", "id", pollId));
91-
92-
// Retrieve Vote Counts of every choice belonging to the current poll
93-
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(pollId);
94-
95-
Map<Long, Long> choiceVotesMap = votes.stream()
96-
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
97-
98-
// Retrieve poll creator details
99-
User creator = userRepository.findById(poll.getCreatedBy())
100-
.orElseThrow(() -> new ResourceNotFoundException("User", "id", poll.getCreatedBy()));
101-
102-
// Retrieve vote done by logged in user
103-
Vote userVote = null;
104-
if(currentUser != null) {
105-
userVote = voteRepository.findByUserIdAndPollId(currentUser.getId(), pollId);
106-
}
107-
108-
return ModelMapper.mapPollToPollResponse(poll, choiceVotesMap,
109-
creator, userVote != null ? userVote.getChoice().getId(): null);
68+
return pollService.getPollById(pollId, currentUser);
11069
}
11170

11271
@PostMapping("/{pollId}/votes")
11372
@PreAuthorize("hasRole('USER')")
114-
public PollResponse castVote(@CurrentUser UserPrincipal userPrincipal,
73+
public PollResponse castVote(@CurrentUser UserPrincipal currentUser,
11574
@PathVariable Long pollId,
11675
@Valid @RequestBody VoteRequest voteRequest) {
117-
118-
Poll poll = pollRepository.findById(pollId)
119-
.orElseThrow(() -> new ResourceNotFoundException("Poll", "id", pollId));
120-
121-
if(poll.getExpirationDateTime().isBefore(Instant.now())) {
122-
throw new BadRequestException("Sorry! This Poll has already expired");
123-
}
124-
125-
User user = userRepository.getOne(userPrincipal.getId());
126-
127-
Choice selectedChoice = poll.getChoices().stream()
128-
.filter(choice -> choice.getId().equals(voteRequest.getChoiceId()))
129-
.findFirst()
130-
.orElseThrow(() -> new ResourceNotFoundException("Choice", "id", voteRequest.getChoiceId()));
131-
132-
Vote vote = new Vote();
133-
vote.setPoll(poll);
134-
vote.setUser(user);
135-
vote.setChoice(selectedChoice);
136-
137-
vote = voteRepository.save(vote);
138-
139-
140-
//-- Vote Saved, Return the updated Poll Response now --
141-
142-
// Retrieve Vote Counts of every choice belonging to the current poll
143-
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(pollId);
144-
145-
Map<Long, Long> choiceVotesMap = votes.stream()
146-
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
147-
148-
// Retrieve poll creator details
149-
User creator = userRepository.findById(poll.getCreatedBy())
150-
.orElseThrow(() -> new ResourceNotFoundException("User", "id", poll.getCreatedBy()));
151-
152-
return ModelMapper.mapPollToPollResponse(poll, choiceVotesMap, creator, vote.getChoice().getId());
76+
return pollService.castVoteAndGetUpdatedPoll(pollId, voteRequest, currentUser);
15377
}
15478

15579
}

polling-app-server/src/main/java/com/example/polls/model/Vote.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
import javax.persistence.*;
55

66
@Entity
7-
@Table(name = "votes")
7+
@Table(name = "votes", uniqueConstraints = {
8+
@UniqueConstraint(columnNames = {
9+
"poll_id",
10+
"user_id"
11+
})
12+
})
813
public class Vote extends DateAudit {
914
@Id
1015
@GeneratedValue(strategy = GenerationType.IDENTITY)

polling-app-server/src/main/java/com/example/polls/service/PollService.java

+94-7
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22

33
import com.example.polls.exception.BadRequestException;
44
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.*;
96
import com.example.polls.payload.PagedResponse;
7+
import com.example.polls.payload.PollRequest;
108
import com.example.polls.payload.PollResponse;
9+
import com.example.polls.payload.VoteRequest;
1110
import com.example.polls.repository.PollRepository;
1211
import com.example.polls.repository.UserRepository;
1312
import com.example.polls.repository.VoteRepository;
@@ -17,12 +16,15 @@
1716
import org.slf4j.Logger;
1817
import org.slf4j.LoggerFactory;
1918
import org.springframework.beans.factory.annotation.Autowired;
19+
import org.springframework.dao.DataIntegrityViolationException;
2020
import org.springframework.data.domain.Page;
2121
import org.springframework.data.domain.PageRequest;
2222
import org.springframework.data.domain.Pageable;
2323
import org.springframework.data.domain.Sort;
2424
import org.springframework.stereotype.Service;
2525

26+
import java.time.Duration;
27+
import java.time.Instant;
2628
import java.util.Collections;
2729
import java.util.List;
2830
import java.util.Map;
@@ -47,7 +49,7 @@ public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int pa
4749
validatePageNumberAndSize(page, size);
4850

4951
// Retrieve Polls
50-
Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "createdAt");
52+
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
5153
Page<Poll> polls = pollRepository.findAll(pageable);
5254

5355
if(polls.getNumberOfElements() == 0) {
@@ -79,7 +81,7 @@ public PagedResponse<PollResponse> getPollsCreatedBy(String username, UserPrinci
7981
.orElseThrow(() -> new ResourceNotFoundException("User", "username", username));
8082

8183
// 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");
8385
Page<Poll> polls = pollRepository.findByCreatedBy(user.getId(), pageable);
8486

8587
if (polls.getNumberOfElements() == 0) {
@@ -110,7 +112,7 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
110112
.orElseThrow(() -> new ResourceNotFoundException("User", "username", username));
111113

112114
// 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");
114116
Page<Long> userVotedPollIds = voteRepository.findVotedPollIdsByUserId(user.getId(), pageable);
115117

116118
if (userVotedPollIds.getNumberOfElements() == 0) {
@@ -140,6 +142,91 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
140142
return new PagedResponse<>(pollResponses, userVotedPollIds.getNumber(), userVotedPollIds.getSize(), userVotedPollIds.getTotalElements(), userVotedPollIds.getTotalPages(), userVotedPollIds.isLast());
141143
}
142144

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+
143230
private void validatePageNumberAndSize(int page, int size) {
144231
if(page < 0) {
145232
throw new BadRequestException("Page number cannot be less than zero.");

polling-app-server/src/main/resources/application.properties

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ spring.datasource.password= callicoder
1010
## Hibernate Properties
1111
# The SQL dialect makes Hibernate generate better SQL for the chosen database
1212
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
13-
spring.jpa.hibernate.ddl-auto = validate
13+
spring.jpa.hibernate.ddl-auto = update
1414

1515
## Hibernate Logging
1616
logging.level.org.hibernate.SQL= DEBUG

0 commit comments

Comments
 (0)