Trinh Tong 6 år sedan
förälder
incheckning
ebabd47eab

+ 36
- 1
src/main/java/io/zipcoder/tc_spring_poll_application/RestExceptionHandler.java Visa fil

1
 package io.zipcoder.tc_spring_poll_application;
1
 package io.zipcoder.tc_spring_poll_application;
2
 
2
 
3
 import io.zipcoder.tc_spring_poll_application.error.ErrorDetail;
3
 import io.zipcoder.tc_spring_poll_application.error.ErrorDetail;
4
+import io.zipcoder.tc_spring_poll_application.error.ValidationError;
4
 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;
7
+import org.springframework.context.MessageSource;
5
 import org.springframework.http.HttpStatus;
8
 import org.springframework.http.HttpStatus;
6
 import org.springframework.http.ResponseEntity;
9
 import org.springframework.http.ResponseEntity;
10
+import org.springframework.validation.FieldError;
11
+import org.springframework.web.bind.MethodArgumentNotValidException;
7
 import org.springframework.web.bind.annotation.ControllerAdvice;
12
 import org.springframework.web.bind.annotation.ControllerAdvice;
8
 import org.springframework.web.bind.annotation.ExceptionHandler;
13
 import org.springframework.web.bind.annotation.ExceptionHandler;
9
 
14
 
10
 import javax.servlet.http.HttpServletRequest;
15
 import javax.servlet.http.HttpServletRequest;
16
+import java.util.ArrayList;
11
 import java.util.Arrays;
17
 import java.util.Arrays;
12
 import java.util.Date;
18
 import java.util.Date;
19
+import java.util.List;
13
 
20
 
14
 @ControllerAdvice
21
 @ControllerAdvice
15
 public class RestExceptionHandler {
22
 public class RestExceptionHandler {
16
 
23
 
24
+    @Autowired
25
+    MessageSource messageSource;
26
+
17
     @ExceptionHandler(ResourceNotFoundException.class)
27
     @ExceptionHandler(ResourceNotFoundException.class)
18
     public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
28
     public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
19
 
29
 
20
         ErrorDetail ed = new ErrorDetail();
30
         ErrorDetail ed = new ErrorDetail();
21
 
31
 
22
         ed.setTimeStamp(new Date().getTime());
32
         ed.setTimeStamp(new Date().getTime());
23
-        ed.setTitle("Validation Failture");
33
+        ed.setTitle("Resource Not Found.");
24
         ed.setStatus(404);
34
         ed.setStatus(404);
25
         ed.setDetail("Unable to complete request or entity was not found.");
35
         ed.setDetail("Unable to complete request or entity was not found.");
26
         ed.setDeveloperMessage(Arrays.toString(rnfe.getStackTrace()));
36
         ed.setDeveloperMessage(Arrays.toString(rnfe.getStackTrace()));
27
 
37
 
28
         return new ResponseEntity<>(ed, HttpStatus.NOT_FOUND);
38
         return new ResponseEntity<>(ed, HttpStatus.NOT_FOUND);
29
     }
39
     }
40
+
41
+    @ExceptionHandler(MethodArgumentNotValidException.class)
42
+    public ResponseEntity<?>
43
+    handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request){
44
+        ErrorDetail ed = new ErrorDetail();
45
+
46
+        ed.setTimeStamp(new Date().getTime());
47
+        ed.setTitle("Validation Failure");
48
+        ed.setStatus(404);
49
+        ed.setDetail("Unable to complete request.");
50
+        ed.setDeveloperMessage(Arrays.toString(manve.getStackTrace()));
51
+
52
+
53
+        List<FieldError> fieldErrors =  manve.getBindingResult().getFieldErrors();
54
+        for(FieldError fe : fieldErrors) {
55
+
56
+            List<ValidationError> validationErrorList = ed.getErrors().computeIfAbsent(fe.getField(), k -> new ArrayList<>());
57
+            ValidationError validationError = new ValidationError();
58
+            validationError.setCode(fe.getCode());
59
+            validationError.setMessage(messageSource.getMessage(fe,null));
60
+            validationErrorList.add(validationError);
61
+        }
62
+
63
+        return new ResponseEntity<>(ed, HttpStatus.BAD_REQUEST);
64
+    }
30
 }
