5 Revīzijas

Autors SHA1 Ziņojums Datums
  Yesoda Sanka 2aa61671d2 commited 5 gadus atpakaļ
  Yesoda Sanka 5a6c4ee399 Merge branch 'master' of https://git.zipcode.rocks/Cohort4.2/SpringQuickPoll 5 gadus atpakaļ
  git-leon 7a0cb83508 Update 'README.md' 5 gadus atpakaļ
  git-leon d5ac3273fc Update 'README.md' 5 gadus atpakaļ
  git-leon 14a2b3fd25 Update 'README.md' 6 gadus atpakaļ

+ 12
- 9
README.md Parādīt failu

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.
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
 * Because we don’t have any polls created yet, this command should result in an empty collection.
141
 * Because we don’t have any polls created yet, this command should result in an empty collection.
142
 * If your application cannot run because something is occupying a port, use this command with the respective port number specified:
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
 
506
 
507
 
507
 
508
 
508
 
509
-## Part 5.4 - Validating domain entities
509
+## Part 5.5 - Validating domain entities
510
 
510
 
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.
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
   - `question` should be `@NotEmpty`
515
   - `question` should be `@NotEmpty`
516
 - To enforce these validations, add `@Valid` annotations to Poll objects in `RequestMapping`-annotated controller methods (there should be 2)
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
 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 `io.zipcoder.tc_spring_poll_application.dto.error` with the following fields and appropriate getters and setters:
521
 
521
 
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.
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
 - add below handler to `RestExceptionHandler`
530
 - add below handler to `RestExceptionHandler`
531
 
531
 
532
 ```java
532
 ```java
533
 @ExceptionHandler(MethodArgumentNotValidException.class)
533
 @ExceptionHandler(MethodArgumentNotValidException.class)
534
 public ResponseEntity<?>
534
 public ResponseEntity<?>
535
-handleValidationError(  MethodArgumentNotValidException manve,
535
+handleValidationError(MethodArgumentNotValidException manve,
536
 						HttpServletRequest request){...}
536
 						HttpServletRequest request){...}
537
 ```
537
 ```
538
 
538
 
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
 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.
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
 - Create a `messages.properties` file in the `src/main/resources` directory with the given properties below
571
 - Create a `messages.properties` file in the `src/main/resources` directory with the given properties below
569
   - `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
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
   - `.properties` files are a common idiom in Java applications; they contain additional information the application uses that doesn't impact the actual source code.
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
 **`messages.properties` content**:
576
 **`messages.properties` content**:
575
 
577
 
646
 ## Part 6.2 - Spring's Built-in Pagination
648
 ## Part 6.2 - Spring's Built-in Pagination
647
 
649
 
648
 * Make use of Spring's built-in page number pagination support by researching `org.springframework.data.repository.PagingAndSortingRepository`.
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
 * Send a `GET` request to `http://localhost:8080/polls?page=0&size=2` via Postman.
653
 * Send a `GET` request to `http://localhost:8080/polls?page=0&size=2` via Postman.
651
 * Ensure the response is a `JSON` object with pagination-specific information.
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 Parādīt failu

2
 
2
 
3
 import io.zipcoder.tc_spring_poll_application.domain.Vote;
3
 import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
 import io.zipcoder.tc_spring_poll_application.domain.repositories.VoteRepository;
4
 import io.zipcoder.tc_spring_poll_application.domain.repositories.VoteRepository;
5
+import io.zipcoder.tc_spring_poll_application.dtos.OptionCount;
5
 import io.zipcoder.tc_spring_poll_application.dtos.VoteResult;
6
 import io.zipcoder.tc_spring_poll_application.dtos.VoteResult;
6
 import org.springframework.beans.factory.annotation.Autowired;
7
 import org.springframework.beans.factory.annotation.Autowired;
7
 import org.springframework.http.HttpStatus;
8
 import org.springframework.http.HttpStatus;
11
 import org.springframework.web.bind.annotation.RequestParam;
12
 import org.springframework.web.bind.annotation.RequestParam;
12
 import org.springframework.web.bind.annotation.RestController;
13
 import org.springframework.web.bind.annotation.RestController;
13
 
14
 
15
+import java.util.ArrayList;
16
+
14
 @RestController
17
 @RestController
