org.everit.json.schema.Schema Java Examples

The following examples show how to use org.everit.json.schema.Schema. 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: SchemaLoader.java    From json-schema with Apache License 2.0 6 votes vote down vote up
private Schema.Builder loadSchemaObject(JsonObject o) {
    AdjacentSchemaExtractionState postExtractionState = runSchemaExtractors(o);
    Collection<Schema.Builder<?>> extractedSchemas = postExtractionState.extractedSchemaBuilders();
    Schema.Builder effectiveReturnedSchema;
    if (extractedSchemas.isEmpty()) {
        effectiveReturnedSchema = EmptySchema.builder();
    } else if (extractedSchemas.size() == 1) {
        effectiveReturnedSchema = extractedSchemas.iterator().next();
    } else {
        Collection<Schema> built = extractedSchemas.stream()
                .map(Schema.Builder::build)
                .map(Schema.class::cast)
                .collect(toList());
        effectiveReturnedSchema = CombinedSchema.allOf(built).isSynthetic(true);
    }
    AdjacentSchemaExtractionState postCommonPropLoadingState = loadCommonSchemaProperties(effectiveReturnedSchema, postExtractionState);
    Map<String, Object> unprocessed = postCommonPropLoadingState.projectedSchemaJson().toMap();
    effectiveReturnedSchema.unprocessedProperties(unprocessed);
    return effectiveReturnedSchema;
}
 
Example #2
Source File: JsonSchemaFromFieldDescriptorsGenerator.java    From restdocs-raml with MIT License 6 votes vote down vote up
private Schema traverse(List<String> traversedSegments, List<JsonFieldPath> jsonFieldPaths, ObjectSchema.Builder builder) {

        Map<String, List<JsonFieldPath>> groupedFields = groupFieldsByFirstRemainingPathSegment(traversedSegments, jsonFieldPaths);
        groupedFields.forEach((propertyName, fieldList) -> {

            List<String> newTraversedSegments = new ArrayList<>(traversedSegments);
            newTraversedSegments.add(propertyName);
            fieldList.stream()
                    .filter(isDirectMatch(newTraversedSegments))
                    .findFirst()
                    .map(directMatch -> {
                        if (fieldList.size() == 1) {
                            handleEndOfPath(builder, propertyName, directMatch.getFieldDescriptor());
                        } else {
                            List<JsonFieldPath> newFields = new ArrayList<>(fieldList);
                            newFields.remove(directMatch);
                            processRemainingSegments(builder, propertyName, newTraversedSegments, newFields, (String) directMatch.getFieldDescriptor().getDescription());
                        }
                        return true;
                    }).orElseGet(() -> {
                        processRemainingSegments(builder, propertyName, newTraversedSegments, fieldList, null);
                        return true;
                    });
        });
        return builder.build();
    }
 
Example #3
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 #4
Source File: ArraySchemaDiff.java    From nakadi with MIT License 6 votes vote down vote up
private static void compareItemSchemaArray(
        final ArraySchema original, final ArraySchema update, final SchemaDiffState state) {
    final List<Schema> emptyList = ImmutableList.of();
    final List<Schema> originalSchemas = MoreObjects.firstNonNull(original.getItemSchemas(), emptyList);
    final List<Schema> updateSchemas = MoreObjects.firstNonNull(update.getItemSchemas(), emptyList);

    if (originalSchemas.size() != updateSchemas.size()) {
        state.addChange(NUMBER_OF_ITEMS_CHANGED);
    } else {
        final Iterator<Schema> originalIterator = originalSchemas.iterator();
        final Iterator<Schema> updateIterator = updateSchemas.iterator();
        int index = 0;
        while (originalIterator.hasNext()) {
            state.runOnPath("items/" + index, () -> {
                SchemaDiff.recursiveCheck(originalIterator.next(), updateIterator.next(), state);
            });
            index += 1;
        }
    }
}
 
