Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 126 additions & 8 deletions BowtieJsonSchemaValidator.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.networknt.schema.AbsoluteIri;
import com.networknt.schema.Error;
import com.networknt.schema.OutputFormat;
import com.networknt.schema.Schema;
import com.networknt.schema.SchemaRegistry;
import com.networknt.schema.SpecificationVersion;
import com.networknt.schema.output.OutputUnit;
import com.networknt.schema.resource.InputStreamSource;
import com.networknt.schema.resource.ResourceLoader;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Manifest;
Expand Down Expand Up @@ -58,7 +63,7 @@ private void run(BufferedReader reader) {
reader.lines().forEach(this::handle);
}

private void handle(String data) {
void handle(String data) {
try {
JsonNode node = objectMapper.readTree(data);
String cmd = node.get("cmd").asString();
Expand Down Expand Up @@ -123,6 +128,19 @@ private void run(JsonNode node) {
throw new IllegalArgumentException("Not started!");
}
RunRequest runRequest = objectMapper.treeToValue(node, RunRequest.class);
String outputFormat =
runRequest.output() == null ? "flag" : runRequest.output();
boolean isAnnotations;
switch (outputFormat) {
case "flag" -> isAnnotations = false;
case "annotations" -> isAnnotations = true;
default -> {
output.println(objectMapper.writeValueAsString(new RunSkippedResponse(
runRequest.seq(), true,
"Unsupported output format: " + outputFormat)));
return;
}
}
try {
SchemaRegistry schemaRegistry = SchemaRegistry.withDefaultDialect(
versionFlag,
Expand All @@ -148,9 +166,22 @@ private void run(JsonNode node) {
.map(test -> {
Schema jsonSchema =
schemaRegistry.getSchema(runRequest.testCase().schema());
List<Error> errors = jsonSchema.validate(test.instance());
boolean isValid = errors == null || errors.isEmpty();
return new TestResult(isValid);
if (isAnnotations) {
OutputUnit outputUnit = jsonSchema.validate(
test.instance(), OutputFormat.LIST, executionContext -> {
executionContext.executionConfig(config -> {
config.annotationCollectionEnabled(true);
config.annotationCollectionFilter(keyword -> true);
});
});
List<Map<String, Object>> annotations = new ArrayList<>();
extractAnnotations(outputUnit, annotations);
return new TestResult(outputUnit.isValid(), annotations);
} else {
List<Error> errors = jsonSchema.validate(test.instance());
boolean isValid = errors == null || errors.isEmpty();
return new TestResult(isValid);
}
})
.toList();
output.println(objectMapper.writeValueAsString(
Expand All @@ -172,6 +203,84 @@ private String stackTraceToString(Exception e) {
return stringWriter.toString();
}

static String percentEncodeFragmentToken(String token) {
byte[] bytes = token.getBytes(StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder(bytes.length);
for (byte b : bytes) {
int c = b & 0xFF;
if (isFragmentTokenChar(c)) {
sb.append((char) c);
} else {
sb.append('%');
sb.append(Character.toUpperCase(Character.forDigit((c >>> 4) & 0xF, 16)));
sb.append(Character.toUpperCase(Character.forDigit(c & 0xF, 16)));
}
}
return sb.toString();
}

private static boolean isFragmentTokenChar(int c) {
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| c == '-' || c == '.' || c == '_' || c == '~'
|| c == '!' || c == '$' || c == '&' || c == '\''
|| c == '(' || c == ')' || c == '*' || c == '+'
|| c == ',' || c == ';' || c == '=' || c == ':'
|| c == '@' || c == '?';
}

static String appendKeywordLocation(String sloc, String keyword) {
String escapedKeyword =
percentEncodeFragmentToken(keyword.replace("~", "~0").replace("/", "~1"));
if (sloc == null || sloc.isEmpty() || "#".equals(sloc)) {
return "#/" + escapedKeyword;
}
int hashIndex = sloc.indexOf('#');
if (hashIndex < 0) {
return sloc + "#/" + escapedKeyword;
}
String base = sloc.substring(0, hashIndex);
String fragment = sloc.substring(hashIndex + 1);
if (fragment.isEmpty()) {
return base + "#/" + escapedKeyword;
}
if (!fragment.startsWith("/")) {
throw new IllegalArgumentException(
"Expected JSON Pointer fragment in schemaLocation: " + sloc);
}
StringBuilder result = new StringBuilder(base).append('#');
String[] tokens = fragment.substring(1).split("/", -1);
for (String token : tokens) {
result.append('/').append(percentEncodeFragmentToken(token));
}
return result.append('/').append(escapedKeyword).toString();
}

static void extractAnnotations(OutputUnit unit, List<Map<String, Object>> list) {
if (unit.getAnnotations() != null) {
for (Map.Entry<String, Object> entry : unit.getAnnotations().entrySet()) {
Map<String, Object> ann = new HashMap<>();
ann.put("keyword", entry.getKey());
ann.put("instanceLocation", unit.getInstanceLocation() == null ? "" : unit.getInstanceLocation());

String loc = appendKeywordLocation(unit.getSchemaLocation(), entry.getKey());
if (loc.startsWith("#")) {
ann.put("keywordLocation", loc);
} else {
ann.put("absoluteKeywordLocation", loc);
}
ann.put("annotation", entry.getValue());
list.add(ann);
}
}
if (unit.getDetails() != null) {
for (OutputUnit child : unit.getDetails()) {
extractAnnotations(child, list);
}
}
}

class CustomResourceLoader implements ResourceLoader {

private final Map<String, JsonNode> registry;
Expand Down Expand Up @@ -211,12 +320,18 @@ record DialectRequest(String dialect) {}

record DialectResponse(boolean ok) {}

record RunRequest(JsonNode seq, @JsonProperty("case") TestCase testCase) {}
record RunRequest(JsonNode seq, @JsonProperty("case") TestCase testCase,
String output) {}

record RunResponse(JsonNode seq, List<TestResult> results) {}

record RunSkippedResponse(JsonNode seq, boolean skipped, String message,
String issue_url) {}
record RunSkippedResponse(
JsonNode seq, boolean skipped, String message,
@JsonInclude(JsonInclude.Include.NON_NULL) String issue_url) {
RunSkippedResponse(JsonNode seq, boolean skipped, String message) {
this(seq, skipped, message, null);
}
}

record RunErroredResponse(JsonNode seq, boolean errored, ErrorContext context) {
}
Expand All @@ -238,4 +353,7 @@ record TestCase(String description, String comment, JsonNode schema,
Test(String description, String comment, JsonNode instance, boolean valid) {
}

record TestResult(boolean valid) {}
record TestResult(boolean valid, @JsonInclude(JsonInclude.Include.NON_NULL)
List<Map<String, Object>> annotations) {
public TestResult(boolean valid) { this(valid, null); }
}
Loading