Преглед на файлове

Merge f5c61068511b6557d9d0f79d9bbc1d349849249a into f91a622cc731197181dd1b1e4b17c9bcb450ae8a

EricBarnaba преди 8 години
родител
ревизия
92f8dd457e
No account linked to committer's email
променени са 25 файла, в които са добавени 690 реда и са изтрити 16 реда
  1. 9
    9
      README.md
  2. 2
    2
      pom.xml
  3. 1
    1
      src/main/java/quickpoll/QuickPollApplication.java
  4. 44
    0
      src/main/java/quickpoll/dtos/ComputeResultController.java
  5. 22
    0
      src/main/java/quickpoll/dtos/OptionCount.java
  6. 23
    0
      src/main/java/quickpoll/dtos/VoteResult.java
  7. 61
    0
      src/main/java/quickpoll/dtos/error/ErrorDetail.java
  8. 22
    0
      src/main/java/quickpoll/dtos/error/ValidationError.java
  9. 91
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/controller/PollController.java
  10. 35
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/controller/VoteController.java
  11. 44
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Option.java
  12. 50
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Poll.java
  13. 31
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Vote.java
  14. 18
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java
  15. 75
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/exception/RestExceptionHandler.java
  16. 7
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java
  17. 8
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java
  18. 14
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java
  19. 7
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/IOperations.java
  20. 8
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/PollService.java
  21. 22
    0
      src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/PollServiceImp.java
  22. 90
    0
      src/main/resource/import.sql
  23. 2
    0
      src/main/resource/messages.properties
  24. 0
    4
      src/test/java/io/zipcoder/tc_spring_poll_application/QuickPollApplicationTest.java
  25. 4
    0
      src/test/java/quickpoll/io/zipcoder/tc_spring_poll_application/QuickPollApplicationTest.java

+ 9
- 9
README.md Целия файл

@@ -1,12 +1,12 @@
1 1
 # Poll Application
2 2
 * **Purpose**
