Skip to content

Instantly share code, notes, and snippets.

@amr
Created March 3, 2017 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amr/bd289ec0b14ca67e461f664dff07161e to your computer and use it in GitHub Desktop.
Save amr/bd289ec0b14ca67e461f664dff07161e to your computer and use it in GitHub Desktop.
Mapping ConstraintViolatation paths to JSON Pointer and JSON Path
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