• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.networknt.schema;
2 import com.fasterxml.jackson.databind.JsonNode;
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import com.networknt.schema.resource.InputStreamSource;
5 import com.networknt.schema.resource.SchemaLoader;
6 
7 import org.junit.jupiter.api.Test;
8 
9 import java.io.ByteArrayInputStream;
10 import java.nio.charset.StandardCharsets;
11 import java.util.Set;
12 
13 import static org.hamcrest.CoreMatchers.is;
14 import static org.hamcrest.MatcherAssert.assertThat;
15 
16 public class CustomUriTest {
17     @Test
customUri()18     public void customUri() throws Exception {
19         /* Given */
20         final JsonSchemaFactory factory = buildJsonSchemaFactory();
21         final JsonSchema schema = factory.getSchema(
22                 "{\"$schema\": \"https://json-schema.org/draft/2019-09/schema\",\"type\": \"object\",\"additionalProperties\": false,\"properties\": {\"customAnyOf\": {\"anyOf\": [{\"type\": \"null\"},{\"$ref\": \"custom:date\"}]},\"customOneOf\": {\"oneOf\": [{\"type\": \"null\"},{\"$ref\": \"custom:date\"}]}}}");
23         final ObjectMapper mapper = new ObjectMapper();
24         final JsonNode value = mapper.readTree("{\"customAnyOf\": null,\"customOneOf\": null}");
25 
26         /* When */
27         final Set<ValidationMessage> errors = schema.validate(value);
28 
29         /* Then */
30         assertThat(errors.isEmpty(), is(true));
31     }
32 
buildJsonSchemaFactory()33     private JsonSchemaFactory buildJsonSchemaFactory() {
34         return JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909))
35                 .schemaLoaders(schemaLoaders -> schemaLoaders.add(new CustomUriFetcher())).build();
36     }
37 
38     private static class CustomUriFetcher implements SchemaLoader {
39         private static final String SCHEMA = "{\"$schema\": \"https://json-schema.org/draft/2019-09/schema\",\"$id\":\"custom:date\",\"type\":\"string\",\"format\":\"date\"}";
40 
41         @Override
getSchema(AbsoluteIri absoluteIri)42         public InputStreamSource getSchema(AbsoluteIri absoluteIri) {
43             return () -> new ByteArrayInputStream(SCHEMA.getBytes(StandardCharsets.UTF_8));
44         }
45     }
46 }
47