Eric Barnaba před 8 roky
rodič
revize
e841148796

+ 17
- 5
src/main/java/quickpoll/dtos/ComputeResultController.java Zobrazit soubor

@@ -10,6 +10,8 @@ import org.springframework.web.bind.annotation.RequestParam;
10 10
 import org.springframework.web.bind.annotation.RestController;
11 11
 
12 12
 import javax.inject.Inject;
13
+import java.util.HashMap;
14
+import java.util.Map;
13 15
 
14 16
 @RestController
15 17
 public class ComputeResultController {
@@ -21,11 +23,21 @@ public class ComputeResultController {
21 23
         VoteResult voteResult = new VoteResult();
22 24
         Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
23 25
 
24
-        //TODO: count votes
25
-//        for(Vote v : allVotes){
26
-//
27
-//        }
28
-        voteResult.setTotalVotes(200);
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());
29 41
 
30 42
         return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
31 43
     }

+ 12
- 0
src/main/java/quickpoll/dtos/error/ErrorDetail.java Zobrazit soubor

@@ -1,11 +1,15 @@
1 1
 package quickpoll.dtos.error;
2 2
 
3
+import java.util.List;
4
+import java.util.Map;
5
+
3 6
 public class ErrorDetail {
4 7
     private String title;
5 8
     private int status;
6 9
     private String detail;
7 10
     private long timeStamp;
8 11
     private String developerMessage;
12
+    private Map<String,List<ValidationError>> errors;
9 13
 
10 14
     public String getTitle() {
11 15
         return title;
@@ -46,4 +50,12 @@ public class ErrorDetail {
46 50
     public void setDeveloperMessage(String developerMessage) {
47 51
         this.developerMessage = developerMessage;
48 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
+    }
49 61
 }

+ 4
- 4
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/controller/PollController.java Zobrazit soubor

@@ -26,9 +26,9 @@ public class PollController {
26 26
    }
27 27
 
28 28
 
29
-   @Valid
29
+
30 30
    @RequestMapping(value = "/polls", method = RequestMethod.POST)
31
-   public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
31
+   public ResponseEntity<?> createPoll(@Valid @RequestBody Poll poll) {
32 32
        URI newPollUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(poll.getId()).toUri();
33 33
        poll = pollRepository.save(poll);
34 34
        HttpHeaders header = new HttpHeaders();
@@ -43,9 +43,9 @@ public class PollController {
43 43
        return new ResponseEntity<>(p, HttpStatus.OK);
44 44
    }
45 45
 
46
-   @Valid
46
+
47 47
    @RequestMapping(value="/polls/{pollId}", method = RequestMethod.PUT)
48
-   public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId){
48
+   public ResponseEntity<?> updatePoll(@Valid @RequestBody Poll poll, @PathVariable Long pollId){
49 49
        verifyPoll(pollId);
50 50
        Poll p = pollRepository.save(poll);
51 51
        return new ResponseEntity<>(HttpStatus.OK);

+ 1
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/domain/Poll.java Zobrazit soubor

@@ -3,6 +3,7 @@ package quickpoll.io.zipcoder.tc_spring_poll_application.domain;
3 3
 import org.hibernate.validator.constraints.NotEmpty;
4 4
 
5 5
 import javax.persistence.*;
6
+import javax.validation.constraints.NotNull;
6 7
 import javax.validation.constraints.Size;
7 8
 import java.util.Set;
8 9
 

+ 52
- 0
src/main/java/quickpoll/io/zipcoder/tc_spring_poll_application/exception/RestExceptionHandler.java Zobrazit soubor

@@ -1,16 +1,33 @@
1 1
 package quickpoll.io.zipcoder.tc_spring_poll_application.exception;
2 2
 
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.context.MessageSource;
3 5
 import org.springframework.http.HttpStatus;
4 6
 import org.springframework.http.ResponseEntity;
7
+import org.springframework.validation.FieldError;
8
+import org.springframework.web.bind.MethodArgumentNotValidException;
5 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;
6 13
 import quickpoll.dtos.error.ErrorDetail;
14
+import quickpoll.dtos.error.ValidationError;
7 15
 
16
+
17
+import javax.inject.Inject;
8 18
 import javax.servlet.http.HttpServletRequest;
19
+import java.util.ArrayList;
9 20
 import java.util.Date;
21
+import java.util.List;
10 22
 
11 23
 @ControllerAdvice
12 24
 public class RestExceptionHandler {
13 25
 
26
+    @Autowired
27
+    private MessageSource messageSource;
28
+
29
+    @ExceptionHandler(ResourceNotFoundException.class)
30
+    @ResponseStatus(HttpStatus.NOT_FOUND)
14 31
     public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
15 32
         ErrorDetail errorDetail = new ErrorDetail();
16 33
         errorDetail.setTitle("Resource Not Found");
@@ -21,4 +38,39 @@ public class RestExceptionHandler {
21 38
 
22 39
         return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
23 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().
61
+                    get(fe.getField());
62
+            if(validationErrorList == null) {
63
+            }
64
+            validationErrorList = new ArrayList<ValidationError>();
65
+            errorDetail.getErrors().put(fe.getField(),
66
+                    validationErrorList);
67
+            ValidationError validationError = new ValidationError();
68
+            validationError.setCode(fe.getCode());
69
+            validationError.setMessage(messageSource.getMessage(fe, null));
70
+            validationErrorList.add(validationError);
71
+        }
72
+        return errorDetail;
73
+    }
74
+
75
+
24 76
 }

+ 4
- 0
src/main/resource/import.sql Zobrazit soubor

@@ -0,0 +1,4 @@
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 (2, 'Blue', 1);

+ 2
- 0
src/main/resource/messages.properties Zobrazit soubor

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