org.everit.json.schema.loader.SchemaLoader Java Examples

The following examples show how to use org.everit.json.schema.loader.SchemaLoader. 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: JsonSchemaDiffLibrary.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Find and analyze differences between two JSON schemas.
 *
 * @param original Original/Previous/First/Left JSON schema representation
 * @param updated  Updated/Next/Second/Right JSON schema representation
 * @return an object to access the found differences: Original -> Updated
 * @throws IllegalArgumentException if the input is not a valid representation of a JsonSchema
 */
public static DiffContext findDifferences(String original, String updated) {
    try {
        JSONObject originalJson = MAPPER.readValue(original, JSONObject.class);
        JSONObject updatedJson = MAPPER.readValue(updated, JSONObject.class);

        Schema originalSchema = SchemaLoader.builder()
            .schemaJson(originalJson)
            .build().load().build();

        Schema updatedSchema = SchemaLoader.builder()
            .schemaJson(updatedJson)
            .build().load().build();

        return findDifferences(originalSchema, updatedSchema);

    } catch (JsonProcessingException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #2
Source File: RelativeURITest.java    From json-schema with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    System.out.println(JettyWrapper.class
            .getResource("/org/everit/json/schema/relative-uri/").toExternalForm());

    JettyWrapper jetty = new JettyWrapper("/org/everit/json/schema/relative-uri");
    jetty.start();
    try {
        SchemaLoader.builder()
                .resolutionScope("http://localhost:1234/schema/")
                .schemaJson(
                        new JSONObject(new JSONTokener(IOUtils.toString(getClass().getResourceAsStream(
                                "/org/everit/json/schema/relative-uri/schema/main.json")))))
                .build().load().build();
    } finally {
        jetty.stop();
    }
}
 
Example #3
Source File: CapabilitySchemaValidator.java    From AppiumTestDistribution with GNU General Public License v3.0 6 votes vote down vote up
public void validateCapabilitySchema(JSONObject capability) {
    try {
        isPlatformInEnv();
        InputStream inputStream = getClass().getResourceAsStream(getPlatform());
        JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
        Schema schema = SchemaLoader.load(rawSchema);
        schema.validate(new JSONObject(capability.toString()));
        validateRemoteHosts();
    } catch (ValidationException e) {
        if (e.getCausingExceptions().size() > 1) {
            e.getCausingExceptions().stream()
                .map(ValidationException::getMessage)
                .forEach(System.out::println);
        } else {
            LOGGER.info(e.getErrorMessage());
        }

        throw new ValidationException("Capability json provided is missing the above schema");
    }
}
 
Example #4
Source File: EventValidatorBuilder.java    From nakadi with MIT License 6 votes vote down vote up
public EventTypeValidator build(final EventType eventType) {
    final List<Function<JSONObject, Optional<ValidationError>>> validators = new ArrayList<>(2);

    // 1. We always validate schema.
    final Schema schema = SchemaLoader.builder()
            .schemaJson(loader.effectiveSchema(eventType))
            .addFormatValidator(new RFC3339DateTimeValidator())
            .build()
            .load()
            .build();
    validators.add((evt) -> validateSchemaConformance(schema, evt));

    // 2. in case of data or business event type we validate occurred_at
    if (eventType.getCategory() == EventCategory.DATA || eventType.getCategory() == EventCategory.BUSINESS) {
        validators.add(this::validateOccurredAt);
    }

    return (event) -> validators
            .stream()
            .map(validator -> validator.apply(event))
            .filter(Optional::isPresent)
            .findFirst()
            .orElse(Optional.empty());
}
 
Example #5
Source File: SchemaDiffTest.java    From nakadi with MIT License 6 votes vote down vote up
@Test
public void checkJsonSchemaCompatibility() throws Exception {
    final JSONArray testCases = new JSONArray(
            readFile("invalid-schema-evolution-examples.json"));

    for (final Object testCaseObject : testCases) {
        final JSONObject testCase = (JSONObject) testCaseObject;
        final Schema original = SchemaLoader.load(testCase.getJSONObject("original_schema"));
        final Schema update = SchemaLoader.load(testCase.getJSONObject("update_schema"));
        final List<String> errorMessages = testCase
                .getJSONArray("errors")
                .toList()
                .stream()
                .map(Object::toString)
                .collect(toList());
        final String description = testCase.getString("description");

        assertThat(description, service.collectChanges(original, update).stream()
                .map(change -> change.getType().toString() + " " + change.getJsonPath())
                .collect(toList()), is(errorMessages));

    }
}
 
Example #6
Source File: EmptyObjectTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void validateEmptyObject() throws IOException {
    JSONObject jsonSchema = new JSONObject(new JSONTokener(IOUtils.toString(
            new InputStreamReader(getClass().getResourceAsStream("/org/everit/json/schema/json-schema-draft-04.json")))));

    JSONObject jsonSubject = new JSONObject("{\n" +
            "  \"type\": \"object\",\n" +
            "  \"properties\": {}\n" +
            "}");

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);
}
 
