package de.zalando.toga.validator; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import static com.github.fge.jackson.JsonLoader.fromFile; import static com.github.fge.jackson.JsonLoader.fromString; public class SchemaValidator { private JsonSchema schema; public void loadSchema(File schemaLocation) { try { JsonNode schemaNode = fromFile(schemaLocation); schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode); } catch (IOException | ProcessingException e) { throw new RuntimeException("Error loading schema", e); } } public ProcessingReport validate(String input) { if (schema == null) { throw new IllegalStateException("Tried to validate without schema."); } try { final JsonNode dataNode = fromString(input); return schema.validate(dataNode); } catch (IOException | ProcessingException e) { throw new RuntimeException("Exception while validating.", e); } } }