Joe Hendricks 8 лет назад
Родитель
Сommit
485871bd9c
16 измененных файлов: 544 добавлений и 0 удалений
  1. 71
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java
  2. 44
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java
  3. 38
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/domain/Option.java
  4. 54
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java
  5. 37
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java
  6. 50
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/dtos/ComputeResultController.java
  7. 22
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/dtos/OptionCount.java
  8. 24
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/dtos/VoteResult.java
  9. 64
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/error/ErrorDetail.java
  10. 56
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/error/RestExceptionHandler.java
  11. 29
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/error/ValidationError.java
  12. 21
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java
  13. 7
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java
  14. 9
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java
  15. 16
    0
      src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java
  16. 2
    0
      src/main/resources/messages.properties

+ 71
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Просмотреть файл

@@ -0,0 +1,71 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
3
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
4
+import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.http.HttpHeaders;
7
+import org.springframework.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.web.bind.annotation.*;
10
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11
+
12
+import javax.validation.Valid;
13
+import java.net.URI;
14
+
15
+@RestController
16
+public class PollController {
17
+
18
+    private PollRepository pollRepository;
19
+
20
+    @Autowired
21
+    public PollController(PollRepository pollRepository){
22
+        this.pollRepository = pollRepository;
23
+    }
24
+
25
+    @RequestMapping(value="/polls", method= RequestMethod.GET)
26
+    public ResponseEntity<Iterable<Poll>> getAllPolls() {
27
+        Iterable<Poll> allPolls = pollRepository.findAll();
28
+        return new ResponseEntity<>(allPolls, HttpStatus.OK);
29
+    }
30
+
31
+    @RequestMapping(value="/polls", method=RequestMethod.POST)
32
+    public ResponseEntity<?> createPoll(@Valid @RequestBody Poll poll) {
33
+        poll = pollRepository.save(poll);
34
+
35
+        HttpHeaders responseHeaders = new HttpHeaders();
36
+
37
+        URI newPollUri = ServletUriComponentsBuilder
38
+                .fromCurrentRequest()
39
+                .path("/{id}")
40
+                .buildAndExpand(poll.getId())
41
+                .toUri();
42
+        responseHeaders.setLocation(newPollUri);
43
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
44
+    }
45
+
46
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
47
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
48
+        Poll p = pollRepository.findOne(pollId);
49
+        return new ResponseEntity<> (p, HttpStatus.OK);
50
+    }
51
+
52
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
53
+    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
54
+        // Save the entity
55
+        Poll p = pollRepository.save(poll);
56
+        return new ResponseEntity<>(HttpStatus.OK);
57
+    }
58
+
59
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
60
+    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
61
+        pollRepository.delete(pollId);
62
+        return new ResponseEntity<>(HttpStatus.OK);
63
+    }
64
+
65
+    protected void verifyPoll(Long pollId) throws ResourceNotFoundException {
66
+        Poll poll = pollRepository.findOne(pollId);
67
+        if(poll == null) {
68
+            throw new ResourceNotFoundException("Poll with id " + pollId + " not found");
69
+        }
70
+    }
71
+}

+ 44
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Просмотреть файл

@@ -0,0 +1,44 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.http.HttpHeaders;
7
+import org.springframework.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.web.bind.annotation.*;
10
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11
+
12
+import javax.inject.Inject;
13
+
14
+@RestController
15
+public class VoteController {
16
+
17
+    private VoteRepository voteRepository;
18
+
19
+    @Autowired
20
+    public VoteController(VoteRepository voteRepository) {
21
+        this.voteRepository = voteRepository;
22
+    }
23
+
24
+    @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
25
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
26
+            vote) {
27
+        vote = voteRepository.save(vote);
28
+        // Set the headers for the newly created resource
29
+        HttpHeaders responseHeaders = new HttpHeaders();
30
+        responseHeaders.setLocation(ServletUriComponentsBuilder.
31
+                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
32
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
33
+    }
34
+
35
+    @RequestMapping(value="/polls/votes", method=RequestMethod.GET)
36
+    public Iterable<Vote> getAllVotes() {
37
+        return voteRepository.findAll();
38
+    }
39
+
40
+    @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
41
+    public Iterable<Vote> getVote(@PathVariable Long pollId) {
42
+        return voteRepository.findVotesByPoll(pollId);
43
+    }
44
+}

+ 38
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Option.java Просмотреть файл

