Sfoglia il codice sorgente

finished quick poll

Jonathan Hinds 5 anni fa
parent
commit
b6417ef427

+ 1
- 1
pom.xml Vedi File

@@ -15,7 +15,7 @@
15 15
     </parent>
16 16
     <properties>
17 17
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18
-        <start-class>io.zipcoder.tc_spring_poll_application.QuickPollApplication</start-class>
18
+        <start-class>io.zipcoder.springdemo.QuickPollApplication</start-class>
19 19
         <java.version>1.7</java.version>
20 20
     </properties>
21 21
     <dependencies>

+ 22
- 0
src/main/java/DTO/OptionCount.java Vedi File

@@ -0,0 +1,22 @@
1
+package DTO;
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
+}

+ 38
- 0
src/main/java/DTO/VoteResult.java Vedi File

@@ -0,0 +1,38 @@
1
+package DTO;
2
+
3
+import java.util.Collection;
4
+public class VoteResult {
5
+    private int totalVotes;
6
+    private Collection<OptionCount> results;
7
+
8
+    public int getTotalVotes() {
9
+        return totalVotes;
10
+    }
11
+
12
+    public void setTotalVotes(int totalVotes) {
13
+        this.totalVotes = totalVotes;
14
+    }
15
+
16
+    public Collection<OptionCount> getResults() {
17
+        return results;
18
+    }
19
+
20
+    public void setResults(Collection<OptionCount> results) {
21
+        this.results = results;
22
+    }
23
+
24
+    public OptionCount getOptionCount(OptionCount optionCount){
25
+        if(results.size() > 0) {
26
+            for (OptionCount optionCount1 : results) {
27
+                if (optionCount.getOptionId().equals(optionCount1.getOptionId())) {
28
+                    return optionCount1;
29
+                }
30
+            }
31
+        }
32
+        return null;
33
+    }
34
+
35
+    public void addOptionCount(OptionCount optionCount){
36
+        results.add(optionCount);
37
+    }
38
+}

+ 74
- 0
src/main/java/DTO/error/ErrorDetail.java Vedi File

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

+ 54
- 0
src/main/java/DTO/error/RestExceptionHandler.java Vedi File

@@ -0,0 +1,54 @@
1
+package DTO.error;
2
+
3
+import io.zipcoder.tc_spring_poll_application.Exception.ResourceNotFoundException;
4
+import org.springframework.beans.factory.annotation.Autowired;
5
+import org.springframework.context.MessageSource;
6
+import org.springframework.http.HttpStatus;
7
+import org.springframework.http.ResponseEntity;
8
+import org.springframework.validation.FieldError;
9
+import org.springframework.web.bind.MethodArgumentNotValidException;
10
+import org.springframework.web.bind.annotation.ControllerAdvice;
11
+import org.springframework.web.bind.annotation.ExceptionHandler;
12
+
13
+import javax.servlet.http.HttpServletRequest;
14
+import java.util.ArrayList;
15
+import java.util.Date;
16
+import java.util.List;
17
+
18
+@ControllerAdvice
19
+public class RestExceptionHandler {
20
+
21
+    @Autowired
22
+    MessageSource messageSource;
23
+
24
+    @ExceptionHandler(ResourceNotFoundException.class)
25
+    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request){
26
+        ErrorDetail errorDetail = new ErrorDetail();
27
+        errorDetail.setDetail(rnfe.getCause().toString());
28
+        errorDetail.setTitle(rnfe.getMessage());
29
+        errorDetail.setDeveloperMessage(rnfe.getLocalizedMessage());
30
+        errorDetail.setTimestamp(new Date().getTime());
31
+        return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
32
+    }
33
+
34
+    @ExceptionHandler(MethodArgumentNotValidException.class)
35
+    public ResponseEntity<?> handleValidationError(  MethodArgumentNotValidException manve, HttpServletRequest request) {
36
+        ErrorDetail errorDetail = new ErrorDetail();
37
+
38
+        List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
39
+        for (FieldError fe : fieldErrors) {
40
+
41
+            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
42
+            if (validationErrorList == null) {
43
+                validationErrorList = new ArrayList<>();
44
+                errorDetail.getErrors().put(fe.getField(), validationErrorList);
45
+            }
46
+            ValidationError validationError = new ValidationError();
47
+            validationError.setCode(fe.getCode());
48
+            validationError.setMessage(messageSource.getMessage(fe, null));
49
+            validationErrorList.add(validationError);
50
+        }
51
+        return new ResponseEntity<>(errorDetail, HttpStatus.BAD_REQUEST);
52
+    }
53
+}
54
+

+ 31
- 0
src/main/java/DTO/error/ValidationError.java Vedi File

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

+ 19
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/Exception/ResourceNotFoundException.java Vedi File

@@ -0,0 +1,19 @@
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
+}

+ 62
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java Vedi File

