com.github.fge.jsonschema.core.exceptions.ProcessingException Java Examples

The following examples show how to use com.github.fge.jsonschema.core.exceptions.ProcessingException. 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: ValidationService.java    From yaml-json-validator-maven-plugin with Apache License 2.0 6 votes vote down vote up
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: ValidationService.java    From yaml-json-validator-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void validateAgainstSchema(final JsonNode spec, final ValidationResult validationResult) {
    if (schema == null) {
        return;
    }
    try {
        final ProcessingReport report = schema.validate(spec);
        if (!report.isSuccess()) {
            validationResult.encounteredError();
        }
        for (final ProcessingMessage processingMessage : report) {
            validationResult.addMessage(processingMessage.toString());
        }
    } catch (final ProcessingException e) {
        validationResult.addMessage(e.getMessage());
        validationResult.encounteredError();
    }
}
 
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: SyntaxProcessing.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected JsonNode buildResult(final String input)
    throws IOException, ProcessingException
{
    final ObjectNode ret = FACTORY.objectNode();

    final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT,
        input);

    final JsonNode schemaNode = ret.remove(INPUT);

    if (invalidSchema)
        return ret;

    final ProcessingReport report = VALIDATOR.validateSchema(schemaNode);
    final boolean success = report.isSuccess();

    ret.put(VALID, success);
    ret.put(RESULTS, JacksonUtils.prettyPrint(buildReport(report)));
    return ret;
}
 
Example #6
Source File: OpenApiSchemaValidator.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Validates given specification Json and add validation errors and warnings to given open api info model builder.
 * @param specRoot the specification as Json root.
 * @param modelBuilder the model builder receiving all validation errors and warnings.
 */
default void validateJSonSchema(JsonNode specRoot, OpenApiModelInfo.Builder modelBuilder) {
    try {
        final ProcessingReport report = getSchema().validate(specRoot);
        final List<Violation> errors = new ArrayList<>();
        final List<Violation> warnings = new ArrayList<>();
        for (final ProcessingMessage message : report) {
            final boolean added = append(errors, message, Optional.of("error"));
            if (!added) {
                append(warnings, message, Optional.empty());
            }
        }

        modelBuilder.addAllErrors(errors);
        modelBuilder.addAllWarnings(warnings);

    } catch (ProcessingException ex) {
        LoggerFactory.getLogger(OpenApiSchemaValidator.class).error("Unable to load the schema file embedded in the artifact", ex);
        modelBuilder.addError(new Violation.Builder()
            .error("error").property("")
            .message("Unable to load the OpenAPI schema file embedded in the artifact")
            .build());
    }
}
 
Example #7
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 #8
Source File: AvroProcessing.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected JsonNode buildResult(final String input)
    throws IOException, ProcessingException
{
    final ObjectNode ret = FACTORY.objectNode();

    final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT,
        input);

    final JsonNode schemaNode = ret.remove(INPUT);

    if (invalidSchema)
        return ret;

    final JsonTree tree = new SimpleJsonTree(schemaNode);
    final ValueHolder<JsonTree> holder = ValueHolder.hold(tree);

    final ProcessingReport report = new ListProcessingReport();
    final ProcessingResult<ValueHolder<SchemaTree>> result
        = ProcessingResult.uncheckedResult(PROCESSOR, report, holder);
    final boolean success = result.isSuccess();

    final JsonNode content = success
        ? result.getResult().getValue().getBaseNode()
        : buildReport(result.getReport());

    ret.put(VALID, success);
    ret.put(RESULTS, JacksonUtils.prettyPrint(content));
    return ret;
}
 
Example #9
Source File: OpenAPISchemaValidator.java    From microcks with Apache License 2.0 5 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 OpenAPI 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 OpenAPI 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 !
 */
public static List<String> validateJson(JsonNode schemaNode, JsonNode jsonNode) {
   schemaNode = convertOpenAPISchemaToJsonSchema(schemaNode);

   try {
      return JsonSchemaValidator.validateJson(schemaNode, jsonNode);
   } catch (ProcessingException e) {
      log.debug("Got a ProcessingException while trying to interpret schemaNode as a real schema");
      List<String> errors = new ArrayList<>();
      errors.add("schemaNode does not seem to represent a valid OpenAPI schema");
      return errors;
   }
}
 
Example #10
Source File: JsonSchemaValidator.java    From microcks with Apache License 2.0 5 votes vote down vote up
/** */
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 #11
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 #12
Source File: JsonSchemaValidator.java    From microcks with Apache License 2.0 5 votes vote down vote up
/**
 * Check if a Json object is valid against the given Json schema specification.
 * @param schemaText The Json schema specification as a string
 * @param jsonText The Json object as a string
 * @return True if Json object is valid, false otherwise
 * @throws IOException if json string representations cannot be parsed
 */
