Java Code Examples for com.github.fge.jsonschema.main.JsonSchemaFactory#byDefault()

The following examples show how to use com.github.fge.jsonschema.main.JsonSchemaFactory#byDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonSchemaValidationTest.java    From microprofile-health with Apache License 2.0 6 votes 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 2
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 3
Source File: SchemaValidationTest.java    From swagger-inflector with 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 4
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
private JsonSchema resolveJsonSchema(String schemaAsString, boolean removeId) throws Exception {
    JsonNode schemaObject = JsonMapper.readTree(schemaAsString);
    if (removeId) {
        ObjectNode oNode = (ObjectNode) schemaObject;
        if (oNode.get("id") != null) {
            oNode.remove("id");
        }
        if (oNode.get("$schema") != null) {
            oNode.remove("$schema");
        }
        if (oNode.get("description") != null) {
            oNode.remove("description");
        }
    }
    JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    return factory.getJsonSchema(schemaObject);

}
 
Example 5
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 6
Source File: DataExportRecipeValidator.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
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 7
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 8
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 9
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 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: CEFParserTest.java    From metron with Apache License 2.0 5 votes vote down vote up
protected boolean validateJsonData(final String jsonSchema, final String jsonData) throws Exception {
	final JsonNode d = JsonLoader.fromString(jsonData);
	final JsonNode s = JsonLoader.fromString(jsonSchema);

	final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
	JsonValidator v = factory.getValidator();

	ProcessingReport report = v.validate(s, d);

	return report.toString().contains("success");
}
 
Example 12
Source File: LEEFParserTest.java    From metron with Apache License 2.0 5 votes vote down vote up
protected boolean validateJsonData(final String jsonSchema, final String jsonData)
    throws Exception {
  final JsonNode d = JsonLoader.fromString(jsonData);
  final JsonNode s = JsonLoader.fromString(jsonSchema);

  final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
  JsonValidator v = factory.getValidator();

  ProcessingReport report = v.validate(s, d);

  return report.toString().contains("success");
}
 
Example 13
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 14
Source File: AbstractConfigTest.java    From opensoc-streaming with Apache License 2.0 4 votes vote down vote up
/**
 * validateJsonData
 * @param jsonSchema
 * @param jsonData
 * @return
 * @throws Exception
 */
 
protected boolean validateJsonData(final String jsonSchema, final String jsonData)
    throws Exception {
    
    final JsonNode d = JsonLoader.fromString(jsonData);
    final JsonNode s = JsonLoader.fromString(jsonSchema);
    
    final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonValidator v = factory.getValidator();
    
    ProcessingReport report = v.validate(s, d);
    System.out.println(report);
    
    return report.toString().contains("success");
}
 
Example 15
Source File: AbstractSchemaTest.java    From opensoc-streaming with Apache License 2.0 4 votes vote down vote up
/**
 * validateJsonData
 * @param jsonSchema
 * @param jsonData
 * @return
 * @throws Exception
 */
 
protected boolean validateJsonData(final String jsonSchema, final String jsonData)
    throws Exception {
    
    final JsonNode d = JsonLoader.fromString(jsonData);
    final JsonNode s = JsonLoader.fromString(jsonSchema);
    
    final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonValidator v = factory.getValidator();
    
    ProcessingReport report = v.validate(s, d);
    System.out.println(report);
    
    return report.toString().contains("success");
}
 
Example 16
Source File: AbstractParserConfigTest.java    From metron with Apache License 2.0 3 votes vote down vote up
protected boolean validateJsonData(final String jsonSchema, final String jsonData)
    throws IOException, ProcessingException {

  final JsonNode d = JsonLoader.fromString(jsonData);
  final JsonNode s = JsonLoader.fromString(jsonSchema);

  final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
  JsonValidator v = factory.getValidator();

  ProcessingReport report = v.validate(s, d);

  return report.toString().contains("success");
}