@@ -0,0 +1,62 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import DTO.OptionCount;
4
+import DTO.VoteResult;
5
+import io.zipcoder.tc_spring_poll_application.domain.Option;
6
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
7
+import io.zipcoder.tc_spring_poll_application.repository.VoteRepository;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.http.HttpStatus;
10
+import org.springframework.http.ResponseEntity;
11
+import org.springframework.web.bind.annotation.RequestMapping;
12
+import org.springframework.web.bind.annotation.RequestMethod;
13
+import org.springframework.web.bind.annotation.RequestParam;
14
+import org.springframework.web.bind.annotation.RestController;
15
+
16
+import java.util.ArrayList;
17
+import java.util.HashMap;
18
+import java.util.Map;
19
+
20
+@RestController
21
+public class ComputeResultController {
22
+
23
+    private VoteRepository voteRepository;
24
+
25
+    @Autowired
26
+    public ComputeResultController(VoteRepository voteRepository) {
27
+        this.voteRepository = voteRepository;
28
+    }
29
+
30
+    @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
31
+    public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
32
+        VoteResult voteResult = new VoteResult();
33
+        voteResult.setResults(new ArrayList<OptionCount>());
34
+        Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
35
+
36
+        for(Vote vote : allVotes){
37
+            OptionCount optionCount = new OptionCount();
38
+            optionCount.setCount(1);
39
+            optionCount.setOptionId(vote.getOption().getId());
40
+
41
+            //if the results already contain an optioncount for this option
42
+            if(voteResult.getOptionCount(optionCount) != null){
43
+                //get the existing optionCount and
44
+                OptionCount optionCount1 = voteResult.getOptionCount(optionCount);
45
+                //increase its count by 1
46
+                int amount = optionCount1.getCount();
47
+                amount = amount + 1;
48
+                optionCount1.setCount(amount);
49
+
50
+                int votes = voteResult.getTotalVotes();
51
+                votes = votes + 1;
52
+                voteResult.setTotalVotes(votes);
53
+            //if the results does not already contain an optioncount for this option
54
+            } else {
55
+                voteResult.addOptionCount(optionCount);
56
+                voteResult.setTotalVotes(1);
57
+            }
58
+        }
59
+        //TODO: Implement algorithm to count votes
60
+        return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
61
+    }
62
+}

+ 80
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Vedi File

@@ -0,0 +1,80 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.Exception.ResourceNotFoundException;
4
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
5
+import io.zipcoder.tc_spring_poll_application.repository.PollRepository;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.data.domain.Page;
8
+import org.springframework.data.domain.PageRequest;
9
+import org.springframework.http.HttpHeaders;
10
+import org.springframework.http.HttpStatus;
11
+import org.springframework.http.ResponseEntity;
12
+import org.springframework.web.bind.annotation.*;
13
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
14
+
15
+import javax.validation.Valid;
16
+
17
+@RestController
18
+public class PollController {
19
+
20
+    private PollRepository pollRepository;
21
+
22
+    public void pollExists(Long pollId) throws ResourceNotFoundException{
23
+        if(pollRepository.findOne(pollId) == null){
24
+            throw new ResourceNotFoundException("The poll specified does not exist.");
25
+        }
26
+    }
27
+
28
+    @Autowired
29
+    public PollController(PollRepository pollRepository) {
30
+        this.pollRepository = pollRepository;
31
+    }
32
+
33
+    @GetMapping("/polls")
34
+    public ResponseEntity<Iterable<Poll>> getPolls(){
35
+        Iterable<Poll> allPolls = pollRepository.findAll();
36
+        return new ResponseEntity<>(allPolls, HttpStatus.OK);
37
+    }
38
+
39
+    @GetMapping("/polls/{size}/{pageNum}")
40
+    public ResponseEntity<Page<Poll>> getPollsPaged(@PathVariable int size, @PathVariable int pageNum){
41
+
42
+        PageRequest pageRequest = new PageRequest(pageNum, size);
43
+        Page<Poll> page = pollRepository.findAll(pageRequest);
44
+
45
+        //Iterable<Poll> allPolls = pollRepository.findAll();
46
+        return new ResponseEntity<>(page, HttpStatus.OK);
47
+    }
48
+
49
+    @PostMapping("/polls")
50
+    @Valid
51
+    public ResponseEntity<?> createPoll(@RequestBody Poll poll){
52
+        poll = pollRepository.save(poll);
53
+        HttpHeaders httpHeaders = new HttpHeaders();
54
+        httpHeaders.setLocation(ServletUriComponentsBuilder
55
+                .fromCurrentRequest()
56
+                .path("/{id}")
57
+                .buildAndExpand(poll.getId())
58
+                .toUri());
59
+        return new ResponseEntity<>(null, HttpStatus.CREATED);
60
+    }
61
+
62
+    @GetMapping("/polls/{pollId}")
63
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId){
64
+        Poll p = pollRepository.findOne(pollId);
65
+        return new ResponseEntity<>(p, HttpStatus.OK);
66
+    }
67
+
68
+    @PutMapping("/polls/{pollId}")
69
+    @Valid
70
+    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId){
71
+        Poll p = pollRepository.save(poll);
72
+        return new ResponseEntity<>(HttpStatus.OK);
73
+    }
74
+
75
+    @DeleteMapping("/polls/{pollId}")
76
+    public ResponseEntity<?> deletePoll(@PathVariable Long pollId){
77
+        pollRepository.delete(pollId);
78
+        return new ResponseEntity<>(HttpStatus.OK);
79
+    }
80
+ }