Example #5
Source File: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@Override
public void visitEnumSchema(EnumSchemaWrapper schema) {
    Schema orig = original;

    if (orig instanceof FalseSchema)
        return; // FalseSchema matches nothing

    // Const and single-enum equivalency
    if (orig instanceof ConstSchema) {
        Object permittedValue = ((ConstSchema) orig).getPermittedValue();
        orig = EnumSchema.builder()
            .possibleValue(permittedValue)
            .build();
    }

    if (!(orig instanceof EnumSchema)) {
        ctx.addDifference(SUBSCHEMA_TYPE_CHANGED, orig, schema);
        return;
    }
    schema.accept(new EnumSchemaDiffVisitor(ctx, (EnumSchema) orig));
}
 
Example #6
Source File: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@Override
public void visitConstSchema(ConstSchemaWrapper schema) {
    Schema orig = original;

    if (orig instanceof FalseSchema)
        return; // FalseSchema matches nothing

    // Const and single-enum equivalency
    if (orig instanceof EnumSchema) {
        Set<Object> possibleValues = ((EnumSchema) orig).getPossibleValues();
        if (possibleValues.size() == 1) {
            orig = ConstSchema.builder()
                .permittedValue(possibleValues.stream().findAny().get())
                .build();
        }
    }

    if (!(orig instanceof ConstSchema)) {
        ctx.addDifference(SUBSCHEMA_TYPE_CHANGED, orig, schema);
        return;
    }
    schema.accept(new ConstSchemaDiffVisitor(ctx, (ConstSchema) orig));
}
 
Example #7
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 6 votes vote down vote up
@Override List<Schema.Builder<?>> extract() {
    List<Schema.Builder<?>> builders = new ArrayList<>(1);
    if (schemaHasAnyOf(config().specVersion.arrayKeywords())) {
        builders.add(buildArraySchema().requiresArray(false));
    }
    if (schemaHasAnyOf(config().specVersion.objectKeywords())) {
        builders.add(buildObjectSchema().requiresObject(false));
    }
    if (schemaHasAnyOf(NUMBER_SCHEMA_PROPS)) {
        builders.add(buildNumberSchema().requiresNumber(false));
    }
    if (schemaHasAnyOf(STRING_SCHEMA_PROPS)) {
        builders.add(buildStringSchema().requiresString(false));
    }
    if (config().specVersion.isAtLeast(DRAFT_7) && schemaHasAnyOf(CONDITIONAL_SCHEMA_KEYWORDS)) {
        builders.add(buildConditionalSchema());
    }
    return builders;
}
 
Example #8
Source File: JsonValidatorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testLoadAndValidateInvalid() {
  String schemaJson =
      gson.toJson(
          of(
              "title",
              "Hello World Job",
              "type",
              "object",
              "properties",
              of("p1", of("type", "integer"), "p2", of("type", "integer")),
              "required",
              singletonList("p2")));
  Schema schema = jsonValidator.loadSchema(schemaJson);
  try {
    jsonValidator.validate("{\"p1\":\"10\"}", schema);
  } catch (JsonValidationException expected) {
    assertEquals(
        newHashSet(
            new ConstraintViolation("#/p1: expected type: Number, found: String"),
            new ConstraintViolation("#: required key [p2] not found")),
        expected.getViolations());
  }
}
 
Example #9
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 6 votes vote down vote up
private Schema.Builder<?> loadForExplicitType(String typeString) {
    switch (typeString) {
    case "string":
        return buildStringSchema().requiresString(true);
    case "integer":
        return buildNumberSchema().requiresInteger(true);
    case "number":
        return buildNumberSchema();
    case "boolean":
        return BooleanSchema.builder();
    case "null":
        return NullSchema.builder();
    case "array":
        return buildArraySchema();
    case "object":
        return buildObjectSchema();
    default:
        throw new SchemaException(schemaJson.ls.locationOfCurrentObj(), format("unknown type: [%s]", typeString));
    }
}
 
Example #10
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 #11
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 #12
Source File: JsonValidatorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testLoadAndValidate() {
  String schemaJson =
      gson.toJson(
          of(
              "title",
              "Hello World Job",
              "type",
              "object",
              "properties",
              of("delay", of("type", "integer")),
              "required",
              singletonList("delay")));
  Schema schema = jsonValidator.loadSchema(schemaJson);
  jsonValidator.validate("{\"delay\":10}", schema);
}
 
