com.github.fge.jsonschema.main.JsonSchema Java Examples
The following examples show how to use
com.github.fge.jsonschema.main.JsonSchema.
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: ValidationService.java From yaml-json-validator-maven-plugin with Apache License 2.0 | 6 votes |
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 #2
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
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 #3
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
private JsonSchema getSchemaV2() throws Exception { if (schemaV2 != null && (System.currentTimeMillis() - LAST_FETCH) < 600000) { return schemaV2; } try { LOGGER.debug("returning online schema"); LAST_FETCH = System.currentTimeMillis(); schemaV2 = resolveJsonSchema(getUrlContents(SCHEMA2_URL)); return schemaV2; } catch (Exception e) { LOGGER.warn("error fetching schema from GitHub, using local copy"); schemaV2 = resolveJsonSchema(getResourceFileAsString(SCHEMA2_FILE)); LAST_FETCH = System.currentTimeMillis(); return schemaV2; } }
Example #4
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 6 votes |
@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 #5
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 6 votes |
@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 #6
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
private JsonSchema getSchemaV3() throws Exception { if (schemaV3 != null && (System.currentTimeMillis() - LAST_FETCH_V3) < 600000) { return schemaV3; } try { LOGGER.debug("returning online schema v3"); LAST_FETCH_V3 = System.currentTimeMillis(); schemaV3 = resolveJsonSchema(getUrlContents(SCHEMA_URL), true); return schemaV3; } catch (Exception e) { LOGGER.warn("error fetching schema v3 from GitHub, using local copy"); schemaV3 = resolveJsonSchema(getResourceFileAsString(SCHEMA_FILE), true); LAST_FETCH_V3 = System.currentTimeMillis(); return schemaV3; } }
Example #7
Source File: SchemaValidator.java From swagger-inflector with Apache License 2.0 | 6 votes |
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 File: JsonSchemaValidator.java From microcks with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: JsonSchemaValidationTest.java From microprofile-health with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: JsonSchemaValidator.java From microcks with Apache License 2.0 | 5 votes |
/** */ 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: SchemaValidator.java From swagger-inflector with Apache License 2.0 | 5 votes |
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 #12
Source File: JsonSchemaValidator.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
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 #13
Source File: JsonSchemaValidator.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
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 #14
Source File: JsonSchemaValidator.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
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 #15
Source File: MultiOpenApiParser.java From api-compiler with Apache License 2.0 | 5 votes |
/** * Validates the input Swagger JsonNode against Swagger Specification schema. * * @throws OpenApiConversionException */ private static void validateSwaggerSpec(JsonNode swaggerJsonNode) throws OpenApiConversionException { ProcessingReport report = null; try { URL url = Resources.getResource(SCHEMA_RESOURCE_PATH); String swaggerSchema = Resources.toString(url, StandardCharsets.UTF_8); JsonNode schemaNode = Yaml.mapper().readTree(swaggerSchema); JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode); report = schema.validate(swaggerJsonNode); } catch (Exception ex) { throw new OpenApiConversionException("Unable to parse the content. " + ex.getMessage(), ex); } if (!report.isSuccess()) { String message = ""; Iterator itr = report.iterator(); if (itr.hasNext()) { message += ((ProcessingMessage) itr.next()).toString(); } while(itr.hasNext()) { message += "," + ((ProcessingMessage) itr.next()).toString(); } throw new OpenApiConversionException( String.format("Invalid OpenAPI file. Please fix the schema errors:\n%s", message)); } }
Example #16
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 5 votes |
private JsonSchema getSchema(boolean isVersion2) throws Exception { if (isVersion2) { return getSchemaV2(); } else { return getSchemaV3(); } }
Example #17
Source File: AbstractRule.java From light with Apache License 2.0 | 5 votes |
public static Map<String, Object> getRuleByRuleClass(String ruleClass) throws Exception { Map<String, Object> map = null; Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap"); ConcurrentMap<String, Map<String, Object>> cache = (ConcurrentMap<String, Map<String, Object>>)ruleMap.get("cache"); if(cache == null) { cache = new ConcurrentLinkedHashMap.Builder<String, Map<String, Object>>() .maximumWeightedCapacity(1000) .build(); ruleMap.put("cache", cache); } else { map = cache.get(ruleClass); } if(map == null) { OrientGraph graph = ServiceLocator.getInstance().getGraph(); try { OrientVertex rule = (OrientVertex)graph.getVertexByKey("Rule.ruleClass", ruleClass); if(rule != null) { map = rule.getRecord().toMap(); // remove sourceCode as we don't need it and it is big map.remove("sourceCode"); // convert schema to JsonSchema in order to speed up validation. if(map.get("schema") != null) { JsonNode schemaNode = ServiceLocator.getInstance().getMapper().valueToTree(map.get("schema")); JsonSchema schema = schemaFactory.getJsonSchema(schemaNode); map.put("schema", schema); } logger.debug("map = " + map); cache.put(ruleClass, map); } } catch (Exception e) { logger.error("Exception:", e); throw e; } finally { graph.shutdown(); } } return map; }
Example #18
Source File: TypeServiceImpl.java From ic with MIT License | 5 votes |
private synchronized void refresh() { List<Type> typeList = mergeAllWithBaseType(typeRepository.findAll()); Map<String, JsonSchema> newCaches = Maps.newHashMap(); typeList.forEach(type -> newCaches.put(type.getName(), createJsonSchema(type))); caches = newCaches; logger.info("更新Schema列表成功,更新的Schema数量为{}", typeList.size()); }
Example #19
Source File: YamlParser.java From elasticsearch-migration with Apache License 2.0 | 5 votes |
private JsonSchema createJsonSchema() { final LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder() .dereferencing(Dereferencing.INLINE).freeze(); final JsonSchemaFactory factory = JsonSchemaFactory.newBuilder() .setLoadingConfiguration(loadingConfiguration).freeze(); try { final JsonNode schemaObject = jsonMapper.readTree(MIGRATION_SCHEMA); return factory.getJsonSchema(schemaObject); } catch (Exception e) { throw new IllegalStateException("Couldn't parse yaml schema", e); } }
Example #20
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test @Ignore("Used to generate the initial extension definition") public void generateBaseExtensionDefinition() throws Exception { JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(OBJECT_MAPPER); com.fasterxml.jackson.module.jsonSchema.JsonSchema schema = schemaGen.generateSchema(Extension.class); LOG.info(OBJECT_MAPPER.writeValueAsString(schema)); }
Example #21
Source File: BenderConfig.java From bender with Apache License 2.0 | 5 votes |
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 #22
Source File: JSONValidator.java From arctic-sea with Apache License 2.0 | 5 votes |
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 #23
Source File: SchemaUtils.java From karate with MIT License | 5 votes |
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 #24
Source File: OpenApiSchemaValidator.java From syndesis with Apache License 2.0 | 5 votes |
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 #25
Source File: ExtensionSchemaValidationTest.java From syndesis with Apache License 2.0 | 5 votes |
@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 #26
Source File: ODataSerializerTest.java From syndesis with Apache License 2.0 | 5 votes |
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 #27
Source File: TestMetrics4BearsJsonFile.java From repairnator with MIT License | 4 votes |
@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 #28
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 4 votes |
private JsonSchema resolveJsonSchema(String schemaAsString) throws Exception { return resolveJsonSchema(schemaAsString, false); }
Example #29
Source File: Oas20SchemaValidator.java From syndesis with Apache License 2.0 | 4 votes |
@Override public JsonSchema getSchema() { return SWAGGER_2_0_SCHEMA; }
Example #30
Source File: Oas30SchemaValidator.java From syndesis with Apache License 2.0 | 4 votes |
@Override public JsonSchema getSchema() { return OPENAPI_3_0_SCHEMA; }