+ 40
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Vedi File

@@ -0,0 +1,40 @@
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.repository.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
+@RestController
13
+public class VoteController {
14
+
15
+    private VoteRepository voteRepository;
16
+
17
+    @Autowired
18
+    public VoteController(VoteRepository voteRepository) {
19
+        this.voteRepository = voteRepository;
20
+    }
21
+
22
+    @PostMapping("/polls/{pollId}/votes")
23
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote vote) {
24
+        vote = voteRepository.save(vote);
25
+        HttpHeaders responseHeaders = new HttpHeaders();
26
+        responseHeaders.setLocation(ServletUriComponentsBuilder.
27
+                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
28
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
29
+    }
30
+
31
+    @GetMapping("/polls/votes")
32
+    public Iterable<Vote> getAllVotes() {
33
+        return voteRepository.findAll();
34
+    }
35
+
36
+    @GetMapping("/polls/{pollId}/votes")
37
+    public Iterable<Vote> getVote(@PathVariable Long pollId){
38
+        return voteRepository.findVotesByPoll(pollId);
39
+    }
40
+}

+ 32
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Option.java Vedi File

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

+ 50
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Vedi File

@@ -0,0 +1,50 @@
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(strategy = GenerationType.AUTO)
14
+    @Column(name = "POLL_ID")
15
+    private Long id;
16
+
17
+    @Column(name = "QUESTION")
18
+    @NotEmpty
19
+    private String question;
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 Long getId() {
28
+        return id;
29
+    }
30
+
31
+    public void setId(Long id) {
32
+        this.id = id;
33
+    }
34
+
35
+    public String getQuestion() {
36
+        return question;
37
+    }
38
+
39
+    public void setQuestion(String question) {
40
+        this.question = question;
41
+    }
42
+
43
+    public Set<Option> getOptions() {
44
+        return options;
45
+    }
46
+
47
+    public void setOptions(Set<Option> options) {
48
+        this.options = options;
49
+    }
50
+}

+ 32
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Vedi File

@@ -0,0 +1,32 @@
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(strategy = GenerationType.AUTO)
10
+    @Column(name = "VOTE_ID")
11
+    private Long id;
12
+
13
+    @ManyToOne
14
+    @JoinColumn(name = "OPTION_ID")
15
+    private Option option;
16
+
17
+    public Long getId() {
18
+        return id;
19
+    }
20
+
21
+    public void setId(Long id) {
22
+        this.id = id;
23
+    }
24
+
25
+    public Option getOption() {
26
+        return option;
27
+    }
28
+
29
+    public void setOption(Option option) {
30
+        this.option = option;
31
+    }
32
+}

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repository/OptionRepository.java Vedi File

@@ -0,0 +1,7 @@
1
+package io.zipcoder.tc_spring_poll_application.repository;
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
+}

+ 8
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repository/PollRepository.java Vedi File

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

+ 12
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repository/VoteRepository.java Vedi File

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

+ 29
- 0
src/main/resources/import.sql Vedi File

@@ -0,0 +1,29 @@
1
+insert into poll (poll_id, question) values (1, 'What is your favorite color?');
2
+insert into option (option_id, option_value, poll_id) values (1, 'Red', 1);
3
+
4
+insert into poll (poll_id, question) values (2, 'What is your favorite color?');
5
+insert into option (option_id, option_value, poll_id) values (2, 'Red', 2);
6
+
7
+insert into poll (poll_id, question) values (3, 'What is your favorite color?');
8
+insert into option (option_id, option_value, poll_id) values (3, 'Red', 3);
9
+
10
+insert into poll (poll_id, question) values (4, 'What is your favorite color?');
11
+insert into option (option_id, option_value, poll_id) values (4, 'Red', 4);
12
+
13
+insert into poll (poll_id, question) values (5, 'What is your favorite color?');
14
+insert into option (option_id, option_value, poll_id) values (5, 'Red', 5);
15
+
16
+insert into poll (poll_id, question) values (6, 'What is your favorite color?');
17
+insert into option (option_id, option_value, poll_id) values (6, 'Red', 6);
18
+
19
+insert into poll (poll_id, question) values (7, 'What is your favorite color?');
20
+insert into option (option_id, option_value, poll_id) values (7, 'Red', 7);
21
+
22
+insert into poll (poll_id, question) values (8, 'What is your favorite color?');
23
+insert into option (option_id, option_value, poll_id) values (8, 'Red', 8);
24
+
25
+insert into poll (poll_id, question) values (9, 'What is your favorite color?');
26
+insert into option (option_id, option_value, poll_id) values (9, 'Red', 9);
27
+
28
+insert into poll (poll_id, question) values (10, 'What is your favorite color?');
29
+insert into option (option_id, option_value, poll_id) values (10, 'Red', 10);

+ 2
- 0
src/main/resources/messages.properties Vedi File

@@ -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}