Example #13
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 #14
Source File: SchemaLoader.java    From json-schema with Apache License 2.0 6 votes vote down vote up
private AdjacentSchemaExtractionState loadCommonSchemaProperties(Schema.Builder builder, AdjacentSchemaExtractionState state) {
    KeyConsumer consumedKeys = new KeyConsumer(state.projectedSchemaJson());
    consumedKeys.maybe(config.specVersion.idKeyword()).map(JsonValue::requireString).ifPresent(builder::id);
    consumedKeys.maybe("title").map(JsonValue::requireString).ifPresent(builder::title);
    consumedKeys.maybe("description").map(JsonValue::requireString).ifPresent(builder::description);
    if (ls.specVersion() == DRAFT_7) {
        consumedKeys.maybe("readOnly").map(JsonValue::requireBoolean).ifPresent(builder::readOnly);
        consumedKeys.maybe("writeOnly").map(JsonValue::requireBoolean).ifPresent(builder::writeOnly);
    }
    if (config.nullableSupport) {
        builder.nullable(consumedKeys.maybe("nullable")
                .map(JsonValue::requireBoolean)
                .orElse(Boolean.FALSE));
    }
    if (config.useDefaults) {
        consumedKeys.maybe("default").map(JsonValue::deepToOrgJson).ifPresent(builder::defaultValue);
    }
    builder.schemaLocation(ls.pointerToCurrentObj);
    return state.reduce(new ExtractionResult(consumedKeys.collect(), emptyList()));
}
 
Example #15
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 #16
Source File: EventValidatorBuilder.java    From nakadi with MIT License 5 votes vote down vote up
private Optional<ValidationError> validateSchemaConformance(final Schema schema, final JSONObject evt) {
    try {
        schema.validate(evt);
        return Optional.empty();
    } catch (final ValidationException e) {
        final StringBuilder builder = new StringBuilder();
        recursiveCollectErrors(e, builder);
        return Optional.of(new ValidationError(builder.toString()));
    }
}
 
Example #17
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 #18
Source File: AdjacentSchemaExtractionState.java    From json-schema with Apache License 2.0 5 votes vote down vote up
AdjacentSchemaExtractionState reduce(ExtractionResult result) {
    Set<Schema.Builder<?>> newExtractedSchemas = new HashSet<>(extractedSchemas.size() + result.extractedSchemas.size());
    newExtractedSchemas.addAll(extractedSchemas);
    newExtractedSchemas.addAll(result.extractedSchemas);
    JsonObject projectedContext = new ProjectedJsonObject(context, result.consumedKeys);
    return new AdjacentSchemaExtractionState(projectedContext, newExtractedSchemas);
}
 
Example #19
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 #20
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Override List<Schema.Builder<?>> extract() {
    if (containsKey("type")) {
        return singletonList(require("type").canBeMappedTo(JsonArray.class, arr -> (Schema.Builder) buildAnyOfSchemaForMultipleTypes())
                .orMappedTo(String.class, this::loadForExplicitType)
                .requireAny());
    } else {
        return emptyList();
    }
}
 
Example #21
Source File: CombinedSchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleCombinedSchemasAtTheSameNestingLevel() {
    SchemaLoader defaultLoader = SchemaLoader.builder().schemaJson(get("multipleKeywords")).build();
    JsonObject json = JsonValue.of(get("multipleKeywords")).requireObject();
    new LoadingState(LoaderConfig.defaultV4Config(), emptyMap(), json, json, null, SchemaLocation.empty());
    CombinedSchemaLoader subject = new CombinedSchemaLoader(defaultLoader);
    Set<Schema> actual = new HashSet<>(
            subject.extract(json).extractedSchemas.stream().map(builder -> builder.build()).collect(toList()));
    HashSet<CombinedSchema> expected = new HashSet<>(asList(
            CombinedSchema.allOf(singletonList(BooleanSchema.INSTANCE)).build(),
            CombinedSchema.anyOf(singletonList(StringSchema.builder().build())).build()
    ));
    assertEquals(expected, actual);
}
 
