|
| 1 | +package restx.validation; |
| 2 | + |
| 3 | +import com.google.common.base.Function; |
| 4 | +import com.google.common.base.Joiner; |
| 5 | +import com.google.common.collect.Collections2; |
| 6 | + |
| 7 | +import javax.validation.ConstraintViolation; |
| 8 | +import javax.validation.Path; |
| 9 | +import javax.validation.metadata.ConstraintDescriptor; |
| 10 | +import java.lang.annotation.ElementType; |
| 11 | +import java.util.Set; |
| 12 | + |
| 13 | +import static com.google.common.collect.Sets.newHashSet; |
| 14 | + |
| 15 | +/** |
| 16 | + * Created by Thomas Zayouna on 07/10/15. |
| 17 | + * Exception wrapping bean validation violations |
| 18 | + */ |
| 19 | +public class MethodArgumentNotValidException extends IllegalArgumentException { |
| 20 | + |
| 21 | + public static class ViolationContent { |
| 22 | + private final String message; |
| 23 | + private final Path propertyPath; |
| 24 | + private final Class rootBeanClass; |
| 25 | + |
| 26 | + public ViolationContent(String message, Path propertyPath, Class rootBeanClass) { |
| 27 | + this.message = message; |
| 28 | + this.propertyPath = propertyPath; |
| 29 | + this.rootBeanClass = rootBeanClass; |
| 30 | + } |
| 31 | + |
| 32 | + public String getMessage() { |
| 33 | + return message; |
| 34 | + } |
| 35 | + |
| 36 | + public Path getPropertyPath() { |
| 37 | + return propertyPath; |
| 38 | + } |
| 39 | + |
| 40 | + public Class getRootBeanClass() { |
| 41 | + return rootBeanClass; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public static Function<ConstraintViolation, ViolationContent> VIOLATION_CONTENT_EXTRACTOR = new Function<ConstraintViolation, ViolationContent>() { |
| 46 | + @Override |
| 47 | + public ViolationContent apply(ConstraintViolation input) { |
| 48 | + return new ViolationContent(input.getMessage(), input.getPropertyPath(), input.getRootBeanClass()); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + private final Set<ViolationContent> violations; |
| 53 | + |
| 54 | + public <T> MethodArgumentNotValidException(Set<ConstraintViolation<T>> violations) { |
| 55 | + // Kept for backward compat for restx <= 0.34 |
| 56 | + super(Joiner.on(",").join(violations)); |
| 57 | + this.violations = newHashSet(Collections2.transform(violations, VIOLATION_CONTENT_EXTRACTOR)); |
| 58 | + } |
| 59 | + |
| 60 | + public Set<ViolationContent> getViolations() { |
| 61 | + return violations; |
| 62 | + } |
| 63 | +} |
0 commit comments