@@ -0,0 +1,38 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import javax.persistence.Column;
4
+import javax.persistence.Entity;
5
+import javax.persistence.GeneratedValue;
6
+import javax.persistence.Id;
7
+
8
+@Entity
9
+public class Option {
10
+
11
+    @Id
12
+    @GeneratedValue
13
+    @Column(name = "OPTION_ID")
14
+    private Long id;
15
+
16
+    @Column(name = "OPTION_VALUE")
17
+    private String value;
18
+
19
+    public Option(){
20
+
21
+    }
22
+
23
+    public Long getId() {
24
+        return id;
25
+    }
26
+
27
+    public void setId(Long id) {
28
+        this.id = id;
29
+    }
30
+
31
+    public String getValue() {
32
+        return value;
33
+    }
34
+
35
+    public void setValue(String value) {
36
+        this.value = value;
37
+    }
38
+}

+ 54
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Просмотреть файл

@@ -0,0 +1,54 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import org.hibernate.validator.constraints.NotEmpty;
4
+
5
+import javax.persistence.*;
6
+import javax.validation.constraints.Size;
7
+import java.util.Set;
8
+
9
+@Entity
10
+public class Poll {
11
+
12
+    @Id
13
+    @GeneratedValue
14
+    @Column(name = "POLL_ID")
15
+    private Long id;
16
+
17
+    @Column(name = "QUESTION")
18
+    @NotEmpty
19
+    private String quesiton;
20
+
21
+    @OneToMany(cascade = CascadeType.ALL)
22
+    @JoinColumn(name = "POLL_ID")
23
+    @OrderBy
24
+    @Size(min=2, max = 6)
25
+    private Set<Option> options;
26
+
27
+    public Poll(){
28
+
29
+    }
30
+
31
+    public Long getId() {
32
+        return id;
33
+    }
34
+
35
+    public void setId(Long id) {
36
+        this.id = id;
37
+    }
38
+
39
+    public String getQuesiton() {
40
+        return quesiton;
41
+    }
42
+
43
+    public void setQuesiton(String quesiton) {
44
+        this.quesiton = quesiton;
45
+    }
46
+
47
+    public Set<Option> getOptions() {
48
+        return options;
49
+    }
50
+
51
+    public void setOptions(Set<Option> options) {
52
+        this.options = options;
53
+    }
54
+}

+ 37
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Просмотреть файл

@@ -0,0 +1,37 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import javax.persistence.*;
4
+
5
+@Entity
6
+public class Vote {
7
+
8
+    @Id
9
+    @GeneratedValue
10
+    @Column(name = "VOTE_ID")
11
+    private Long id;
12
+
13
+    @ManyToOne
14
+    @JoinColumn(name = "OPTION_ID")
15
+    private Option option;
16
+
17
+    public Vote(){
18
+
19
+    }
20
+
21
+    public Long getId() {
22
+        return id;
23
+    }
24
+
25
+    public void setId(Long id) {
26
+        this.id = id;
27
+    }
28
+
29
+    public Option getOption() {
30
+        return option;
31
+    }
32
+
33
+    public void setOption(Option option) {
34
+        this.option = option;
35
+    }
36
+
37
+}

+ 50
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/ComputeResultController.java Просмотреть файл

@@ -0,0 +1,50 @@
1
+package io.zipcoder.tc_spring_poll_application.dtos;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.http.HttpStatus;
7
+import org.springframework.http.ResponseEntity;
8
+import org.springframework.web.bind.annotation.RequestMapping;
9
+import org.springframework.web.bind.annotation.RequestMethod;
10
+import org.springframework.web.bind.annotation.RequestParam;
11
+import org.springframework.web.bind.annotation.RestController;
12
+
13
+import java.util.HashMap;
14
+import java.util.Map;
15
+
16
+@RestController
17
+public class ComputeResultController {
18
+
19
+    private VoteRepository voteRepository;
20
+
21
+    @Autowired
22
+    public ComputeResultController(VoteRepository voteRepository) {
23
+        this.voteRepository = voteRepository;
24
+
25
+    }
26
+
27
+    @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
28
+    public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
29
+        VoteResult voteResult = new VoteResult();
30
+        Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
31
+
32
+        //TODO: Implement algorithm to count votes
33
+        int totalVotes = 0;
34
+        Map<Long, OptionCount> tempMap = new HashMap<Long, OptionCount>();
35
+        for(Vote v : allVotes) {
36
+            totalVotes ++;
37
+            // Get the OptionCount corresponding to this Option
38
+            OptionCount optionCount = tempMap.get(v.getOption().getId());
39
+            if(optionCount == null) {
40
+                optionCount = new OptionCount();
41
+                optionCount.setOptionId(v.getOption().getId());
42
+                tempMap.put(v.getOption().getId(), optionCount);
43
+            }
44
+            optionCount.setCount(optionCount.getCount()+1);
45
+        }
46
+        voteResult.setTotalVotes(totalVotes);
47
+        voteResult.setResults(tempMap.values());
48
+        return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
49
+    }
50
+}