public static boolean isJsonValid(String schemaText, String jsonText) throws IOException {
   try {
      List<String> errors = validateJson(schemaText, jsonText);
      if (!errors.isEmpty()) {
         log.debug("Get validation errors, returning false");
         return false;
      }
   } catch (ProcessingException pe) {
      log.debug("Got processing exception while extracting schema, returning false");
      return false;
   }
   return true;
}
 
Example #13
Source File: JsonSchemaValidator.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
private Set<JsonNode> doValidate(JsonSchema schema, JsonNode instance) {
    Set<JsonNode> errors = new HashSet<>();
    try {
        schema.validate(instance, true).forEach(message -> {
            errors.add(message.asJson());
        });
    } catch (ProcessingException e) {
        Activator.getDefault().logError(e.getMessage(), e);
    }
    return errors;
}
 
Example #14
Source File: JsonSchemaValidator.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
public Set<JsonNode> validate(JsonNode instance, String schemaPointer) {
    JsonSchema jsonSchema = null;
    try {
        jsonSchema = factory.getJsonSchema(schema, schemaPointer);
    } catch (ProcessingException e) {
        Activator.getDefault().logError(e.getLocalizedMessage(), e);
        return null;
    }

    return doValidate(jsonSchema, instance);
}
 
Example #15
Source File: JsonSchemaValidator.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
public Set<JsonNode> validate(JsonNode instance) {
    JsonSchema jsonSchema = null;
    try {
        jsonSchema = factory.getJsonSchema(schema);
    } catch (ProcessingException e) {
        Activator.getDefault().logError(e.getLocalizedMessage(), e);
        return null;
    }

    return doValidate(jsonSchema, instance);
}
 
Example #16
Source File: SchemaValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: Schema2PojoProcessing.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected JsonNode buildResult(final String input)
    throws IOException, ProcessingException
{
    final ObjectNode ret = FACTORY.objectNode();

    final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT,
        input);

    final JsonNode schemaNode = ret.remove(INPUT);

    if (invalidSchema)
        return ret;

    final SchemaTree tree
        = new CanonicalSchemaTree(SchemaKey.anonymousKey(), schemaNode);
    final ValueHolder<SchemaTree> holder = ValueHolder.hold("schema", tree);

    final ProcessingReport report = new ListProcessingReport();
    final ProcessingResult<ValueHolder<String>> result
        = ProcessingResult.uncheckedResult(PROCESSOR, report, holder);

    final boolean  success = result.isSuccess();
    ret.put(VALID, success);

    final String content = success
        ? result.getResult().getValue()
        : JacksonUtils.prettyPrint(buildReport(result.getReport()));

    ret.put(RESULTS, content);
    return ret;
}
 
Example #18
Source File: JsonParser.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@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 #19
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 #20
Source File: GenerateConnectorInspectionsMojo.java    From syndesis with Apache License 2.0 5 votes vote down vote up
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 #21
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 #22
Source File: OpenApiSchemaValidator.java    From syndesis with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: JSONValidator.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
public ProcessingReport validate(JsonNode node, String schema) {
    JsonSchema jsonSchema;
    try {
        jsonSchema = getJsonSchemaFactory().getJsonSchema(schema);
    } catch (ProcessingException ex) {
        throw new IllegalArgumentException("Unknown schema: " + schema, ex);
    }
    return jsonSchema.validateUnchecked(node);
}
 
Example #24
Source File: BaseComponentDescriptorService.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: AbstractSchemaValidatorTest.java    From elucidate-server with MIT License 5 votes vote down vote up
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 #26
Source File: JsonSchemaAssertions.java    From Bastion with GNU General Public License v3.0 5 votes vote down vote up
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 #27
Source File: JsonValidator.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: AbstractMessageConverter.java    From elucidate-server with MIT License 4 votes vote down vote up
protected String validate(String jsonStr, JsonNode validationSchema) throws ProcessingException, IOException {

        JsonNode json = JsonLoader.fromString(jsonStr);

        JsonValidator jsonValidator = JsonSchemaFactory.byDefault().getValidator();
        ProcessingReport processingReport = jsonValidator.validate(validationSchema, json);
        if (!processingReport.isSuccess()) {

            ArrayNode jsonArray = JsonNodeFactory.instance.arrayNode();

            for (ProcessingMessage processingMessage : processingReport) {
                jsonArray.add(processingMessage.asJson());
            }

            return JsonUtils.toPrettyString(jsonArray);
        }

        return null;
    }
 
Example #29
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));
        }
    }
}
 
Example #30
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));
        }
    }
}