Java Code Examples for com.github.fge.jsonschema.main.JsonSchema#validate()

The following examples show how to use com.github.fge.jsonschema.main.JsonSchema#validate() . 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: ExtensionSchemaValidationTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: ExtensionSchemaValidationTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: JsonSchemaValidationTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: JsonSchemaValidator.java    From microcks with Apache License 2.0 6 votes vote down vote up
/**
 * Validate a Json object representing by its text against a schema object representing byt its
 * text too. Validation is a deep one: its pursue checking children nodes on a failed parent. Validation
 * is respectful of Json schema spec semantics regarding additional or unknown attributes: schema must
 * explicitely set <code>additionalProperties</code> to false if you want to consider unknown attributes
 * as validation errors. It returns a list of validation error messages.
 * @param schemaNode The Json schema specification as a Jackson node
 * @param jsonNode The Json object as a Jackson node
 * @return The list of validation failures. If empty, json object is valid !
 * @throws ProcessingException if json node does not represent valid Schema
 */
public static List<String> validateJson(JsonNode schemaNode, JsonNode jsonNode) throws ProcessingException {
   List<String> errors = new ArrayList<>();

   final JsonSchema jsonSchemaNode = extractJsonSchemaNode(schemaNode);

   // Ask for a deep check to get a full error report.
   ProcessingReport report = jsonSchemaNode.validate(jsonNode, true);
   if (!report.isSuccess()) {
      for (ProcessingMessage processingMessage : report) {
         errors.add(processingMessage.getMessage());
      }
   }

   return errors;
}
 
Example 5
Source File: ExtensionSchemaValidationTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: ODataSerializerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
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 7
Source File: SchemaUtils.java    From karate with MIT License 5 votes vote down vote up
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 8
Source File: BenderConfig.java    From bender with Apache License 2.0 5 votes vote down vote up
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 9
Source File: MultiOpenApiParser.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * 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 10
Source File: TestMetrics4BearsJsonFile.java    From repairnator with MIT License 4 votes vote down vote up
@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 11
Source File: TestMetrics4BearsJsonFile.java    From repairnator with MIT License 4 votes vote down vote up
@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));
        }
    }
}