Java Code Examples for com.github.fge.jsonschema.main.JsonSchemaFactory#getJsonSchema()
The following examples show how to use
com.github.fge.jsonschema.main.JsonSchemaFactory#getJsonSchema() .
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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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()); } }
Example 10
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 11
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 12
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 13
Source File: TestMetrics4BearsJsonFile.java From repairnator with MIT License | 4 votes |
@Ignore @Test public void testBearsJsonFileWithPassingPassingBuilds() throws IOException, ProcessingException { long buggyBuildCandidateId = 386337343; // https://travis-ci.org/fermadeiral/test-repairnator-bears/builds/386337343 long patchedBuildCandidateId = 386348522; // https://travis-ci.org/fermadeiral/test-repairnator-bears/builds/386348522 tmpDir = Files.createTempDirectory("test_bears_json_file_passing_passing_builds").toFile(); Build buggyBuildCandidate = this.checkBuildAndReturn(buggyBuildCandidateId, false); Build patchedBuildCandidate = this.checkBuildAndReturn(patchedBuildCandidateId, false); BuildToBeInspected buildToBeInspected = new BuildToBeInspected(buggyBuildCandidate, patchedBuildCandidate, ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES, "test"); RepairnatorConfig config = RepairnatorConfig.getInstance(); config.setLauncherMode(LauncherMode.BEARS); ProjectInspector4Bears inspector = (ProjectInspector4Bears)InspectorFactory.getBearsInspector(buildToBeInspected, tmpDir.getAbsolutePath(), null); inspector.run(); // check bears.json against schema ObjectMapper jsonMapper = new ObjectMapper(); String workingDir = System.getProperty("user.dir"); workingDir = workingDir.substring(0, workingDir.lastIndexOf("repairnator/")); String jsonSchemaFilePath = workingDir + "resources/bears-schema.json"; File jsonSchemaFile = new File(jsonSchemaFilePath); JsonNode schemaObject = jsonMapper.readTree(jsonSchemaFile); LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder().dereferencing(Dereferencing.INLINE).freeze(); JsonSchemaFactory factory = JsonSchemaFactory.newBuilder().setLoadingConfiguration(loadingConfiguration).freeze(); JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); JsonNode bearsJsonFile = jsonMapper.readTree(new File(inspector.getRepoToPushLocalPath() + "/bears.json")); ProcessingReport report = jsonSchema.validate(bearsJsonFile); String message = ""; for (ProcessingMessage processingMessage : report) { message += processingMessage.toString()+"\n"; } assertTrue(message, report.isSuccess()); // check correctness of the properties File expectedFile = new File(TestMetrics4BearsJsonFile.class.getResource("/json-files/bears-386337343-386348522.json").getPath()); String expectedString = FileUtils.readFileToString(expectedFile, StandardCharsets.UTF_8); File actualFile = new File(inspector.getRepoToPushLocalPath() + "/bears.json"); String actualString = FileUtils.readFileToString(actualFile, StandardCharsets.UTF_8); JSONCompareResult result = JSONCompare.compareJSON(expectedString, actualString, JSONCompareMode.STRICT); assertThat(result.isMissingOnField(), is(false)); assertThat(result.isUnexpectedOnField(), is(false)); for (FieldComparisonFailure fieldComparisonFailure : result.getFieldFailures()) { String fieldComparisonFailureName = fieldComparisonFailure.getField(); if (fieldComparisonFailureName.equals("tests.failingModule") || fieldComparisonFailureName.equals("reproductionBuggyBuild.projectRootPomPath")) { String path = "fermadeiral/test-repairnator-bears/386337343"; String expected = (String) fieldComparisonFailure.getExpected(); expected = expected.substring(expected.indexOf(path), expected.length()); String actual = (String) fieldComparisonFailure.getActual(); actual = actual.substring(actual.indexOf(path), actual.length()); assertTrue("Property failing: " + fieldComparisonFailureName, actual.equals(expected)); } else { assertTrue("Property failing: " + fieldComparisonFailureName + "\nexpected: " + fieldComparisonFailure.getExpected() + "\nactual: " + fieldComparisonFailure.getActual(), this.isPropertyToBeIgnored(fieldComparisonFailureName)); } } }
Example 14
Source File: TestMetrics4BearsJsonFile.java From repairnator with MIT License | 4 votes |
@Ignore @Test public void testRepairnatorJsonFileWithFailingBuild() throws IOException, ProcessingException { long buggyBuildCandidateId = 208897371; // https://travis-ci.org/surli/failingProject/builds/208897371 tmpDir = Files.createTempDirectory("test_repairnator_json_file_failing_build").toFile(); Build buggyBuildCandidate = this.checkBuildAndReturn(buggyBuildCandidateId, false); BuildToBeInspected buildToBeInspected = new BuildToBeInspected(buggyBuildCandidate, null, ScannedBuildStatus.ONLY_FAIL, "test"); RepairnatorConfig config = RepairnatorConfig.getInstance(); config.setLauncherMode(LauncherMode.REPAIR); config.setRepairTools(new HashSet<>(Arrays.asList("NopolSingleTest"))); ProjectInspector inspector = new ProjectInspector(buildToBeInspected, tmpDir.getAbsolutePath(), null, null); inspector.run(); // check repairnator.json against schema ObjectMapper jsonMapper = new ObjectMapper(); String workingDir = System.getProperty("user.dir"); workingDir = workingDir.substring(0, workingDir.lastIndexOf("repairnator/")); String jsonSchemaFilePath = workingDir + "resources/repairnator-schema.json"; File jsonSchemaFile = new File(jsonSchemaFilePath); JsonNode schemaObject = jsonMapper.readTree(jsonSchemaFile); LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder().dereferencing(Dereferencing.INLINE).freeze(); JsonSchemaFactory factory = JsonSchemaFactory.newBuilder().setLoadingConfiguration(loadingConfiguration).freeze(); JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); JsonNode repairnatorJsonFile = jsonMapper.readTree(new File(inspector.getRepoToPushLocalPath() + "/repairnator.json")); ProcessingReport report = jsonSchema.validate(repairnatorJsonFile); String message = ""; for (ProcessingMessage processingMessage : report) { message += processingMessage.toString()+"\n"; } assertTrue(message, report.isSuccess()); // check correctness of the properties File expectedFile = new File(TestMetrics4BearsJsonFile.class.getResource("/json-files/repairnator-208897371.json").getPath()); String expectedString = FileUtils.readFileToString(expectedFile, StandardCharsets.UTF_8); File actualFile = new File(inspector.getRepoToPushLocalPath() + "/repairnator.json"); String actualString = FileUtils.readFileToString(actualFile, StandardCharsets.UTF_8); JSONCompareResult result = JSONCompare.compareJSON(expectedString, actualString, JSONCompareMode.STRICT); assertThat(result.isMissingOnField(), is(false)); assertThat(result.isUnexpectedOnField(), is(false)); for (FieldComparisonFailure fieldComparisonFailure : result.getFieldFailures()) { String fieldComparisonFailureName = fieldComparisonFailure.getField(); if (fieldComparisonFailureName.equals("tests.failingModule") || fieldComparisonFailureName.equals("reproductionBuggyBuild.projectRootPomPath")) { String path = "surli/failingProject/208897371"; String expected = (String) fieldComparisonFailure.getExpected(); expected = expected.substring(expected.indexOf(path), expected.length()); String actual = (String) fieldComparisonFailure.getActual(); actual = actual.substring(actual.indexOf(path), actual.length()); assertTrue("Property failing: " + fieldComparisonFailureName, actual.equals(expected)); } else { assertTrue("Property failing: " + fieldComparisonFailureName + "\nexpected: " + fieldComparisonFailure.getExpected() + "\nactual: " + fieldComparisonFailure.getActual(), this.isPropertyToBeIgnored(fieldComparisonFailureName)); } } }