com.github.fge.jsonschema.main.JsonSchemaFactory Java Examples
The following examples show how to use
com.github.fge.jsonschema.main.JsonSchemaFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidationService.java From yaml-json-validator-maven-plugin with Apache License 2.0 | 6 votes |
private JsonSchema getJsonSchema(final InputStream schemaFile) { if (schemaFile == null) { return null; } JsonSchema jsonSchema; try { // using INLINE dereferencing to avoid internet access while validating LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder().addScheme("classpath", new ClasspathDownloader()) .dereferencing(Dereferencing.INLINE).freeze(); final JsonSchemaFactory factory = JsonSchemaFactory.newBuilder() .setLoadingConfiguration(loadingConfiguration).freeze(); final JsonNode schemaObject = jsonMapper.readTree(schemaFile); jsonSchema = factory.getJsonSchema(schemaObject); } catch (IOException | ProcessingException e) { throw new RuntimeException(e); } return jsonSchema; }
Example #2
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
private JsonSchema resolveJsonSchema(String schemaAsString, boolean removeId) throws Exception { JsonNode schemaObject = JsonMapper.readTree(schemaAsString); if (removeId) { ObjectNode oNode = (ObjectNode) schemaObject; if (oNode.get("id") != null) { oNode.remove("id"); } if (oNode.get("$schema") != null) { oNode.remove("$schema"); } if (oNode.get("description") != null) { oNode.remove("description"); } } JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); return factory.getJsonSchema(schemaObject); }
Example #3
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 6 votes |
@Test public void upgradePublicModelExtensionTest() throws ProcessingException, IOException { String syndesisExtensionSchema = "/syndesis/syndesis-extension-definition-schema.json"; JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("resource:" + syndesisExtensionSchema); ExtensionConverter converter = new DefaultExtensionConverter(); Extension extension = new Extension.Builder() .extensionId("my-extension") .name("Name") .description("Description") .version("1.0.0") .schemaVersion("old-V0.1") .extensionType(Extension.Type.Steps) .build(); JsonNode tree = converter.toPublicExtension(extension); ProcessingReport report = schema.validate(tree); assertFalse(report.toString(), report.iterator().hasNext()); Extension extensionClone = converter.toInternalExtension(tree); assertNotEquals(extensionClone, extension); assertEquals(ExtensionConverter.getCurrentSchemaVersion(), extensionClone.getSchemaVersion()); }
Example #4
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 6 votes |
@Test public void addSchemaVersionInPublicModelExtensionTest() throws ProcessingException, IOException { String syndesisExtensionSchema = "/syndesis/syndesis-extension-definition-schema.json"; JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("resource:" + syndesisExtensionSchema); ExtensionConverter converter = new DefaultExtensionConverter(); ObjectNode tree = OBJECT_MAPPER.createObjectNode() .put("extensionId", "my-extension") .put("name", "Name") .put("description", "Description") .put("version", "1.0.0"); ProcessingReport report = schema.validate(tree); assertFalse(report.toString(), report.iterator().hasNext()); Extension extension = converter.toInternalExtension(tree); assertEquals(ExtensionConverter.getCurrentSchemaVersion(), extension.getSchemaVersion()); }
Example #5
Source File: SchemaValidator.java From swagger-inflector with Apache License 2.0 | 6 votes |
public static boolean validate(Object argument, String schema, Direction direction) { try { JsonNode schemaObject = Json.mapper().readTree(schema); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonNode content = Json.mapper().convertValue(argument, JsonNode.class); com.github.fge.jsonschema.main.JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); ProcessingReport report = jsonSchema.validate(content); if(!report.isSuccess()) { if(direction.equals(Direction.INPUT)) { LOGGER.warn("input: " + content.toString() + "\n" + "does not match schema: \n" + schema); } else { LOGGER.warn("response: " + content.toString() + "\n" + "does not match schema: \n" + schema); } } return report.isSuccess(); } catch (Exception e) { LOGGER.error("can't validate model against schema", e); } return true; }
Example #6
Source File: JsonSchemaValidationTest.java From microprofile-health with Apache License 2.0 | 6 votes |
/** * Verifies that the JSON object returned by the implementation is following the * JSON schema defined by the specification */ @Test @RunAsClient public void testPayloadJsonVerifiesWithTheSpecificationSchema() throws Exception { Response response = getUrlHealthContents(); Assert.assertEquals(response.getStatus(), 200); JsonObject json = readJson(response); ObjectMapper mapper = new ObjectMapper(); JsonNode schemaJson = mapper.readTree(Thread.currentThread() .getContextClassLoader().getResourceAsStream("health-check-schema.json")); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(schemaJson); ProcessingReport report = schema.validate(toJsonNode(json)); Assert.assertTrue(report.isSuccess(), "Returned Health JSON does not validate against the specification schema"); }
Example #7
Source File: SchemaValidationTest.java From swagger-inflector with Apache License 2.0 | 6 votes |
@Test public void testValidation() throws Exception { String schemaAsString = "{\n" + " \"properties\": {\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"format\": \"int64\"\n" + " }\n" + " }\n" + "}"; JsonNode schemaObject = Json.mapper().readTree(schemaAsString); JsonNode content = Json.mapper().readValue("{\n" + " \"id\": 123\n" + "}", JsonNode.class); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); com.github.fge.jsonschema.main.JsonSchema schema = factory.getJsonSchema(schemaObject); ProcessingReport report = schema.validate(content); assertTrue(report.isSuccess()); }
Example #8
Source File: JsonSchemaValidator.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
public JsonSchemaValidator(JsonNode schema, Map<String, JsonNode> preloadSchemas) { this.schema = schema; this.loadingConfiguration = getLoadingConfiguration(preloadSchemas); this.factory = JsonSchemaFactory.newBuilder() // .setLoadingConfiguration(loadingConfiguration) // .freeze(); }
Example #9
Source File: JsonSchemaAssertions.java From Bastion with GNU General Public License v3.0 | 5 votes |
private void assertResponseConformsToSchema(JsonNode response) throws ProcessingException, IOException { ProcessingReport validationReport = JsonSchemaFactory.byDefault() .getJsonSchema(getExpectedSchema()).validate(response); if (!validationReport.isSuccess()) { String messages = StreamSupport.stream(validationReport.spliterator(), false) .map(ProcessingMessage::getMessage) .collect(Collectors.joining(", ")); Assert.fail(String.format("Actual response body is not as specified. The following message(s) where produced during validation; %s.", messages)); } }
Example #10
Source File: JsonValidator.java From Poseidon with Apache License 2.0 | 5 votes |
private void validate(String schemaPath, String filePath) throws IOException, ProcessingException { JsonNode schema = JsonLoader.fromResource(schemaPath); JsonNode json = JsonLoader.fromPath(filePath); com.github.fge.jsonschema.main.JsonValidator validator = JsonSchemaFactory.byDefault().getValidator(); ProcessingReport report = validator.validate(schema, json); if ((report == null) || !report.isSuccess()) { logger.error("Invalid JSON"); if (report != null) { throw new ProcessingException(report.toString()); } else { throw new ProcessingException("JSON validation report is null for " + filePath); } } }
Example #11
Source File: JsonParser.java From attic-apex-malhar with Apache License 2.0 | 5 votes |
@Override public void setup(OperatorContext context) { try { if (jsonSchema != null) { JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonNode schemaNode = JsonLoader.fromString(jsonSchema); schema = factory.getJsonSchema(schemaNode); } objMapper = new ObjectMapper(); objMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } catch (ProcessingException | IOException e) { DTThrowable.wrapIfChecked(e); } }
Example #12
Source File: SchemaValidator.java From swagger-inflector with Apache License 2.0 | 5 votes |
public static com.github.fge.jsonschema.main.JsonSchema getValidationSchema(String schema) throws IOException, ProcessingException { schema = schema.trim(); JsonSchema output = SCHEMA_CACHE.get(schema); if(output == null) { JsonNode schemaObject = Json.mapper().readTree(schema); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); com.github.fge.jsonschema.main.JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); SCHEMA_CACHE.put(schema, jsonSchema); output = jsonSchema; } return output; }
Example #13
Source File: AbstractSchemaValidatorTest.java From elucidate-server with MIT License | 5 votes |
protected void validateJson(String jsonFileName) throws IOException, ProcessingException, JsonLdError { JsonNode schema = getSchema(); assertNotNull(schema); String jsonStr = getJson(jsonFileName); assertNotNull(jsonStr); Object jsonObj = JsonUtils.fromString(jsonStr); List<Object> expandedJson = JsonLdProcessor.expand(jsonObj); jsonStr = JsonUtils.toString(expandedJson); JsonNode json = JsonLoader.fromString(jsonStr); JsonValidator jsonValidator = JsonSchemaFactory.byDefault().getValidator(); ProcessingReport processingReport = jsonValidator.validate(schema, json); assertNotNull(processingReport); if (!processingReport.isSuccess()) { ArrayNode jsonArray = JsonNodeFactory.instance.arrayNode(); assertNotNull(jsonArray); Iterator<ProcessingMessage> iterator = processingReport.iterator(); while (iterator.hasNext()) { ProcessingMessage processingMessage = iterator.next(); jsonArray.add(processingMessage.asJson()); } String errorJson = JsonUtils.toPrettyString(jsonArray); assertNotNull(errorJson); fail(errorJson); } }
Example #14
Source File: JsonSchemaValidator.java From microcks with Apache License 2.0 | 5 votes |
/** */ private static JsonSchema extractJsonSchemaNode(JsonNode jsonNode) throws ProcessingException { final JsonNode schemaIdentifier = jsonNode.get(JSON_SCHEMA_IDENTIFIER_ELEMENT); if (schemaIdentifier == null){ ((ObjectNode) jsonNode).put(JSON_SCHEMA_IDENTIFIER_ELEMENT, JSON_V4_SCHEMA_IDENTIFIER); } final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); return factory.getJsonSchema(jsonNode); }
Example #15
Source File: CEFParserTest.java From metron with Apache License 2.0 | 5 votes |
protected boolean validateJsonData(final String jsonSchema, final String jsonData) throws Exception { final JsonNode d = JsonLoader.fromString(jsonData); final JsonNode s = JsonLoader.fromString(jsonSchema); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonValidator v = factory.getValidator(); ProcessingReport report = v.validate(s, d); return report.toString().contains("success"); }
Example #16
Source File: LEEFParserTest.java From metron with Apache License 2.0 | 5 votes |
protected boolean validateJsonData(final String jsonSchema, final String jsonData) throws Exception { final JsonNode d = JsonLoader.fromString(jsonData); final JsonNode s = JsonLoader.fromString(jsonSchema); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonValidator v = factory.getValidator(); ProcessingReport report = v.validate(s, d); return report.toString().contains("success"); }
Example #17
Source File: JsonSchemaValidator.java From raml-tester with Apache License 2.0 | 5 votes |
private synchronized void init() { if (loader != null && factory == null) { final LoadingConfigurationBuilder loadingConfig = LoadingConfiguration.newBuilder(); final String simpleName = loader.getClass().getSimpleName(); loadingConfig.addScheme(simpleName, new LoaderUriDownloader(loader)); loadingConfig.setURITranslatorConfiguration(URITranslatorConfiguration.newBuilder().setNamespace(simpleName + ":///").freeze()); factory = JsonSchemaFactory.newBuilder().setLoadingConfiguration(loadingConfig.freeze()).freeze(); } }
Example #18
Source File: RestAssuredIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory .newBuilder() .setValidationConfiguration( ValidationConfiguration.newBuilder() .setDefaultVersion(SchemaVersion.DRAFTV4) .freeze()).freeze(); get("/events?id=390") .then() .assertThat() .body(matchesJsonSchemaInClasspath("event_0.json").using( jsonSchemaFactory)); }
Example #19
Source File: OpenApiSchemaValidator.java From syndesis with Apache License 2.0 | 5 votes |
static JsonSchema loadSchema(final String path, final String uri) { try { final JsonNode oas30Schema = JsonUtils.reader().readTree(Resources.getResourceAsText(path)); final LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder() .preloadSchema(oas30Schema) .freeze(); return JsonSchemaFactory.newBuilder().setLoadingConfiguration(loadingConfiguration).freeze().getJsonSchema(uri); } catch (final ProcessingException | IOException ex) { throw new IllegalStateException("Unable to load the schema file embedded in the artifact", ex); } }
Example #20
Source File: JsonSchemaUtils.java From TestHub with MIT License | 5 votes |
/** * 将需要验证的JsonNode 与 JsonSchema标准对象 进行比较 * * @param schema schema标准对象 * @param data 需要比对的Schema对象 */ private static void assertJsonSchema(JsonNode schema, JsonNode data) { ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schema, data); if (!report.isSuccess()) { for (ProcessingMessage aReport : report) { Reporter.log(aReport.getMessage(), true); } } Assert.assertTrue(report.isSuccess()); }
Example #21
Source File: YamlParser.java From elasticsearch-migration with Apache License 2.0 | 5 votes |
private JsonSchema createJsonSchema() { final LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder() .dereferencing(Dereferencing.INLINE).freeze(); final JsonSchemaFactory factory = JsonSchemaFactory.newBuilder() .setLoadingConfiguration(loadingConfiguration).freeze(); try { final JsonNode schemaObject = jsonMapper.readTree(MIGRATION_SCHEMA); return factory.getJsonSchema(schemaObject); } catch (Exception e) { throw new IllegalStateException("Couldn't parse yaml schema", e); } }
Example #22
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void validateStepExtensionTest() throws ProcessingException, IOException { String syndesisExtensionSchema = "/syndesis/syndesis-extension-definition-schema.json"; JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("resource:" + syndesisExtensionSchema); ExtensionConverter converter = new DefaultExtensionConverter(); Extension extension = new Extension.Builder() .extensionId("my-extension") .name("Name") .description("Description") .version("1.0.0") .schemaVersion(ExtensionConverter.getCurrentSchemaVersion()) .addAction(new StepAction.Builder() .id("action-1") .name("action-1-name") .description("Action 1 Description") .pattern(Action.Pattern.From) .descriptor(new StepDescriptor.Builder() .entrypoint("direct:hello") .kind(StepAction.Kind.ENDPOINT) .build()) .build()) .build(); JsonNode tree = converter.toPublicExtension(extension); ProcessingReport report = schema.validate(tree); assertFalse(report.toString(), report.iterator().hasNext()); Extension extensionClone = converter.toInternalExtension(tree); assertEquals(extensionClone, extension); }
Example #23
Source File: GenerateConnectorInspectionsMojo.java From syndesis with Apache License 2.0 | 5 votes |
private void initJsonSchema() throws MojoExecutionException { if (jsonSchema != null) { return; // already initialised } InputStream schemaStream = null; try { schemaStream = getClass().getResourceAsStream("/" + CONNECTOR_SCHEMA_FILE); if (schemaStream == null) { throw new IOException("Schema Initialisation Error: file not available"); } LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder() .dereferencing(Dereferencing.INLINE).freeze(); JsonSchemaFactory factory = JsonSchemaFactory.newBuilder() .setLoadingConfiguration(loadingConfiguration).freeze(); JsonNode schemaObject = JsonUtils.reader().readTree(schemaStream); jsonSchema = factory.getJsonSchema(schemaObject); } catch (IOException | ProcessingException ex) { throw new MojoExecutionException("Schema Initialisation Error", ex); } finally { if (schemaStream != null) { try { schemaStream.close(); } catch (IOException e) { getLog().error(e); } } } }
Example #24
Source File: ODataSerializerTest.java From syndesis with Apache License 2.0 | 5 votes |
private static void validateResultAgainstSchema(JsonNode jsonResultNode, JsonNode schemaNode) throws ProcessingException { String schemaURI = "http://json-schema.org/schema#"; LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder() .preloadSchema(schemaURI, schemaNode) .freeze(); JsonSchema jsonSchema = JsonSchemaFactory.newBuilder() .setLoadingConfiguration(loadingConfiguration) .freeze() .getJsonSchema(schemaURI); ProcessingReport report = jsonSchema.validate(jsonResultNode); assertTrue(report.isSuccess()); }
Example #25
Source File: MultiOpenApiParser.java From api-compiler with Apache License 2.0 | 5 votes |
/** * Validates the input Swagger JsonNode against Swagger Specification schema. * * @throws OpenApiConversionException */ private static void validateSwaggerSpec(JsonNode swaggerJsonNode) throws OpenApiConversionException { ProcessingReport report = null; try { URL url = Resources.getResource(SCHEMA_RESOURCE_PATH); String swaggerSchema = Resources.toString(url, StandardCharsets.UTF_8); JsonNode schemaNode = Yaml.mapper().readTree(swaggerSchema); JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode); report = schema.validate(swaggerJsonNode); } catch (Exception ex) { throw new OpenApiConversionException("Unable to parse the content. " + ex.getMessage(), ex); } if (!report.isSuccess()) { String message = ""; Iterator itr = report.iterator(); if (itr.hasNext()) { message += ((ProcessingMessage) itr.next()).toString(); } while(itr.hasNext()) { message += "," + ((ProcessingMessage) itr.next()).toString(); } throw new OpenApiConversionException( String.format("Invalid OpenAPI file. Please fix the schema errors:\n%s", message)); } }
Example #26
Source File: SchemaUtils.java From karate with MIT License | 5 votes |
public static boolean isValid(String json, String schema) throws Exception { JsonNode schemaNode = JsonLoader.fromString(schema); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonSchema jsonSchema = factory.getJsonSchema(schemaNode); JsonNode jsonNode = JsonLoader.fromString(json); ProcessingReport report = jsonSchema.validate(jsonNode); logger.debug("report: {}", report); return report.isSuccess(); }
Example #27
Source File: JsonSchemaFromFieldDescriptorsGeneratorTest.java From restdocs-raml with MIT License | 5 votes |
@SneakyThrows private void thenSchemaIsValid() { final ProcessingReport report = JsonSchemaFactory.byDefault() .getSyntaxValidator() .validateSchema(JsonLoader.fromString(schemaString)); then(report.isSuccess()).describedAs("schema invalid - validation failures: %s", report).isTrue(); }
Example #28
Source File: BaseComponentDescriptorService.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public boolean validate(ComponentDescriptor component, JsonNode configuration) { JsonValidator validator = JsonSchemaFactory.byDefault().getValidator(); try { if (!component.getConfigurationDescriptor().has("schema")) { throw new DataValidationException("Configuration descriptor doesn't contain schema property!"); } JsonNode configurationSchema = component.getConfigurationDescriptor().get("schema"); ProcessingReport report = validator.validate(configurationSchema, configuration); return report.isSuccess(); } catch (ProcessingException e) { throw new IncorrectParameterException(e.getMessage(), e); } }
Example #29
Source File: DataExportRecipeValidator.java From TomboloDigitalConnector with MIT License | 5 votes |
public static ProcessingReport validate(Reader jsonFile) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); JsonNode node = JsonLoader.fromURL(loader.getResource("data_export_specification_schema.json")); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true); return factory.getJsonSchema(node).validate(mapper.readTree(jsonFile)); } catch (Exception e) { throw new Error("Validator JSON Schema is invalid", e); } }
Example #30
Source File: BenderConfig.java From bender with Apache License 2.0 | 5 votes |
public static boolean validate(String data, ObjectMapper objectMapper, BenderSchema benderSchema) throws ConfigurationException { ProcessingReport report; try { /* * Create object */ JsonNode node = objectMapper.readTree(data); /* * Create JSON schema */ JsonNode jsonSchema = benderSchema.getSchema(); /* * Validate */ final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(jsonSchema); report = schema.validate(node); } catch (IOException | ProcessingException ioe) { throw new ConfigurationException("unable to validate config", ioe); } if (report.isSuccess()) { return true; } else { throw new ConfigurationException("invalid config file", report.iterator().next().asException()); } }