Example #22
Source File: JSONPrinter.java    From json-schema with Apache License 2.0 5 votes vote down vote up
public <K> void printSchemaMap(Map<K, Schema> input) {
    object();
    input.entrySet().forEach(entry -> {
        key(entry.getKey().toString());
        entry.getValue().describeTo(this);
    });
    endObject();
}
 
Example #23
Source File: JsonSchemaFromFieldDescriptorsGenerator.java    From restdocs-raml with MIT License 5 votes vote down vote up
private Schema unWrapRootArray(List<JsonFieldPath> jsonFieldPaths, Schema schema) {
    if (schema instanceof ObjectSchema) {
        ObjectSchema objectSchema = (ObjectSchema) schema;
        final Map<String, List<JsonFieldPath>> groups = groupFieldsByFirstRemainingPathSegment(emptyList(), jsonFieldPaths);
        if (groups.keySet().size() ==  1 && groups.keySet().contains("[]")) {
            return ArraySchema.builder().allItemSchema(objectSchema.getPropertySchemas().get("[]")).title(objectSchema.getTitle()).build();
        }

    }
    return schema;
}
 
Example #24
Source File: JSONSchemaStoreTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testReadSchema() throws IOException {
  byte[] data = Resources.toByteArray(
      Resources.getResource("schema/test-schemas/schemas/namespace_0/foo/foo.1.schema.json"));
  Schema schema = JSONSchemaStore.readSchema(data);
  assertTrue(schema.definesProperty("payload"));
}
 
Example #25
Source File: ReferenceLookup.java    From json-schema with Apache License 2.0 5 votes vote down vote up
private Schema.Builder<?> createReferenceSchema(String relPointerString, String absPointerString, JsonValue rawReferenced) {
    ReferenceKnot knot = new ReferenceKnot();
    ReferenceSchema.Builder refBuilder = knot.initReference(relPointerString);
    ls.pointerSchemas.put(absPointerString, knot);
    Schema referredSchema = new SchemaLoader(rawReferenced.ls).load().build();
    knot.resolveWith(referredSchema);
    return refBuilder;
}
 
Example #26
Source File: DecryptAetIdentifiersTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
@Test(expected = ValidationException.class)
public void testForbiddenFieldsStructured() throws Exception {
  JsonValidator validator = new JsonValidator();
  byte[] data = Resources
      .toByteArray(Resources.getResource("account-ecosystem/structured.schema.json"));
  Schema fxaSchema = JSONSchemaStore.readSchema(data);
  ObjectNode json = Json.asObjectNode(ImmutableMap.<String, Object>builder()
      .put("ecosystem_client_id", "3ed15efab7e94757bf9e9ef5e844ada2")
      .put("ecosystem_device_id", "7ab4e373ce434b848a9d0946e388fee9")
      .put("ecosystem_user_id", "aab4e373ce434b848a9d0946e388fdd3").build());
  validator.validate(fxaSchema, json);
}
 
Example #27
Source File: ParsePayload.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
private void validateTimed(Schema schema, ObjectNode json) throws JsonProcessingException {
  if (validator == null) {
    validator = new JsonValidator();
  }
  long startTime = System.currentTimeMillis();
  validator.validate(schema, json);
  long endTime = System.currentTimeMillis();
  validateTimer.update(endTime - startTime);
}
 
Example #28
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void genericProperties() {
    Schema actual = SchemaLoader.load(get("genericProperties"));
    assertEquals("myId", actual.getId());
    assertEquals("my title", actual.getTitle());
    assertEquals("my description", actual.getDescription());
}
 
Example #29
Source File: Validator.java    From daq with Apache License 2.0 5 votes vote down vote up
private void validateMessage(Schema schema, Object message) {
  final String stringMessage;
  try {
    stringMessage = OBJECT_MAPPER.writeValueAsString(message);
  } catch (Exception e) {
    throw new RuntimeException("While converting to string", e);
  }
  schema.validate(new JSONObject(new JSONTokener(stringMessage)));
}
 
Example #30
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);
  }
}