+ 22
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/OptionCount.java Просмотреть файл

@@ -0,0 +1,22 @@
1
+package io.zipcoder.tc_spring_poll_application.dtos;
2
+
3
+public class OptionCount {
4
+    private Long optionId;
5
+    private int count;
6
+
7
+    public Long getOptionId() {
8
+        return optionId;
9
+    }
10
+
11
+    public void setOptionId(Long optionId) {
12
+        this.optionId = optionId;
13
+    }
14
+
15
+    public int getCount() {
16
+        return count;
17
+    }
18
+
19
+    public void setCount(int count) {
20
+        this.count = count;
21
+    }
22
+}

+ 24
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/VoteResult.java Просмотреть файл

@@ -0,0 +1,24 @@
1
+package io.zipcoder.tc_spring_poll_application.dtos;
2
+
3
+import java.util.Collection;
4
+
5
+public class VoteResult {
6
+    private int totalVotes;
7
+    private Collection<OptionCount> results;
8
+
9
+    public int getTotalVotes() {
10
+        return totalVotes;
11
+    }
12
+
13
+    public void setTotalVotes(int totalVotes) {
14
+        this.totalVotes = totalVotes;
15
+    }
16
+
17
+    public Collection<OptionCount> getResults() {
18
+        return results;
19
+    }
20
+
21
+    public void setResults(Collection<OptionCount> results) {
22
+        this.results = results;
23
+    }
24
+}

+ 64
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/error/ErrorDetail.java Просмотреть файл

@@ -0,0 +1,64 @@
1
+package io.zipcoder.tc_spring_poll_application.error;
2
+
3
+import java.util.HashMap;
4
+import java.util.List;
5
+import java.util.Map;
6
+
7
+public class ErrorDetail {
8
+
9
+    private String title;
10
+    private int status;
11
+    private String detail;
12
+    private long timeStamp;
13
+    private String developerMessage;
14
+    private Map<String, List<ValidationError>> errors = new HashMap<String,
15
+    List<ValidationError>>();
16
+
17
+    public Map<String, List<ValidationError>> getErrors() {
18
+        return errors;
19
+    }
20
+
21
+    public void setErrors(Map<String, List<ValidationError>> errors) {
22
+        this.errors = errors;
23
+    }
24
+
25
+    public String getTitle() {
26
+        return title;
27
+    }
28
+
29
+    public void setTitle(String title) {
30
+        this.title = title;
31
+    }
32
+
33
+    public int getStatus() {
34
+        return status;
35
+    }
36
+
37
+    public void setStatus(int status) {
38
+        this.status = status;
39
+    }
40
+
41
+    public String getDetail() {
42
+        return detail;
43
+    }
44
+
45
+    public void setDetail(String detail) {
46
+        this.detail = detail;
47
+    }
48
+
49
+    public long getTimeStamp() {
50
+        return timeStamp;
51
+    }
52
+
53
+    public void setTimeStamp(long timeStamp) {
54
+        this.timeStamp = timeStamp;
55
+    }
56
+
57
+    public String getDeveloperMessage() {
58
+        return developerMessage;
59
+    }
60
+
61
+    public void setDeveloperMessage(String developerMessage) {
62
+        this.developerMessage = developerMessage;
63
+    }
64
+}

+ 56
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/error/RestExceptionHandler.java Просмотреть файл

