Java Code Examples for com.github.fge.jsonschema.core.report.ProcessingReport#isSuccess()

The following examples show how to use com.github.fge.jsonschema.core.report.ProcessingReport#isSuccess() . 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: 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 2
Source File: Index.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 3
Source File: JJSchemaProcessing.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
{
    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 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: SchemaValidator.java    From swagger-inflector with 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 6
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 7
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 8
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 9
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 10
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 11
Source File: AbstractRunner.java    From TomboloDigitalConnector with 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 12
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 13
Source File: ValidationMatchers.java    From arctic-sea with 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 14
Source File: JSONValidator.java    From arctic-sea with 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 15
Source File: FieldDecoderTest.java    From arctic-sea with 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 16
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 17
Source File: JsonSchemaUtils.java    From TestHub with 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 18
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 19
Source File: OnboardingService.java    From cubeai with Apache License 2.0 4 votes vote down vote up
private Boolean parseMetadata(Solution solution, File dataFile) {
    JSONObject metadataJson;

    try {
        String jsonString = FileUtils.readFileToString(dataFile, "UTF-8");
        // solution.setMetadata(jsonString); // 作废metadata字段,直接从文件中获取

        metadataJson = JSONObject.parseObject(jsonString);

        //==========================================================================================================
        // validate schemaVersion
        String schemafile = null;
        String schemaVersion = metadataJson.get("schema").toString();

        if (schemaVersion.contains("3")) {
            schemafile = "/model-schema/model-schema-0.3.0.json";
        } else if (schemaVersion.contains("4")) {
            schemafile = "/model-schema/model-schema-0.4.0.json";
        } else if (schemaVersion.contains("5")) {
            schemafile = "/model-schema/model-schema-0.5.0.json";
        } else {
            log.error("No matching model schema");
            return false;
        }

        JsonNode schema = JsonLoader.fromResource(schemafile);    // 直接以resources为根目录读取
        JsonNode metadataJson1 = JsonLoader.fromFile(dataFile);
        JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        com.github.fge.jsonschema.main.JsonValidator validator = factory.getValidator();
        ProcessingReport report = validator.validate(schema, metadataJson1);
        if (!report.isSuccess()) {
            StringBuilder sb = new StringBuilder();
            for (ProcessingMessage processingMessage : report) {
                if (!processingMessage.getMessage()
                    .equals("the following keywords are unknown and will be ignored: [self]"))
                    sb.append(processingMessage.getMessage() + "\n");
            }
            log.error("Input JSON is not as per schema cause: '" + sb.toString() + "'");
            return false;
        }
        //==========================================================================================================

        if (metadataJson.containsKey("name")) {
            solution.setName(metadataJson.get("name").toString());
        }

        if (metadataJson.containsKey("modelVersion")) {
            solution.setVersion(metadataJson.get("modelVersion").toString());
        } else {
            solution.setVersion("snapshot");
        }
    } catch (Exception e) {
        return false;
    }

    return true;
}
 
Example 20
Source File: JsonParser.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public void processTuple(byte[] tuple)
{
  if (tuple == null) {
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(null, "null tuple"));
    }
    errorTupleCount++;
    return;
  }
  String incomingString = new String(tuple);
  try {
    if (schema != null) {
      ProcessingReport report = null;
      JsonNode data = JsonLoader.fromString(incomingString);
      report = schema.validate(data);
      if (report != null && !report.isSuccess()) {
        Iterator<ProcessingMessage> iter = report.iterator();
        StringBuilder s = new StringBuilder();
        while (iter.hasNext()) {
          ProcessingMessage pm = iter.next();
          s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
              .append(",");
        }
        s.setLength(s.length() - 1);
        errorTupleCount++;
        if (err.isConnected()) {
          err.emit(new KeyValPair<String, String>(incomingString, s.toString()));
        }
        return;
      }
    }
    if (parsedOutput.isConnected()) {
      parsedOutput.emit(new JSONObject(incomingString));
      parsedOutputCount++;
    }
    if (out.isConnected()) {
      out.emit(objMapper.readValue(tuple, clazz));
      emittedObjectCount++;
    }
  } catch (JSONException | ProcessingException | IOException e) {
    errorTupleCount++;
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(incomingString, e.getMessage()));
    }
    logger.error("Failed to parse json tuple {}, Exception = {} ", tuple, e);
  }
}