Created
March 3, 2017 10:05
-
-
Save amr/bd289ec0b14ca67e461f664dff07161e to your computer and use it in GitHub Desktop.
Mapping ConstraintViolatation paths to JSON Pointer and JSON Path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.core.JsonPointer; | |
import javax.validation.ElementKind; | |
import javax.validation.Path; | |
import javax.validation.Path.Node; | |
import java.util.stream.Stream; | |
import java.util.stream.StreamSupport; | |
/** | |
* This has not been extensively tested. It's just a starting point. Please improve! | |
*/ | |
public class ConstraintViolationPathUtils { | |
public static String toJsonPointer(Path path) { | |
return StreamSupport.stream(path.spliterator(), false) | |
.filter(p -> p.getKind().equals(ElementKind.BEAN) || p.getKind().equals(ElementKind.PROPERTY)) | |
// If this is an element in an iterable, we want represent it by 2 path segments, the index | |
// then the element name | |
.flatMap(n -> n.isInIterable() ? Stream.of(n.getIndex(), n.getName()) : Stream.of(n.getName())) | |
.map(n -> JsonPointer.compile("/" + n)) | |
.reduce(JsonPointer.compile("/"), JsonPointer::append) | |
.toString(); | |
} | |
public static String toJsonPath(Path path) { | |
return StreamSupport.stream(path.spliterator(), false) | |
.filter(p -> p.getKind().equals(ElementKind.BEAN) || p.getKind().equals(ElementKind.PROPERTY)) | |
.map(Node::toString) | |
.reduce("$", (s1, s2) -> s1 + "." + s2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment