Java Code Examples for org.everit.json.schema.loader.SchemaLoader#load()

The following examples show how to use org.everit.json.schema.loader.SchemaLoader#load() . 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: 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 2
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 3
Source File: SchemaEvolutionServiceTest.java    From nakadi with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    final List<SchemaEvolutionConstraint> evolutionConstraints = Lists.newArrayList(evolutionConstraint);
    final JSONObject metaSchemaJson = new JSONObject(Resources.toString(Resources.getResource("schema.json"),
            Charsets.UTF_8));
    final Schema metaSchema = SchemaLoader.load(metaSchemaJson);
    this.service = new SchemaEvolutionService(metaSchema, evolutionConstraints, schemaDiff, levelResolver,
            errorMessages);

    Mockito.doReturn("error").when(errorMessages).get(any());
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: InvalidObjectInArrayTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Schema schema = SchemaLoader.load(readObject("schema.json"));
    Object subject = readObject("subject.json");
    try {
        schema.validate(subject);
        Assert.fail("did not throw exception");
    } catch (ValidationException e) {
        Assert.assertEquals("#/notification/target/apps/0/id", e.getPointerToViolation());
    }
}
 
Example 11
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 12
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 13
Source File: SchemaDiffTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void testSchemaAddsProperties() {
    final Schema first = SchemaLoader.load(new JSONObject("{}"));

    final Schema second = SchemaLoader.load(new JSONObject("{\"properties\": {}}"));
    final List<SchemaChange> changes = service.collectChanges(first, second);
    assertTrue(changes.isEmpty());
}
 
Example 14
Source File: SchemaDiffTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void testRecursiveCheck() throws IOException {
    final Schema original = SchemaLoader.load(new JSONObject(
            readFile("recursive-schema.json")));
    final Schema newOne = SchemaLoader.load(new JSONObject(
            readFile("recursive-schema.json")));
    assertTrue(service.collectChanges(original, newOne).isEmpty());
}
 
Example 15
Source File: SchemaValidatorConfig.java    From nakadi with MIT License 5 votes vote down vote up
@Bean
public SchemaEvolutionService schemaEvolutionService() throws IOException {
    final JSONObject metaSchemaJson = new JSONObject(Resources.toString(Resources.getResource("schema.json"),
            Charsets.UTF_8));
    final Schema metaSchema = SchemaLoader.load(metaSchemaJson);

    final List<SchemaEvolutionConstraint> schemaEvolutionConstraints = Lists.newArrayList(
            new CategoryChangeConstraint(),
            new CompatibilityModeChangeConstraint(adminService),
            new PartitionKeyFieldsConstraint(),
            new PartitionStrategyConstraint(),
            new EnrichmentStrategyConstraint()
    );

    final Map<SchemaChange.Type, String> errorMessage = new HashMap<>();
    errorMessage.put(SCHEMA_REMOVED, "change not allowed");
    errorMessage.put(TYPE_NARROWED, "schema types cannot be narrowed");
    errorMessage.put(TYPE_CHANGED, "schema types must be the same");
    errorMessage.put(NUMBER_OF_ITEMS_CHANGED, "the number of schema items cannot be changed");
    errorMessage.put(PROPERTY_REMOVED, "schema properties cannot be removed");
    errorMessage.put(DEPENDENCY_ARRAY_CHANGED, "schema dependencies array cannot be changed");
    errorMessage.put(DEPENDENCY_SCHEMA_CHANGED, "schema dependencies cannot be changed");
    errorMessage.put(COMPOSITION_METHOD_CHANGED, "schema composition method changed");
    errorMessage.put(ATTRIBUTE_VALUE_CHANGED, "change to attribute value not allowed");
    errorMessage.put(ENUM_ARRAY_CHANGED, "enum array changed");
    errorMessage.put(SUB_SCHEMA_CHANGED, "sub schema changed");
    errorMessage.put(DEPENDENCY_SCHEMA_REMOVED, "dependency schema removed");
    errorMessage.put(REQUIRED_ARRAY_CHANGED, "required array changed");
    errorMessage.put(REQUIRED_ARRAY_EXTENDED, "required array changed");
    errorMessage.put(ADDITIONAL_PROPERTIES_CHANGED, "change not allowed");
    errorMessage.put(ADDITIONAL_PROPERTIES_NARROWED, "change not allowed");
    errorMessage.put(ADDITIONAL_ITEMS_CHANGED, "change not allowed");

    final SchemaDiff diff = new SchemaDiff();

    return new SchemaEvolutionService(metaSchema, schemaEvolutionConstraints, diff, errorMessage);
}
 
Example 16
Source File: SchemaEvolutionService.java    From nakadi with MIT License 4 votes vote down vote up
private Schema schema(final EventTypeBase eventType) {
    final JSONObject schemaAsJson = new JSONObject(eventType.getSchema().getSchema());

    return SchemaLoader.load(schemaAsJson);
}
 
Example 17
Source File: JsonSchemaFromFieldDescriptorsGeneratorTest.java    From restdocs-raml with MIT License 4 votes vote down vote up
private void whenSchemaGenerated() {
    schemaString = generator.generateSchema(fieldDescriptors);
    schema = SchemaLoader.load(new JSONObject(schemaString));
}
 
Example 18
Source File: JSONSchemaStore.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Return a Schema from bytes for use outside of the SchemaStore.
 */
public static Schema readSchema(byte[] bytes) throws IOException {
  JSONObject json = Json.readValue(bytes, JSONObject.class);
  return SchemaLoader.load(json);
}
 
Example 19
Source File: Util.java    From configuration-as-code-plugin with MIT License 3 votes vote down vote up
/**
 * Retrieves the JSON schema for the running jenkins instance.
 * <p>Example Usage:</p>
 * <pre>{@code
 *      Schema jsonSchema = returnSchema();}
 *      </pre>
 *
 * @return the schema for the current jenkins instance
 */
public static Schema returnSchema() {
    JSONObject schemaObject = generateSchema();
    JSONObject jsonSchema = new JSONObject(
        new JSONTokener(schemaObject.toString()));
    return SchemaLoader.load(jsonSchema);
}