Java Code Examples for com.github.fge.jsonschema.core.report.ProcessingReport

The following examples show how to use com.github.fge.jsonschema.core.report.ProcessingReport. These examples are extracted from open source projects. 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 Project: syndesis   Source File: ExtensionSchemaValidationTest.java    License: 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 Project: syndesis   Source File: ExtensionSchemaValidationTest.java    License: 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 Project: syndesis   Source File: OpenApiSchemaValidator.java    License: 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 4
/**
 * 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 5
@Test
public void testValidateWithValidBuilder() throws Exception {
    DataExportSpecificationBuilder spec = DataExportSpecificationBuilder.withGeoJsonExporter().addSubjectSpecification(
            new SubjectSpecificationBuilder("uk.gov.ons", "lsoa").setMatcher("label", "E01002766"))
            .addSubjectSpecification(
                    new SubjectSpecificationBuilder("uk.gov.ons", "localAuthority").setMatcher("label", "E08000035"))
            .addDatasourceSpecification("uk.org.tombolo.importer.ons.CensusImporter", "qs103ew", "")
            .addFieldSpecification(
                    FieldBuilder.wrapperField("attributes", Arrays.asList(
                            FieldBuilder.fractionOfTotal("percentage_under_1_years_old_label")
                                    .addDividendAttribute("uk.gov.ons", "CL_0000053_2") // number under one year old
                                    .setDivisorAttribute("uk.gov.ons", "CL_0000053_1") // total population
                    ))
            );
    ProcessingReport report = DataExportRecipeValidator.validate(new StringReader(spec.toJSONString()));
    assertTrue("Spec is valid", report.isSuccess());
}
 
Example 6
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 7
Source Project: swagger-inflector   Source File: SchemaValidator.java    License: Apache License 2.0 6 votes vote down vote up
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 8
Source Project: swagger-inflector   Source File: SchemaValidationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: microcks   Source File: JsonSchemaValidator.java    License: 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 10
@Override
protected JsonNode buildResult(final String input)
    throws IOException
{
    final ValueHolder<String> holder = ValueHolder.hold("source", input);
    final ProcessingReport report = new ListProcessingReport();
    final ProcessingResult<ValueHolder<SchemaTree>> result
        = ProcessingResult.uncheckedResult(PROCESSOR, report, holder);

    final ProcessingReport processingReport = result.getReport();

    final ObjectNode ret = FACTORY.objectNode();
    final boolean success = processingReport.isSuccess();
    ret.put(VALID, success);

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

    ret.put(RESULTS, JacksonUtils.prettyPrint(content));
    return ret;
}
 
Example 11
private static JsonNode buildResult(final String rawSchema,
    final String rawData)
    throws IOException
{
    final ObjectNode ret = JsonNodeFactory.instance.objectNode();

    final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT,
        rawSchema);
    final boolean invalidData = fillWithData(ret, INPUT2, INVALID_INPUT2,
        rawData);

    final JsonNode schemaNode = ret.remove(INPUT);
    final JsonNode data = ret.remove(INPUT2);

    if (invalidSchema || invalidData)
        return ret;

    final ProcessingReport report
        = VALIDATOR.validateUnchecked(schemaNode, data);

    final boolean success = report.isSuccess();
    ret.put(VALID, success);
    final JsonNode node = ((AsJson) report).asJson();
    ret.put(RESULTS, JacksonUtils.prettyPrint(node));
    return ret;
}
 
Example 12
@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 13
Source Project: TestHub   Source File: JsonSchemaUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 将需要验证的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 14
Source Project: syndesis   Source File: ExtensionSchemaValidationTest.java    License: 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 15
Source Project: syndesis   Source File: ODataSerializerTest.java    License: 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 16
Source Project: karate   Source File: SchemaUtils.java    License: 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 17
Source Project: arctic-sea   Source File: FieldDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
protected SweField validateWithValueAndDecode(ObjectNode json, boolean withValue)
        throws DecodingException {
    ProcessingReport report = validator.validate(json,
            withValue ? SchemaConstants.Common.FIELD_WITH_VALUE : SchemaConstants.Common.FIELD);
    if (!report.isSuccess()) {
        System.err.println(validator.encode(report, json));
        fail("Invalid generated field!");
    }
    return decoder.decode(json);
}
 
Example 18
Source Project: arctic-sea   Source File: JSONValidator.java    License: 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 19
Source Project: arctic-sea   Source File: JSONValidator.java    License: Apache License 2.0 5 votes vote down vote up
public String encode(ProcessingReport report, JsonNode instance) {
    ObjectNode objectNode = Json.nodeFactory().objectNode();
    objectNode.set(JSONConstants.INSTANCE, instance);
    ArrayNode errors = objectNode.putArray(JSONConstants.ERRORS);
    for (ProcessingMessage m : report) {
        errors.add(m.asJson());
    }
    return Json.print(objectNode);
}
 
Example 20
Source Project: arctic-sea   Source File: JSONValidator.java    License: Apache License 2.0 5 votes vote down vote up
public void validateAndThrow(JsonNode instance, String schema)
        throws DecodingException {
    ProcessingReport report = JSONValidator.getInstance().validate(instance, schema);
    if (!report.isSuccess()) {
        String message = encode(report, instance);
        LOG.info("Invalid JSON instance:\n{}", message);
        throw new JSONDecodingException(message);
    }
}
 
Example 21
Source Project: arctic-sea   Source File: ValidationMatchers.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean describeProcessingReport(ProcessingReport report, JsonNode item,
        Description mismatchDescription) throws JsonProcessingException {
    if (!report.isSuccess()) {
        ObjectNode objectNode = JacksonUtils.nodeFactory().objectNode();
        objectNode.set(JSONConstants.INSTANCE, item);
        ArrayNode errors = objectNode.putArray(JSONConstants.ERRORS);
        for (ProcessingMessage m : report) {
            errors.add(m.asJson());
        }
        mismatchDescription.appendText(JacksonUtils.prettyPrint(objectNode));
    }
    return report.isSuccess();
}
 
Example 22
@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 23
@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 24
Source Project: TomboloDigitalConnector   Source File: AbstractRunner.java    License: MIT License 5 votes vote down vote up
private void validateRecipe(String recipe, boolean isString) throws FileNotFoundException {
    ProcessingReport report = DataExportRecipeValidator.validate(!isString? new FileReader(recipe) :
            new BufferedReader(new InputStreamReader(new ByteArrayInputStream(recipe.getBytes()))));
    if (!report.isSuccess()) {
        DataExportRecipeValidator.display(report);
        System.exit(1);
    }
}
 
Example 25
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 26
public static void display(ProcessingReport report) {
    String logString = "The recipe file contains errors.\n\n";

    for (ProcessingMessage message : report) {
        logString += message.getMessage() + "\n";
        logString += message.toString() + "\n\n";
    }

    log.error(logString);
}
 
Example 27
@Test
public void testValidateWithValidFixture() throws Exception {
    String resourcePath = "executions/valid_specification_file.json";
    ClassLoader classLoader = getClass().getClassLoader();
    ProcessingReport report = DataExportRecipeValidator.validate(new FileReader(classLoader.getResource(resourcePath).getFile()));
    assertTrue("Spec is valid", report.isSuccess());
}
 
Example 28
Source Project: bender   Source File: BenderConfig.java    License: 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 29
Source Project: elucidate-server   Source File: AbstractSchemaValidatorTest.java    License: 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 30
Source Project: Bastion   Source File: JsonSchemaAssertions.java    License: 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));
    }
}