65
 }

+ 3
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Visa fil

10
 import org.springframework.web.bind.annotation.*;
10
 import org.springframework.web.bind.annotation.*;
11
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
12
 
12
 
13
+import javax.validation.Valid;
13
 import java.net.URI;
14
 import java.net.URI;
14
 
15
 
15
 @RestController
16
 @RestController
27
         return new ResponseEntity<>(allPolls, HttpStatus.OK);
28
         return new ResponseEntity<>(allPolls, HttpStatus.OK);
28
     }
29
     }
29
 
30
 
31
+    @Valid
30
     @RequestMapping(value="/polls", method = RequestMethod.POST)
32
     @RequestMapping(value="/polls", method = RequestMethod.POST)
31
     public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
33
     public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
32
         URI newPollUri = ServletUriComponentsBuilder
34
         URI newPollUri = ServletUriComponentsBuilder
48
         return new ResponseEntity<> (p, HttpStatus.OK);
50
         return new ResponseEntity<> (p, HttpStatus.OK);
49
     }
51
     }
50
 
52
 
53
+    @Valid
51
     @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
54
     @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
52
     public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
55
     public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
53
         // Save the entity
56
         // Save the entity

+ 5
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Visa fil

1
 package io.zipcoder.tc_spring_poll_application.domain;
1
 package io.zipcoder.tc_spring_poll_application.domain;
2
 
2
 
3
+import org.hibernate.validator.constraints.NotEmpty;
4
+
3
 import javax.persistence.*;
5
 import javax.persistence.*;
6
+import javax.validation.constraints.Size;
4
 import java.util.Set;
7
 import java.util.Set;
5
 
8
 
6
 @Entity
9
 @Entity
11
     @Column(name = "POLL_ID")
14
     @Column(name = "POLL_ID")
12
     private Long id;
15
     private Long id;
13
 
16
 
17
+    @NotEmpty
14
     @Column(name = "QUESTION")
18
     @Column(name = "QUESTION")
15
     private String question;
19
     private String question;
16
 
20
 
17
     @OneToMany(cascade = CascadeType.ALL)
21
     @OneToMany(cascade = CascadeType.ALL)
18
     @JoinColumn(name = "POLL_ID")
22
     @JoinColumn(name = "POLL_ID")
19
     @OrderBy
23
     @OrderBy
24
+    @Size(min = 2, max = 6)
20
     private Set<Option> options;
25
     private Set<Option> options;
21
 
26
 
22
 
27
 

+ 12
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/error/ErrorDetail.java Visa fil

1
 package io.zipcoder.tc_spring_poll_application.error;
1
 package io.zipcoder.tc_spring_poll_application.error;
2
 
2
 
3
+import java.util.List;
4
+import java.util.Map;
5
+
3
 public class ErrorDetail {
6
 public class ErrorDetail {
4
 
7
 
5
     private String title;
8
     private String title;
7
     private String detail;
10
     private String detail;
8
     private long timeStamp;
11
     private long timeStamp;
9
     private String developerMessage;
12
     private String developerMessage;
13
+    private Map<String, List<ValidationError>> errors;
10
 
14
 
11
     public ErrorDetail() {
15
     public ErrorDetail() {
12
     }
16
     }
50
     public void setDeveloperMessage(String developerMessage) {
54
     public void setDeveloperMessage(String developerMessage) {
51
         this.developerMessage = developerMessage;
55
         this.developerMessage = developerMessage;
52
     }
56
     }
57
+
58
+    public Map<String, List<ValidationError>> getErrors() {
59
+        return errors;
60
+    }
61
+
62
+    public void setErrors(Map<String, List<ValidationError>> errors) {
63
+        this.errors = errors;
64
+    }
53
 }
65
 }

+ 22
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/error/ValidationError.java Visa fil

1
+package io.zipcoder.tc_spring_poll_application.error;
2
+
3
+public class ValidationError {
4
+
5
+    private String code, 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
+}

+ 2
- 0
src/main/resources/message.properties Visa fil

1
+NotEmpty.poll.question=Question is a required field
2
+Size.poll.options=Options must be greater than {2} and less than {1}