@@ -0,0 +1,56 @@
1
+package io.zipcoder.tc_spring_poll_application.error;
2
+
3
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
4
+import org.springframework.http.HttpStatus;
5
+import org.springframework.http.ResponseEntity;
6
+import org.springframework.validation.FieldError;
7
+import org.springframework.web.bind.MethodArgumentNotValidException;
8
+import org.springframework.web.bind.annotation.ControllerAdvice;
9
+import org.springframework.web.bind.annotation.ExceptionHandler;
10
+
11
+import javax.servlet.http.HttpServletRequest;
12
+import java.util.ArrayList;
13
+import java.util.Date;
14
+import java.util.List;
15
+
16
+@ControllerAdvice
17
+public class RestExceptionHandler {
18
+
19
+    @ExceptionHandler(MethodArgumentNotValidException.class)
20
+    public ResponseEntity<?> handleValidationError(MethodArgumentNotValidException
21
+                                                           manve, HttpServletRequest request) {
22
+        ErrorDetail errorDetail = new ErrorDetail();
23
+
24
+        // Populate errorDetail instance
25
+        errorDetail.setTimeStamp(new Date().getTime());
26
+        errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
27
+        String requestPath = (String) request.getAttribute("javax.servlet.error. request_uri");
28
+        if (requestPath == null) {
29
+            requestPath = request.getRequestURI();
30
+        }
31
+
32
+        errorDetail.setTitle("Validation Failed");
33
+        errorDetail.setDetail("Input validation failed");
34
+        errorDetail.setDeveloperMessage(manve.getClass().getName());
35
+        // Create ValidationError instances
36
+
37
+        List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
38
+        for (FieldError fe : fieldErrors) {
39
+
40
+            List<ValidationError> validationErrorList = errorDetail.getErrors().
41
+                    get(fe.getField());
42
+            if (validationErrorList == null) {
43
+                validationErrorList = new ArrayList<ValidationError>();
44
+                errorDetail.getErrors().put(fe.getField(),
45
+                        validationErrorList);
46
+            }
47
+            ValidationError validationError = new ValidationError();
48
+            validationError.setCode(fe.getCode());
49
+            validationError.setMessage(fe.getDefaultMessage());
50
+            validationErrorList.add(validationError);
51
+            }
52
+
53
+        return new ResponseEntity<>(errorDetail, null, HttpStatus.BAD_REQUEST);
54
+    }
55
+
56
+}

+ 29
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/error/ValidationError.java Просмотреть файл

@@ -0,0 +1,29 @@
1
+package io.zipcoder.tc_spring_poll_application.error;
2
+
3
+import java.util.HashMap;
4
+import java.util.List;
5
+import java.util.Map;
6
+
7
+public class ValidationError {
8
+
9
+    private String code;
10
+    private String message;
11
+
12
+
13
+    public String getCode() {
14
+        return code;
15
+    }
16
+
17
+    public void setCode(String code) {
18
+        this.code = code;
19
+    }
20
+
21
+    public String getMessage() {
22
+        return message;
23
+    }
24
+
25
+    public void setMessage(String message) {
26
+        this.message = message;
27
+    }
28
+
29
+}

+ 21
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java Просмотреть файл

@@ -0,0 +1,21 @@
1
+package io.zipcoder.tc_spring_poll_application.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(HttpStatus.NOT_FOUND)
7
+public class ResourceNotFoundException  extends RuntimeException{
8
+
9
+    public ResourceNotFoundException() {
10
+    }
11
+
12
+    public ResourceNotFoundException(String message) {
13
+        super(message);
14
+    }
15
+
16
+    public ResourceNotFoundException(String message, Throwable cause) {
17
+        super(message, cause);
18
+    }
19
+
20
+
21
+}

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java Просмотреть файл

@@ -0,0 +1,7 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Option;
4
+import org.springframework.data.repository.CrudRepository;
5
+
6
+public interface OptionRepository extends CrudRepository<Option, Long> {
7
+}

+ 9
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java Просмотреть файл

@@ -0,0 +1,9 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Option;
4
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
5
+import org.springframework.data.repository.CrudRepository;
6
+
7
+public interface PollRepository extends CrudRepository<Poll, Long
8
+        > {
9
+}

+ 16
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java Просмотреть файл

@@ -0,0 +1,16 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Option;
4
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
5
+import org.springframework.data.jpa.repository.Query;
6
+import org.springframework.data.repository.CrudRepository;
7
+
8
+public interface VoteRepository extends CrudRepository<Vote, Long> {
9
+
10
+    @Query(value = "SELECT v.* " +
11
+            "FROM Option o, Vote v " +
12
+            "WHERE o.POLL_ID = ?1 " +
13
+            "AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
14
+    public Iterable<Vote> findVotesByPoll(Long pollId);
15
+
16
+}

+ 2
- 0
src/main/resources/messages.properties Просмотреть файл

@@ -0,0 +1,2 @@
1
+NotEmpty.poll.question=Question is a required field
2
+Size.poll.options=Options must be greater than {2} and less than {1}