Example #7
Source File: Validator.java    From aws-cloudformation-resource-schema with Apache License 2.0 5 votes vote down vote up
/** get schema-builder preloaded with JSON draft V7 meta-schema */
private SchemaLoaderBuilder getSchemaLoader() {
    final SchemaLoaderBuilder builder = SchemaLoader
        .builder()
        .draftV7Support()
        .schemaClient(downloader);

    // registers the local schema with the draft-07 url
    builder.registerSchemaByURI(JSON_SCHEMA_URI_HTTP, jsonSchemaObject);

    return builder;
}
 
Example #8
Source File: NotSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void issue345() {
    JSONObject rawSchema = LOADER.readObj("issue345.json");
    Schema notSchema = SchemaLoader.builder()
        .schemaJson(rawSchema)
        .build().load().build();
    assertThat(new JSONObject(notSchema.toString()), sameJsonAs(rawSchema));
}
 
Example #9
Source File: StringSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoFormat() {
    JSONObject rawSchemaJson = ResourceLoader.DEFAULT.readObj("tostring/stringschema.json");
    rawSchemaJson.remove("format");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #10
Source File: StringSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoExplicitType() {
    JSONObject rawSchemaJson = ResourceLoader.DEFAULT.readObj("tostring/stringschema.json");
    rawSchemaJson.remove("type");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #11
Source File: StringSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void regexpFactoryIsUsedByLoader() {
    SchemaLoader loader = SchemaLoader.builder()
            .regexpFactory(new RE2JRegexpFactory())
            .schemaJson(ResourceLoader.DEFAULT.readObj("tostring/stringschema.json"))
            .build();

    StringSchema result = (StringSchema) loader.load().build();

    assertEquals(result.getRegexpPattern().getClass().getSimpleName(), "RE2JRegexp");
}
 
Example #12
Source File: ObjectSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoExplicitType() {
    JSONObject rawSchemaJson = loader.readObj("tostring/objectschema.json");
    rawSchemaJson.remove("type");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #13
Source File: ObjectSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringWithUnprocessedProps() {
    JSONObject rawSchemaJson = loader.readObj("tostring/objectschema-unprocessed.json");
    Schema schema = SchemaLoader.load(rawSchemaJson);
    String actual = schema.toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #14
Source File: ObjectSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoAdditionalProperties() {
    JSONObject rawSchemaJson = loader.readObj("tostring/objectschema.json");
    rawSchemaJson.put("additionalProperties", false);
    Schema schema = SchemaLoader.load(rawSchemaJson);
    String actual = schema.toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #15
Source File: ReferenceSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringTest() {
    JSONObject rawSchemaJson = ResourceLoader.DEFAULT.readObj("tostring/ref.json");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertTrue(ObjectComparator.deepEquals(rawSchemaJson.query("/properties"),
            new JSONObject(actual).query("/properties")));
}
 
Example #16
Source File: ArraySchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringAdditionalItems() {
    JSONObject rawSchemaJson = loader.readObj("tostring/arrayschema-list.json");
    rawSchemaJson.remove("items");
    rawSchemaJson.put("additionalItems", false);
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertFalse(new JSONObject(actual).getBoolean("additionalItems"));
}
 
Example #17
Source File: ArraySchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoExplicitType() {
    JSONObject rawSchemaJson = loader.readObj("tostring/arrayschema-list.json");
    rawSchemaJson.remove("type");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #18
Source File: ArraySchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringContains() {
    JSONObject rawSchemaJson = loader.readObj("tostring/arrayschema-contains.json");
    String actual = SchemaLoader.builder()
            .draftV6Support()
            .schemaJson(rawSchemaJson)
            .build()
            .load()
            .build()
            .toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #19
Source File: NumberSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoExplicitType() {
    JSONObject rawSchemaJson = loader.readObj("numberschema.json");
    rawSchemaJson.remove("type");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #20
Source File: NumberSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringReqInteger() {
    JSONObject rawSchemaJson = loader.readObj("numberschema.json");
    rawSchemaJson.put("type", "integer");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example #21
Source File: CommonG.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 * Check json matches schema
 *
 * @param schema schema obtained from deploy-api
 * @param json   json to be checked
 * @return boolean whether the json matches the schema or not
 */
public boolean matchJsonToSchema(JSONObject schema, JSONObject json) throws Exception {
    SchemaLoader.builder()
            .useDefaults(true)
            .schemaJson(schema)
            .build()
            .load()
            .build()
            .validate(json);
    return true;
}
 
Example #22
Source File: JsonValidator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Loads JSON schema. The schema may contain remote references.
 *
 * @param schema String containing the JSON schema to load
 * @return loaded {@link Schema}
 * @throws InvalidJsonSchemaException if the schema fails to load
 */
public Schema loadSchema(String schema) {
  try {
    JSONObject rawSchema = new JSONObject(new JSONTokener(schema));
    return SchemaLoader.load(rawSchema);
  } catch (JSONException | SchemaException e) {
    throw new InvalidJsonSchemaException(e);
  }
}
 
Example #23
Source File: JSONSchemaUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = ValidationException.class)
public void givenInvalidInput_whenValidating_thenInvalid() {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
    JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json")));

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);
}
 
Example #24
Source File: JSONSchemaUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenValidInput_whenValidating_thenValid() {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
    JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_valid.json")));

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);
}
 
Example #25
Source File: MetaSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void validateMetaSchema() throws IOException {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(
            IOUtils.toString(
                    new InputStreamReader(getClass().getResourceAsStream("/org/everit/json/schema/json-schema-draft-04.json")))
    ));

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSchema);
}
 
Example #26
Source File: ValidatorTest.java    From aws-cloudformation-resource-schema with Apache License 2.0 5 votes vote down vote up
/**
 * trivial coverage test: cannot cache a schema if it has an invalid $id
 */
@ParameterizedTest
@ValueSource(strings = { ":invalid/uri", "" })
public void registerMetaSchema_invalidRelativeRef_shouldThrow(String uri) {

    JSONObject badSchema = loadJSON(RESOURCE_DEFINITION_SCHEMA_PATH);
    badSchema.put("$id", uri);
    assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> {
        validator.registerMetaSchema(SchemaLoader.builder(), badSchema);
    });
}
 
Example #27
Source File: ValidatorTest.java    From aws-cloudformation-resource-schema with Apache License 2.0 5 votes vote down vote up
/**
 * trivial coverage test: cannot cache a schema if it has no $id
 */
@Test
public void registerMetaSchema_nullId_shouldThrow() {
    JSONObject badSchema = loadJSON(RESOURCE_DEFINITION_SCHEMA_PATH);
    badSchema.remove("$id");
    assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> {
        validator.registerMetaSchema(SchemaLoader.builder(), badSchema);
    });
}
 
Example #28
Source File: JsonSchemaTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@BeforeEach
  public void setUp() throws Exception {
    if (sFhir == null) {
//      String path = TestUtilities.resourceNameToFile("fhir.schema.json"); // todo... what should this be?
//      String source = TextFile.fileToString(path);
//      JSONObject rawSchema = new JSONObject(new JSONTokener(source));
//      sFhir = SchemaLoader.load(rawSchema);
      JSONObject rawSchema = new JSONObject(new JSONTokener(TEST_SCHEMA));
      sTest = SchemaLoader.load(rawSchema);
    }
  }
 
Example #29
Source File: Validator.java    From daq with Apache License 2.0 5 votes vote down vote up
private Schema getSchema(File schemaFile) {
  try (InputStream schemaStream = new FileInputStream(schemaFile)) {
    JSONObject rawSchema = new JSONObject(new JSONTokener(schemaStream));
    SchemaLoader loader = SchemaLoader.builder().schemaJson(rawSchema).httpClient(new RelativeClient()).build();
    return loader.load().build();
  } catch (Exception e) {
    throw new RuntimeException("While loading schema " + schemaFile.getAbsolutePath(), e);
  }
}
 
Example #30
Source File: Registrar.java    From daq with Apache License 2.0 5 votes vote down vote up
private void loadSchema(String key) {
  File schemaFile = new File(schemaBase, key);
  try (InputStream schemaStream = new FileInputStream(schemaFile)) {
    JSONObject rawSchema = new JSONObject(new JSONTokener(schemaStream));
    schemas.put(key, SchemaLoader.load(rawSchema, new Loader()));
  } catch (Exception e) {
    throw new RuntimeException("While loading schema " + schemaFile.getAbsolutePath(), e);
  }
}