15
 public class ComputeResultController {
18
 public class ComputeResultController {
16
 
19
 
18
 
21
 
19
     @Autowired
22
     @Autowired
20
     public ComputeResultController(VoteRepository voteRepository) {
23
     public ComputeResultController(VoteRepository voteRepository) {
24
+
21
         this.voteRepository = voteRepository;
25
         this.voteRepository = voteRepository;
22
     }
26
     }
23
 
27
 
25
 
29
 
26
     public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
30
     public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
27
         VoteResult voteResult = new VoteResult();
31
         VoteResult voteResult = new VoteResult();
32
+        voteResult.setResults(new ArrayList<OptionCount>());
28
         Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
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 Parādīt failu

4
 import io.zipcoder.tc_spring_poll_application.domain.repositories.PollRepository;
4
 import io.zipcoder.tc_spring_poll_application.domain.repositories.PollRepository;
5
 import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
5
 import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
6
 import org.springframework.beans.factory.annotation.Autowired;
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
 import org.springframework.http.HttpStatus;
10
 import org.springframework.http.HttpStatus;
8
 import org.springframework.http.ResponseEntity;
11
 import org.springframework.http.ResponseEntity;
9
 import org.springframework.web.bind.annotation.*;
12
 import org.springframework.web.bind.annotation.*;
10
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
13
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11
 
14
 
15
+import javax.validation.Valid;
12
 import java.net.URI;
16
 import java.net.URI;
13
 
17
 
14
 /*
18
 /*
24
 public class PollController {
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
     @Autowired
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
         Iterable<Poll> allPolls = pollRepository.findAll();
97
         Iterable<Poll> allPolls = pollRepository.findAll();
39
         return new ResponseEntity<>(allPolls, HttpStatus.OK);
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 Parādīt failu

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

+ 2
- 2
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Parādīt failu

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

+ 2
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/domain/repositories/PollRepository.java Parādīt failu

2
 
2
 
3
 import io.zipcoder.tc_spring_poll_application.domain.Poll;
3
 import io.zipcoder.tc_spring_poll_application.domain.Poll;
4
 import org.springframework.data.repository.CrudRepository;
4
 import org.springframework.data.repository.CrudRepository;
5
+import org.springframework.data.repository.PagingAndSortingRepository;
5
 import org.springframework.stereotype.Repository;
6
 import org.springframework.stereotype.Repository;
6
 
7
 
7
 @Repository
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 Parādīt failu

15
 import java.util.Map;
15
 import java.util.Map;
16
 
16
 
17
 public class ErrorDetail {
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
     public String getTitle() {
38
     public String getTitle() {
25
         return title;
39
         return title;
61
         this.developerMessage = developerMessage;
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 Parādīt failu

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

+ 42
- 5
src/main/java/io/zipcoder/tc_spring_poll_application/dtos/RestExceptionHandler.java Parādīt failu

1
 package io.zipcoder.tc_spring_poll_application.dtos;
1
 package io.zipcoder.tc_spring_poll_application.dtos;
2
 
2
 
3
+import io.zipcoder.tc_spring_poll_application.error.ValidationError;
3
 import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
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
 import org.springframework.http.HttpStatus;
7
 import org.springframework.http.HttpStatus;
5
 import org.springframework.http.ResponseEntity;
8
 import org.springframework.http.ResponseEntity;
9
+import org.springframework.validation.FieldError;
10
+import org.springframework.web.bind.MethodArgumentNotValidException;
6
 import org.springframework.web.bind.annotation.ControllerAdvice;
11
 import org.springframework.web.bind.annotation.ControllerAdvice;
7
 import org.springframework.web.bind.annotation.ExceptionHandler;
12
 import org.springframework.web.bind.annotation.ExceptionHandler;
8
 
13
 
9
 import javax.servlet.http.HttpServletRequest;
14
 import javax.servlet.http.HttpServletRequest;
15
+import java.util.ArrayList;
16
+import java.util.Date;
17
+import java.util.List;
10
 
18
 
11
 @ControllerAdvice
19
 @ControllerAdvice
12
 public class RestExceptionHandler {
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 Parādīt failu

18
     }
18
     }
19
 
19
 
20
     public void setResults(Collection<OptionCount> results) {
20
     public void setResults(Collection<OptionCount> results) {
21
+
21
         this.results = results;
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 Parādīt failu

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

+ 48
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/error/RestExceptionHandler.java Parādīt failu

1
 package io.zipcoder.tc_spring_poll_application.error;
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 Parādīt failu

16
 
16
 
17
 //@RestExceptionHandler
17
 //@RestExceptionHandler
18
 public class Validationerrorhandler<RestExceptionHandler> {
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 Parādīt failu

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 Parādīt failu

1
 spring.datasource.url=jdbc:h2:mem:testdb;Mode=Oracle
1
 spring.datasource.url=jdbc:h2:mem:testdb;Mode=Oracle
2
 spring.datasource.platform=h2
2
 spring.datasource.platform=h2
3
 spring.jpa.hibernate.ddl-auto=none
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}