3
-	* to demonstrate the basic functionality of the [Spring Framework](https://spring.io/)
3
+	* to demonstrate the basic functionality of the [Spring Framework](https://spring.quickpoll.io/)
4 4
 	* to demonstrate API testing via [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)
5 5
 
6 6
 # Part 1 - Domain Implementation
7 7
 
8 8
 * _Domain objects_ are the backbone for an application and contain the [business logic](https://en.wikipedia.org/wiki/Business_logic).
9
-* Create a sub package of `io.zipcoder.tc_spring_poll_application` named `domain`.
9
+* Create a sub package of `quickpoll.io.zipcoder.tc_spring_poll_application` named `domain`.
10 10
 
11 11
 
12 12
 ## Part 1.1 - Create class `Option`
@@ -76,7 +76,7 @@
76 76
 * _Repositories_ or [Data Access Objects (DAO)](https://en.wikipedia.org/wiki/Data_access_object), provide an abstraction for interacting with _datastores_.
77 77
 * Typically DAOs include an interface that provides a set of finder methods such as `findById`, `findAll`, for retrieving data, and methods to persist and delete data.
78 78
 * It is customary to have one `Repository` per `domain` object.
79
-* Create a sub-package of `io.zipcoder.tc_spring_poll_application` named `repositories`.
79
+* Create a sub-package of `quickpoll.io.zipcoder.tc_spring_poll_application` named `repositories`.
80 80
 
81 81
 
82 82
 ## Part 2.1 - Create interface `OptionRepository`
@@ -100,7 +100,7 @@
100 100
 
101 101
 * _Controllers_ provides all of the necessary [endpoints](https://en.wikipedia.org/wiki/Web_API#Endpoints) to access and manipulate respective domain objects.
102 102
 	*  REST resources are identified using URI endpoints.
103
-* Create a sub package of `io.zipcoder.tc_spring_poll_application` named `controller`.
103
+* Create a sub package of `quickpoll.io.zipcoder.tc_spring_poll_application` named `controller`.
104 104
 
105 105
 
106 106
 ## Part 3.1 - Create class `PollController`
@@ -134,7 +134,7 @@ public ResponseEntity<Iterable<Poll>> getAllPolls() {
134 134
 
135 135
 ### Part 3.1.2 - Testing via Postman
136 136
 
137
-* Ensure that the `start-class` tag in your `pom.xml` encapsulates `io.zipcoder.springdemo.QuickPollApplication`
137
+* Ensure that the `start-class` tag in your `pom.xml` encapsulates `quickpoll.io.zipcoder.springdemo.QuickPollApplication`
138 138
 * Open a command line and navigate to the project's root directory and run this command:
139 139
 	* `mvn spring-boot:run`
140 140
 * Launch the [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) app and enter the URI `http://localhost:8080/polls` and hit Send.
@@ -358,7 +358,7 @@ public Iterable<Vote> getVote(@PathVariable Long pollId) {
358 358
 
359 359
 * The final piece remaining for us is the implementation of the ComputeResult resource.
360 360
 * Because we don’t have any domain objects that can directly help generate this resource representation, we implement two Data Transfer Objects or DTOs—OptionCount and VoteResult
361
-* Create a sub package of `java` named `dtos`
361
+* Create a sub package of `java` named `quickpoll.dtos`
362 362
 
363 363
 
364 364
 ## Part 4.1 - Create class `OptionCount`
@@ -461,7 +461,7 @@ public class ComputeResultController {
461 461
 
462 462
 ## Part 5.1 - Create `ResourceNotFoundException`
463 463
 
464
-- Create a `exception` package inside of `io.zipcoder.springdemo.QuickPollApplication`
464
+- Create a `exception` package inside of `quickpoll.io.zipcoder.springdemo.QuickPollApplication`
465 465
 - Create a `ResourceNotFoundException` class that extends `RuntimeException`. We'll use this to signal when a requested resource is not found.
466 466
 - Annotate the `ResourceNotFoundException` class with `@ResponseStatus(HttpStatus.NOT_FOUND)`. This informs Spring that any request mapping that throws a `ResourceNotFoundException` should result in a `404 NOT FOUND` http status.
467 467
 - Implement three constructors
@@ -478,7 +478,7 @@ Create a void method in `PollController` called `verifyPoll` that checks if a sp
478 478
 
479 479
 ## Part 5.3 - Create custom Error Responses
480 480
 
481
-Spring provides some built-in exception handling and error response, but we'll customize it a bit here. Create an `ErrorDetail` class in a new `io.zipcoder.tc_spring_poll_application.dto.error` package to hold relevant information any time an error occurs.
481
+Spring provides some built-in exception handling and error response, but we'll customize it a bit here. Create an `ErrorDetail` class in a new `quickpoll.io.zipcoder.tc_spring_poll_application.dto.error` package to hold relevant information any time an error occurs.
482 482
 
483 483
 Fields (Don't forget to provide getters and setters):
484 484
 
@@ -517,7 +517,7 @@ Now it's time to make sure that all objects persisted to the database actually c
517 517
 
518 518
 ## Part 5.5 - Customizing validation errors
519 519
 
520
-In order to customize validation errors we'll need a class for error information. Create a `ValidationError` class in `io.zipcoder.tc_spring_poll_application.dto.error` with the following fields and appropriate getters and setters:
520
+In order to customize validation errors we'll need a class for error information. Create a `ValidationError` class in `quickpoll.io.zipcoder.tc_spring_poll_application.dto.error` with the following fields and appropriate getters and setters:
521 521
 
522 522
 - `String code`
523 523
 - `String message`

+ 2
- 2
pom.xml Целия файл

@@ -4,7 +4,7 @@
4 4
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 5
     <modelVersion>4.0.0</modelVersion>
6 6
 
7
-    <groupId>io.zipcoder</groupId>
7
+    <groupId>quickpoll.io.zipcoder</groupId>
8 8
     <artifactId>spring-demo</artifactId>
9 9
     <version>1.0-SNAPSHOT</version>
10 10
     <parent>
@@ -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>quickpoll.QuickPollApplication</start-class>
19 19
         <java.version>1.7</java.version>
20 20
     </properties>
21 21
     <dependencies>

src/main/java/io/zipcoder/tc_spring_poll_application/QuickPollApplication.java → src/main/java/quickpoll/QuickPollApplication.java Целия файл

@@ -1,4 +1,4 @@
1
-package io.zipcoder.tc_spring_poll_application;
1
+package quickpoll;
2 2
 
3 3
 import org.springframework.boot.SpringApplication;
4 4
 import org.springframework.boot.autoconfigure.SpringBootApplication;

+ 44
- 0
src/main/java/quickpoll/dtos/ComputeResultController.java Целия файл

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

+ 22
- 0
src/main/java/quickpoll/dtos/OptionCount.java Целия файл

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

+ 23
- 0
src/main/java/quickpoll/dtos/VoteResult.java Целия файл

@@ -0,0 +1,23 @@
1
+package quickpoll.dtos;
2
+import java.util.Collection;
3
+
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
+}

+ 61
- 0
src/main/java/quickpoll/dtos/error/ErrorDetail.java Целия файл

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

+ 22
- 0
src/main/java/quickpoll/dtos/error/ValidationError.java Целия файл

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

+ 91
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/controller/PollController.java Целия файл

@@ -0,0 +1,91 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.data.domain.Page;
5
+import org.springframework.web.util.UriComponentsBuilder;
6
+import quickpoll.io.zipcoder.tc_spring_poll_application.domain.Poll;
7
+import quickpoll.io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
8
+import quickpoll.io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
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
+import quickpoll.io.zipcoder.tc_spring_poll_application.service.PollService;
15
+
16
+import javax.inject.Inject;
17
+import javax.servlet.http.HttpServletResponse;
18
+import javax.validation.Valid;
19
+import javax.xml.ws.Service;
20
+import java.net.URI;
21
+import java.util.List;
22
+
23
+
24
+@RestController
25
+public class PollController {
26
+   @Inject
27
+    private PollRepository pollRepository;
28
+
29
+   @Inject
30
+   private PollService service;
31
+
32
+
33
+
34
+   @RequestMapping(value="/polls", method = RequestMethod.GET)
35
+   public ResponseEntity<Iterable<Poll>> getAllPolls() {
36
+       Iterable<Poll> allPolls = pollRepository.findAll();
37
+       return new ResponseEntity<>(allPolls, HttpStatus.OK);
38
+   }
39
+
40
+
41
+
42
+   @RequestMapping(value = "/polls", method = RequestMethod.POST)
43
+   public ResponseEntity<?> createPoll(@Valid @RequestBody Poll poll) {
44
+       URI newPollUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(poll.getId()).toUri();
45
+       poll = pollRepository.save(poll);
46
+       HttpHeaders header = new HttpHeaders();
47
+       header.setLocation(newPollUri);
48
+       return new ResponseEntity<>(header, HttpStatus.CREATED);
49
+   }
50
+
51
+   @RequestMapping(value = "/polls", params = {"page", "size"}, method = RequestMethod.GET)
52
+   @ResponseBody
53
+   public List<Poll> findPaginated(@RequestParam("page") int page, @RequestParam("size") int size, UriComponentsBuilder uriBuilder, HttpServletResponse response) {
54
+       Page<Poll> resultPage = service.findPaginated(page,size);
55
+       if(page> resultPage.getTotalPages()){
56
+           throw new ResourceNotFoundException();
57
+       }
58
+
59
+
60
+       return resultPage.getContent();
61
+   }
62
+
63
+   @RequestMapping(value="/polls/{pollId}", method = RequestMethod.GET)
64
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
65
+       verifyPoll(pollId);
66
+       Poll p = pollRepository.findOne(pollId);
67
+       return new ResponseEntity<>(p, HttpStatus.OK);
68
+   }
69
+
70
+
71
+   @RequestMapping(value="/polls/{pollId}", method = RequestMethod.PUT)
72
+   public ResponseEntity<?> updatePoll(@Valid @RequestBody Poll poll, @PathVariable Long pollId){
73
+       verifyPoll(pollId);
74
+       Poll p = pollRepository.save(poll);
75
+       return new ResponseEntity<>(HttpStatus.OK);
76
+   }
77
+
78
+   @RequestMapping(value="/polls/{pollId}", method = RequestMethod.DELETE)
79
+   public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
80
+       verifyPoll(pollId);
81
+       pollRepository.delete(pollId);
82
+       return new ResponseEntity<>(HttpStatus.OK);
83
+   }
84
+
85
+   public void verifyPoll(Long pollId){
86
+       if(pollRepository.findOne(pollId) == null){
87
+           throw new ResourceNotFoundException("Poll Not Found");
88
+       }
89
+   }
90
+
91
+}

+ 35
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Целия файл

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

+ 44
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Option.java Целия файл

@@ -0,0 +1,44 @@
1
+package quickpoll.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
+    @Id
11
+    @GeneratedValue
12
+    @Column(name = "OPTION_ID")
13
+    private Long id;
14
+
15
+    @Column(name = "OPTION_VALUE")
16
+    private String value;
17
+
18
+    @Column(name = "POLL_ID")
19
+    private Long pollId;
20
+
21
+    public Long getId() {
22
+        return id;
23
+    }
24
+
25
+    public void setId(Long id) {
26
+        this.id = id;
27
+    }
28
+
29
+    public String getValue() {
30
+        return value;
31
+    }
32
+
33
+    public void setValue(String value) {
34
+        this.value = value;
35
+    }
36
+
37
+    public Long getPollId() {
38
+        return pollId;
39
+    }
40
+
41
+    public void setPollId(Long pollId) {
42
+        this.pollId = pollId;
43
+    }
44
+}

+ 50
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Poll.java Целия файл

@@ -0,0 +1,50 @@
1
+package quickpoll.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.NotNull;
7
+import javax.validation.constraints.Size;
8
+import java.util.Set;
9
+
10
+@Entity
11
+public class Poll {
12
+    @Id
13
+    @GeneratedValue
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
+}

+ 31
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Vote.java Целия файл

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

+ 18
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java Целия файл

@@ -0,0 +1,18 @@
1
+package quickpoll.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
+    public ResourceNotFoundException(String message){
12
+        super(message);
13
+    }
14
+
15
+    public ResourceNotFoundException(String message, Throwable cause){
16
+        super(message,cause);
17
+    }
18
+}

+ 75
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/exception/RestExceptionHandler.java Целия файл

@@ -0,0 +1,75 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.exception;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.context.MessageSource;
5
+import org.springframework.http.HttpStatus;
6
+import org.springframework.http.ResponseEntity;
7
+import org.springframework.validation.FieldError;
8
+import org.springframework.web.bind.MethodArgumentNotValidException;
9
+import org.springframework.web.bind.annotation.ControllerAdvice;
10
+import org.springframework.web.bind.annotation.ExceptionHandler;
11
+import org.springframework.web.bind.annotation.ResponseBody;
12
+import org.springframework.web.bind.annotation.ResponseStatus;
13
+import quickpoll.dtos.error.ErrorDetail;
14
+import quickpoll.dtos.error.ValidationError;
15
+
16
+
17
+import javax.inject.Inject;
18
+import javax.servlet.http.HttpServletRequest;
19
+import java.util.ArrayList;
20
+import java.util.Date;
21
+import java.util.List;
22
+
23
+@ControllerAdvice
24
+public class RestExceptionHandler {
25
+
26
+    @Autowired
27
+    private MessageSource messageSource;
28
+
29
+    @ExceptionHandler(ResourceNotFoundException.class)
30
+    @ResponseStatus(HttpStatus.NOT_FOUND)
31
+    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
32
+        ErrorDetail errorDetail = new ErrorDetail();
33
+        errorDetail.setTitle("Resource Not Found");
34
+        errorDetail.setStatus(404);
35
+        errorDetail.setDetail(rnfe.getMessage());
36
+        errorDetail.setTimeStamp(new Date().getTime());
37
+        errorDetail.setDeveloperMessage(rnfe.getStackTrace().toString());
38
+
39
+        return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
40
+    }
41
+
42
+    @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST)
43
+    public @ResponseBody
44
+    ErrorDetail handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
45
+        ErrorDetail errorDetail = new ErrorDetail();
46
+
47
+        errorDetail.setTimeStamp(new Date().getTime());
48
+        errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
49
+        String requestPath = (String) request.getAttribute("javax.servlet.error.request_uri");
50
+        if(requestPath == null) {
51
+            requestPath = request.getRequestURI();
52
+        }
53
+        errorDetail.setTitle("Validation Failed");
54
+        errorDetail.setDetail("Input validation failed");
55
+        errorDetail.setDeveloperMessage(manve.getClass().getName());
56
+
57
+        List<FieldError> fieldErrors =  manve.getBindingResult().getFieldErrors();
58
+        //System.out.println(fieldErrors);
59
+        for(FieldError fe : fieldErrors) {
60
+            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
61
+            if(validationErrorList == null) {
62
+                validationErrorList = new ArrayList<ValidationError>();
63
+                errorDetail.getErrors().put(fe.getField(), validationErrorList);
64
+            }
65
+
66
+            ValidationError validationError = new ValidationError();
67
+            validationError.setCode(fe.getCode());
68
+            validationError.setMessage(messageSource.getMessage(fe, null));
69
+            validationErrorList.add(validationError);
70
+        }
71
+        return errorDetail;
72
+    }
73
+
74
+
75
+}

+ 7
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java Целия файл

@@ -0,0 +1,7 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import quickpoll.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/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java Целия файл

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

+ 14
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java Целия файл

@@ -0,0 +1,14 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import quickpoll.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
+    @Query(value = "SELECT v.* " +
9
+    "FROM Option o, Vote v " +
10
+    "WHERE o.POLL_ID = ?1 " +
11
+    "AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
12
+    public Iterable<Vote> findVotesByPoll(Long pollId);
13
+
14
+}

+ 7
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/IOperations.java Целия файл

@@ -0,0 +1,7 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.service;
2
+
3
+import org.springframework.data.domain.Page;
4
+
5
+public interface IOperations<T> {
6
+    public Page<T> findPaginated(final int page, final int size);
7
+}

+ 8
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/PollService.java Целия файл

@@ -0,0 +1,8 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.service;
2
+
3
+import org.springframework.context.annotation.Bean;
4
+import quickpoll.io.zipcoder.tc_spring_poll_application.domain.Poll;
5
+
6
+
7
+public interface PollService extends IOperations<Poll> {
8
+}

+ 22
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/service/PollServiceImp.java Целия файл

@@ -0,0 +1,22 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application.service;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.data.domain.Page;
5
+import org.springframework.data.domain.PageRequest;
6
+import org.springframework.stereotype.Service;
7
+import quickpoll.io.zipcoder.tc_spring_poll_application.domain.Poll;
8
+import quickpoll.io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
9
+
10
+@Service
11
+public class PollServiceImp implements PollService {
12
+
13
+    @Autowired
14
+    private PollRepository dao;
15
+
16
+    @Override
17
+    public Page<Poll> findPaginated(int page, int size) {
18
+        return dao.findAll(new PageRequest(page,size));
19
+
20
+    }
21
+
22
+}

+ 90
- 0
src/main/resource/import.sql Целия файл

@@ -0,0 +1,90 @@
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, 'Green', 1);
3
+insert into option (option_id, option_value, poll_id) values (2, 'Red', 1);
4
+insert into option (option_id, option_value, poll_id) values (3, 'Blue', 1);
5
+
6
+insert into poll (poll_id, question) values (2, 'What is your favorite animal?');
7
+insert into option (option_id, option_value, poll_id) values (4, 'Jaguar', 2);
8
+insert into option (option_id, option_value, poll_id) values (5, 'Otter', 2);
9
+insert into option (option_id, option_value, poll_id) values (6, 'Camel', 2);
10
+
11
+insert into poll (poll_id, question) values (3, 'What is the best bear?');
12
+insert into option (option_id, option_value, poll_id) values (7, 'Beets', 3);
13
+insert into option (option_id, option_value, poll_id) values (8, 'Bears', 3);
14
+insert into option (option_id, option_value, poll_id) values (9, 'Battlstar Gallactica', 3);
15
+
16
+insert into poll (poll_id, question) values (4, 'What is the best Office Character');
17
+insert into option (option_id, option_value, poll_id) values (10, 'Creed', 4);
18
+insert into option (option_id, option_value, poll_id) values (11, 'Jim', 4);
19
+insert into option (option_id, option_value, poll_id) values (12, 'Dwight', 4);
20
+
21
+insert into poll (poll_id, question) values (5, 'What is the airspeed velocity of a swallow?');
22
+insert into option (option_id, option_value, poll_id) values (13, 'What kind of swallow?', 5);
23
+insert into option (option_id, option_value, poll_id) values (14, 'African?', 5);
24
+insert into option (option_id, option_value, poll_id) values (15, 'European?', 5);
25
+
26
+insert into poll (poll_id, question) values (6, 'What is the best cheese?');
27
+insert into option (option_id, option_value, poll_id) values (16, 'Gouda', 6);
28
+insert into option (option_id, option_value, poll_id) values (17, 'Muenster', 6);
29
+insert into option (option_id, option_value, poll_id) values (18, 'Cheddar', 6);
30
+
31
+insert into poll (poll_id, question) values (7, 'How do you like your steak cooked?');
32
+insert into option (option_id, option_value, poll_id) values (19, 'Rare', 7);
33
+insert into option (option_id, option_value, poll_id) values (20, 'Medium Rare', 7);
34
+insert into option (option_id, option_value, poll_id) values (21, 'Medium', 7);
35
+
36
+insert into poll (poll_id, question) values (8, 'Where do you live?');
37
+insert into option (option_id, option_value, poll_id) values (22, 'Wilmington', 8);
38
+insert into option (option_id, option_value, poll_id) values (23, 'Newark', 8);
39
+insert into option (option_id, option_value, poll_id) values (24, 'Kennet', 8);
40
+
41
+insert into poll (poll_id, question) values (9, 'What is your favorite clown?');
42
+insert into option (option_id, option_value, poll_id) values (25, 'Pennywise', 9);
43
+insert into option (option_id, option_value, poll_id) values (26, 'Bozo', 9);
44
+insert into option (option_id, option_value, poll_id) values (27, 'Stinky Pete', 9);
45
+
46
+insert into poll (poll_id, question) values (10, 'How much wood could a wood chuck chuck');
47
+insert into option (option_id, option_value, poll_id) values (28, 'Some Wood', 10);
48
+insert into option (option_id, option_value, poll_id) values (29, 'No Wood', 10);
49
+insert into option (option_id, option_value, poll_id) values (30, 'So Much Wood', 10);
50
+
51
+insert into poll (poll_id, question) values (11, 'Who is the greatest?');
52
+insert into option (option_id, option_value, poll_id) values (31, 'Conan the Barbarian', 11);
53
+insert into option (option_id, option_value, poll_id) values (32, 'Conan OBrian', 11);
54
+insert into option (option_id, option_value, poll_id) values (33, 'Conan the Librarian', 11);
55
+
56
+insert into poll (poll_id, question) values (12, 'What is your favorite milk?');
57
+insert into option (option_id, option_value, poll_id) values (34, 'Goat', 12);
58
+insert into option (option_id, option_value, poll_id) values (35, 'Cow', 12);
59
+insert into option (option_id, option_value, poll_id) values (36, 'Camel', 12);
60
+
61
+insert into poll (poll_id, question) values (13, 'How much Diggity is there?');
62
+insert into option (option_id, option_value, poll_id) values (37, 'Some Diggity', 13);
63
+insert into option (option_id, option_value, poll_id) values (38, 'No Diggity', 13);
64
+insert into option (option_id, option_value, poll_id) values (39, 'An overwhelming surplus of Diggity', 13);
65
+
66
+insert into poll (poll_id, question) values (14, 'What is your favorite country?');
67
+insert into option (option_id, option_value, poll_id) values (40, 'Wakanda', 14);
68
+insert into option (option_id, option_value, poll_id) values (41, 'Narnia', 14);
69
+insert into option (option_id, option_value, poll_id) values (42, 'Ishbala', 14);
70
+
71
+insert into poll (poll_id, question) values (15, 'Who will win the Iron Throne?');
72
+insert into option (option_id, option_value, poll_id) values (43, 'Daenyrys', 15);
73
+insert into option (option_id, option_value, poll_id) values (44, 'Tyrion', 15);
74
+insert into option (option_id, option_value, poll_id) values (45, 'Cersei', 15);
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+

+ 2
- 0
src/main/resource/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}

+ 0
- 4
src/test/java/io/zipcoder/tc_spring_poll_application/QuickPollApplicationTest.java Целия файл

@@ -1,4 +0,0 @@
1
-package io.zipcoder.tc_spring_poll_application;
2
-
3
-public class QuickPollApplicationTest {
4
-}

+ 4
- 0
src/test/java/quickpoll/io/zipcoder/tc_spring_poll_application/QuickPollApplicationTest.java Целия файл

@@ -0,0 +1,4 @@
1
+package quickpoll.io.zipcoder.tc_spring_poll_application;
2
+
3
+public class QuickPollApplicationTest {
4
+}