java-json-tools / json-schema-validator

A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order
http://json-schema-validator.herokuapp.com/
Other
1.62k stars 399 forks source link

Feature: schema resolver #213

Open joelstewart opened 7 years ago

joelstewart commented 7 years ago

Json Schema Validator has the URITranslatorConfiguration to map URIs to resource or other downloadable URIs, and LoadingConfiguration has a way to preload schemas.

What I want to be able to do is dynamically load schemas. I am thinking something similar to XML schemaResolvers,

The idea is to programmatically return the JsonNode for the schema, rather than the other 2 options. I am recognizing that I can dynamically create factories, so I can accomplish what I want to do without it, but it might be something to add to this project.

What is the order of resolution today, if both preload schemas and URITranslatorConfiguration are in use? If a SchemaResolverConfiguration was added, where would it fall into the order?

joelstewart commented 7 years ago

It is URI Downloader...

Using Elasticsearch as a repo of json schemas, I define the URI downloader to find docs in the schema index that contain the uri in the id field.

import com.github.fge.jsonschema.core.load.download.URIDownloader;

public class ElasticsearchSchemaDownloader implements URIDownloader {
    private static final Logger log = LoggerFactory.getLogger(ElasticsearchSchemaDownloader.class);

    private static final URIDownloader INSTANCE = new ElasticsearchSchemaDownloader();

    public static URIDownloader getInstance() {
        return INSTANCE;
    }

    @Override
    public InputStream fetch(final URI source) throws IOException {
        final String uri = source.toString();
        log.debug("fetching uri: " + uri);

        return IOUtils.toInputStream(ESService.getInstance().findSchemaByURI(uri));

    }
}

... and create factory/schema ...

        final LoadingConfiguration cfg = LoadingConfiguration.newBuilder()
                .addScheme("https", ElasticsearchSchemaDownloader.getInstance())
                .addScheme("http", ElasticsearchSchemaDownloader.getInstance()).freeze();

        final JsonSchemaFactory factory = JsonSchemaFactory.newBuilder().setLoadingConfiguration(cfg).freeze();

        final JsonSchema schema = factory.getJsonSchema(schemaURI);

        ProcessingReport report = schema.validate(document);

(looking into the idea of adding json schema validation as a plugin to elasticsearch).