5 Commitit

Tekijä SHA1 Viesti Päivämäärä
  Yesoda Sanka 2aa61671d2 commited 5 vuotta sitten
  Yesoda Sanka 5a6c4ee399 Merge branch 'master' of https://git.zipcode.rocks/Cohort4.2/SpringQuickPoll 5 vuotta sitten
  git-leon 7a0cb83508 Update 'README.md' 5 vuotta sitten
  git-leon d5ac3273fc Update 'README.md' 5 vuotta sitten
  git-leon 14a2b3fd25 Update 'README.md' 6 vuotta sitten

+ 12
- 9
README.md Näytä tiedosto

@@ -140,7 +140,7 @@ public ResponseEntity<Iterable<Poll>> getAllPolls() {
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.
141 141
 * Because we don’t have any polls created yet, this command should result in an empty collection.
142 142
 * If your application cannot run because something is occupying a port, use this command with the respective port number specified:
143
-	* ``kill -kill `lsof -t -i tcp:8080` ``
143
+	* ``npx kill-port 8080``
144 144
 
145 145
 
146 146
 
@@ -506,7 +506,7 @@ public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundExcepti
506 506
 
507 507
 
508 508
 
509
-## Part 5.4 - Validating domain entities
509
+## Part 5.5 - Validating domain entities
510 510
 
511 511
 Now it's time to make sure that all objects persisted to the database actually contain valid values. Use the `org.hibernate.validator.constraints.NotEmpty` and `javax.validation.constraints.Size` and `javax.validation.Valid` annotations for validation.
512 512
 
@@ -515,7 +515,7 @@ Now it's time to make sure that all objects persisted to the database actually c
515 515
   - `question` should be `@NotEmpty`
516 516
 - To enforce these validations, add `@Valid` annotations to Poll objects in `RequestMapping`-annotated controller methods (there should be 2)
517 517
 
518
-## Part 5.5 - Customizing validation errors
518
+## Part 5.6 - Customizing validation errors
519 519
 
520 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:
521 521
 
@@ -525,14 +525,14 @@ In order to customize validation errors we'll need a class for error information
525 525
 We also need a new field in the `ErrorDetail` class to hold errors. There may be multiple validation errors associated with a request, sometimes more than one of the same type, so this field will be a collection, specifically a `Map<String, List<ValidationError>> errors` field.
526 526
 
527 527
 
528
-## Part 5.6 - Create a validation error handler
528
+## Part 5.7 - Create a validation error handler
529 529
 
530 530
 - add below handler to `RestExceptionHandler`
531 531
 
532 532
 ```java
533 533
 @ExceptionHandler(MethodArgumentNotValidException.class)
534 534
 public ResponseEntity<?>
535
-handleValidationError(  MethodArgumentNotValidException manve,
535
+handleValidationError(MethodArgumentNotValidException manve,
536 536
 						HttpServletRequest request){...}
537 537
 ```
538 538
 
@@ -559,7 +559,10 @@ for(FieldError fe : fieldErrors) {
559 559
 }
560 560
 ```
561 561
 
562
-## Part 5.7 - Externalize strings in a messages.properties file
562
+- Use an autowired `MessageSource` object in the `RestExceptionHandler` to set the message on ValidationError objects (ie: `setMessage(messageSource.getMessage(fe,null));` )
563
+  - This object will be autowired (or injected) the same way your `CRUDRepository` instances are.
564
+
565
+## Part 5.8 - Externalize strings in a messages.properties file
563 566
 
564 567
 Commonly used strings in your Java program can be removed from the source code and placed in a separate file. This is called externalizing, and is useful for allowing changes to text displayed without impacting actual program logic. One example of where this is done is in internationalization, the practice of providing multilingual support in an application, allowing users to use an application in their native language.
565 568
 
@@ -568,8 +571,7 @@ There are two steps needed here to externalize and standardize the validation er
568 571
 - Create a `messages.properties` file in the `src/main/resources` directory with the given properties below
569 572
   - `messages.properties` is a key-value file stored in plain text. Your IDE may have a table-based view or show the contents as text
570 573
   - `.properties` files are a common idiom in Java applications; they contain additional information the application uses that doesn't impact the actual source code.
571
-- Use an autowired `MessageSource` object in the `RestExceptionHandler` to set the message on ValidationError objects (ie: `setMessage(messageSource.getMessage(fe,null));` )
572
-  - This object will be autowired (or injected) the same way your `CRUDRepository` instances are.
574
+
573 575
 
574 576
 **`messages.properties` content**:
575 577
 
@@ -646,6 +648,7 @@ Size.poll.options=Options must be greater than {2} and less than {1}
646 648
 ## Part 6.2 - Spring's Built-in Pagination
647 649
 
648 650
 * Make use of Spring's built-in page number pagination support by researching `org.springframework.data.repository.PagingAndSortingRepository`.
649
-* Modify respective `Controller` methods to handle `Pageable` arguments.
651
+* Modify respective `Controller` methods to handle `Pageable` arguments and `Page<T>` return-types.
652
+* Modify respective `Repository` methods to handle `Page<T>` objects.
650 653
 * Send a `GET` request to `http://localhost:8080/polls?page=0&size=2` via Postman.
651 654
 * Ensure the response is a `JSON` object with pagination-specific information.

+ 28
- 3
src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java Näytä tiedosto

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

+ 102
- 39
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Näytä tiedosto

@@ -4,11 +4,15 @@ import io.zipcoder.tc_spring_poll_application.domain.Poll;
4 4
 import io.zipcoder.tc_spring_poll_application.domain.repositories.PollRepository;
5 5
 import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
6 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;
7 10
 import org.springframework.http.HttpStatus;
8 11
 import org.springframework.http.ResponseEntity;
9 12
 import org.springframework.web.bind.annotation.*;
10 13
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11 14
 
15
+import javax.validation.Valid;
12 16
 import java.net.URI;
13 17
 
14 18
 /*
@@ -24,57 +28,116 @@ Create a `PollController` class in the `controller` sub package.
24 28
 public class PollController {
25 29
 
26 30
 
27
-    PollRepository pollRepository;
31
+    private PollRepository pollRepository;
32
+
33
+
34
+    //    @Autowired
35
+//    public PollController(PollRepository pollRepository1) {
36
+//        this.pollRepository = pollRepository1;
37
+//
38
+//    }
39
+//
40
+//    @RequestMapping(value = "/polls", method = RequestMethod.GET)
41
+//    public ResponseEntity<Iterable<Poll>> getAllPolls() {
42
+//        Iterable<Poll> allPolls = pollRepository.findAll();
43
+//        return new ResponseEntity<>(allPolls, HttpStatus.OK);
44
+//    }
45
+//
46
+//    @RequestMapping(value = "/polls", method = RequestMethod.POST)
47
+//
48
+//    public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
49
+//        poll = pollRepository.save(poll);
50
+//
51
+//        URI newPollUri = ServletUriComponentsBuilder
52
+//                .fromCurrentRequest()
53
+//                .path("/{id}")
54
+//                .buildAndExpand(poll.getId())
55
+//                .toUri();
56
+//
57
+//        return new ResponseEntity<>(null, HttpStatus.CREATED);
58
+//    }
59
+//
60
+//    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.GET)
61
+//    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
62
+//        Poll p = pollRepository.findOne(pollId);
63
+//        return new ResponseEntity<>(p, HttpStatus.OK);
64
+//    }
65
+//
66
+//    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.PUT)
67
+//    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
68
+//        // Save the entity
69
+//        Poll p = pollRepository.save(poll);
70
+//        return new ResponseEntity<>(HttpStatus.OK);
71
+//    }
72
+//
73
+//    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.DELETE)
74
+//    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
75
+//        pollRepository.delete(pollId);
76
+//        return new ResponseEntity<>(HttpStatus.OK);
77
+//    }
78
+//
79
+////    public void verifypoll() throws ResourceNotFoundException {
80
+////        throw new ResourceNotFoundException();
81
+////    }
82
+//}
83
+    public void pollExists(Long pollId) throws ResourceNotFoundException {
84
+        if (pollRepository.findOne(pollId) == null) {
85
+            throw new ResourceNotFoundException("The poll specified does not exist.");
86
+        }
28 87
 
88
+    }
29 89
 
30 90
     @Autowired
31
-    public PollController(PollRepository pollRepository1) {
32
-        this.pollRepository = pollRepository1;
33
-
91
+    public PollController(PollRepository pollRepository) {
92
+        this.pollRepository = pollRepository;
34 93
     }
35 94
 
36
-    @RequestMapping(value = "/polls", method = RequestMethod.GET)
37
-    public ResponseEntity<Iterable<Poll>> getAllPolls() {
95
+    @GetMapping("/polls")
96
+    public ResponseEntity<Iterable<Poll>> getPolls() {
38 97
         Iterable<Poll> allPolls = pollRepository.findAll();
39 98
         return new ResponseEntity<>(allPolls, HttpStatus.OK);
40 99
     }
41 100
 
42
-    @RequestMapping(value = "/polls", method = RequestMethod.POST)
43
-
44
-    public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
45
-        poll = pollRepository.save(poll);
46
-
47
-        URI newPollUri = ServletUriComponentsBuilder
48
-                .fromCurrentRequest()
49
-                .path("/{id}")
50
-                .buildAndExpand(poll.getId())
51
-                .toUri();
52
-
53
-        return new ResponseEntity<>(null, HttpStatus.CREATED);
54
-    }
55
-
56
-    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.GET)
57
-    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
58
-        Poll p = pollRepository.findOne(pollId);
59
-        return new ResponseEntity<>(p, HttpStatus.OK);
60
-    }
101
+    @GetMapping("/polls/{size}/{pageNum}")
102
+    public ResponseEntity<Page<Poll>> getPollsPaged(@PathVariable int size, @PathVariable int pageNum) {
61 103
 
62
-    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.PUT)
63
-    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
64
-        // Save the entity
65
-        Poll p = pollRepository.save(poll);
66
-        return new ResponseEntity<>(HttpStatus.OK);
67
-    }
104
+        PageRequest pageRequest = new PageRequest(pageNum, size);
105
+        Page<Poll> page = pollRepository.findAll(pageRequest);
68 106
 
69
-    @RequestMapping(value = "/polls/{pollId}", method = RequestMethod.DELETE)
70
-    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
71
-        pollRepository.delete(pollId);
72
-        return new ResponseEntity<>(HttpStatus.OK);
107
+        return new ResponseEntity<>(page, HttpStatus.OK);
73 108
     }
74
-
75
-    public void verifypoll() throws ResourceNotFoundException {
76
-        throw new ResourceNotFoundException();
109
+        @PostMapping("/polls")
110
+        @Valid
111
+        public ResponseEntity<?> createPoll (@RequestBody Poll poll){
112
+            poll = pollRepository.save(poll);
113
+            HttpHeaders httpHeaders = new HttpHeaders();
114
+            httpHeaders.setLocation(ServletUriComponentsBuilder
115
+                    .fromCurrentRequest()
116
+                    .path("/{id}")
117
+                    .buildAndExpand(poll.getId())
118
+                    .toUri());
119
+            return new ResponseEntity<>(null, HttpStatus.CREATED);
120
+        }
121
+
122
+        @GetMapping("/polls/{pollId}")
123
+        public ResponseEntity<?> getPoll (@PathVariable Long pollId){
124
+            Poll p = pollRepository.findOne(pollId);
125
+            return new ResponseEntity<>(p, HttpStatus.OK);
126
+
127
+        }
128
+
129
+        @PutMapping("/polls/{pollId}")
130
+        @Valid
131
+        public ResponseEntity<?> updatePoll (@RequestBody Poll poll, @PathVariable Long pollId){
132
+            Poll p = pollRepository.save(poll);
133
+            return new ResponseEntity<>(HttpStatus.OK);
134
+        }
135
+
136
+        @DeleteMapping("/polls/{pollId}")
137
+        public ResponseEntity<?> deletePoll (@PathVariable Long pollId){
138
+            pollRepository.delete(pollId);
139
+            return new ResponseEntity<>(HttpStatus.OK);
140
+        }
77 141
     }
78
-}
79 142
 
80 143
 

+ 2
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Näytä tiedosto

@@ -43,6 +43,7 @@ public class Poll {
43 43
     @OneToMany(cascade = CascadeType.ALL)
44 44
 		 @JoinColumn(name = "POLL_ID")
45 45
 		@OrderBy
46
+       @Size(min=2,max=6)
46 47
       private  Set<Option> options;
47 48
 
48 49
 
@@ -66,7 +67,7 @@ public class Poll {
66 67
 
67 68
         this.question = question;
68 69
     }
69
-    @Size(min=2, max = 6)
70
+
70 71
     public Set<Option> getOptions() {
71 72
         return options;
72 73
     }

+ 2
- 2
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Näytä tiedosto

@@ -23,13 +23,13 @@ Create a `Vote` class in the `domain` sub-package.
23 23
 @Entity
24 24
 public class Vote {
25 25
     @Id
26
-    @GeneratedValue
26
+    @GeneratedValue(strategy = GenerationType.AUTO )
27 27
     @Column (name="VOTE_ID")
28 28
     private Long id;
29 29
 
30 30
     @ManyToOne
31 31
             @JoinColumn (name="OPTION_ID")
32
-    Option option;
32
+    private Option option;
33 33
 
34 34
 
35 35
     public Long getId() {

+ 2
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/domain/repositories/PollRepository.java Näytä tiedosto

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

+ 25
- 7
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/ErrorDetail.java Näytä tiedosto

@@ -15,11 +15,25 @@ import java.util.List;
15 15
 import java.util.Map;
16 16
 
17 17
 public class ErrorDetail {
18
-    String title;
19
-    int status;
20
-    String detail;
21
-    Long timeStamp;
22
-    String developerMessage;
18
+   private String title;
19
+  private  int status;
20
+  private  String detail;
21
+  private  Long timeStamp;
22
+ private   String developerMessage;
23
+ private Map<String, List<ValidationError>> errors;
24
+
25
+    public ErrorDetail() {
26
+    }
27
+
28
+    public ErrorDetail(String title, int status, String detail, Long timestamp, String developerMessage, Map<String, List<ValidationError>> errors) {
29
+                this.title = title;
30
+              this.status = status;
31
+              this.detail = detail;
32
+             this.timeStamp = timestamp;
33
+             this.developerMessage = developerMessage;
34
+               this.errors = errors;
35
+        }
36
+
23 37
 
24 38
     public String getTitle() {
25 39
         return title;
@@ -61,7 +75,11 @@ public class ErrorDetail {
61 75
         this.developerMessage = developerMessage;
62 76
     }
63 77
 
64
-    public Map<String, List<ValidationError>> getErrors() {
65
-        return null;
78
+    public Map<String, List<ValidationError>> getErrors()
79
+    {
80
+        return  errors;
81
+    }
82
+    public  void setErrors (Map<String, List<ValidationError>> errors){
83
+        this.errors =errors ;
66 84
     }
67 85
 }

+ 4
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/OptionCount.java Näytä tiedosto

@@ -6,18 +6,22 @@ public class OptionCount {
6 6
         private int count;
7 7
 
8 8
         public Long getOptionId() {
9
+
9 10
             return optionId;
10 11
         }
11 12
 
12 13
         public void setOptionId(Long optionId) {
14
+
13 15
             this.optionId = optionId;
14 16
         }
15 17
 
16 18
         public int getCount() {
19
+
17 20
             return count;
18 21
         }
19 22
 
20 23
         public void setCount(int count) {
24
+
21 25
             this.count = count;
22 26
         }
23 27
 

+ 42
- 5
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/RestExceptionHandler.java Näytä tiedosto

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

+ 15
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/VoteResult.java Näytä tiedosto

@@ -18,6 +18,21 @@ public class VoteResult {
18 18
     }
19 19
 
20 20
     public void setResults(Collection<OptionCount> results) {
21
+
21 22
         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
+         }
23 38
 }

+ 2
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/error/MethodAr1gumentNotValidException.java Näytä tiedosto

@@ -1,4 +1,5 @@
1 1
 package io.zipcoder.tc_spring_poll_application.error;
2 2
 
3 3
 public class MethodAr1gumentNotValidException extends Throwable {
4
-}
4
+
5
+}

+ 48
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/error/RestExceptionHandler.java Näytä tiedosto

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

+ 35
- 35
src/main/java/io/zipcoder/tc_spring_poll_application/error/Validationerrorhandler.java Näytä tiedosto

@@ -16,41 +16,41 @@ import java.util.List;
16 16
 
17 17
 //@RestExceptionHandler
18 18
 public class Validationerrorhandler<RestExceptionHandler> {
19
-    @Autowired
20
-
21
-    private  MessageSource  messageSource ;
22
-    @ExceptionHandler(MethodAr1gumentNotValidException.class)
23
-
24
-
25
-
26
-
27
-    public ResponseEntity<?>
28
-    handleValidationError(  MethodArgumentNotValidException manve,
29
-                            HttpServletRequest request){
30
-
31
-
32
-
33
-        List<FieldError> fieldErrors =  manve .getBindingResult().getFieldErrors();
34
-        for(FieldError fe : fieldErrors) {
35
-
36
-            ErrorDetail  errorDetail=new ErrorDetail() ;
37
-
38
-            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
39
-
40
-            if(validationErrorList == null) {
41
-                validationErrorList = new ArrayList<>();
42
-
43
-                errorDetail.getErrors().put(fe.getField(), validationErrorList);
44
-            }
45
-
46
-            ValidationError validationError = new ValidationError();
47
-            validationError.setCode(fe.getCode());
48
-            validationError.setMessage(messageSource.getMessage(fe, null));
49
-            validationErrorList.add(validationError);
50
-        }
51
-        ResponseEntity responseEntity = new ResponseEntity<>( HttpStatus.BAD_REQUEST);
52
-        return responseEntity;
53
-    }
19
+//    @Autowired
20
+//
21
+//    private  MessageSource  messageSource ;
22
+//    @ExceptionHandler(MethodAr1gumentNotValidException.class)
23
+//
24
+//
25
+//
26
+//
27
+//    public ResponseEntity<?>
28
+//    handleValidationError(  MethodArgumentNotValidException manve,
29
+//                            HttpServletRequest request){
30
+//
31
+//
32
+//
33
+//        List<FieldError> fieldErrors =  manve .getBindingResult().getFieldErrors();
34
+//        for(FieldError fe : fieldErrors) {
35
+//
36
+//            ErrorDetail  errorDetail=new ErrorDetail() ;
37
+//
38
+//            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
39
+//
40
+//            if(validationErrorList == null) {
41
+//                validationErrorList = new ArrayList<>();
42
+//
43
+//                errorDetail.getErrors().put(fe.getField(), validationErrorList);
44
+//            }
45
+//
46
+//            ValidationError validationError = new ValidationError();
47
+//            validationError.setCode(fe.getCode());
48
+//            validationError.setMessage(messageSource.getMessage(fe, null));
49
+//            validationErrorList.add(validationError);
50
+//        }
51
+//        ResponseEntity responseEntity = new ResponseEntity<>( HttpStatus.BAD_REQUEST);
52
+//        return responseEntity;
53
+//    }
54 54
     }
55 55
 
56 56
 

+ 34
- 0
src/main/resources/import.sql Näytä tiedosto

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

+ 5
- 1
src/main/resources/message.properties Näytä tiedosto

@@ -1,4 +1,8 @@
1 1
 spring.datasource.url=jdbc:h2:mem:testdb;Mode=Oracle
2 2
 spring.datasource.platform=h2
3 3
 spring.jpa.hibernate.ddl-auto=none
4
-spring.datasource.continue-on-error=true
4
+spring.datasource.continue-on-error=true
5
+
6
+NotEmpty.poll.question=Question is a required field
7
+
8
+Size.poll.options=Options must be greater than {2} and less than {1}