org.everit.json.schema.CombinedSchema Java Examples

The following examples show how to use org.everit.json.schema.CombinedSchema. 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: CombinedSchemaDiff.java    From nakadi with MIT License 6 votes vote down vote up
static void recursiveCheck(final CombinedSchema combinedSchemaOriginal, final CombinedSchema combinedSchemaUpdate,
                           final SchemaDiffState state) {
    if (combinedSchemaOriginal.getSubschemas().size() != combinedSchemaUpdate.getSubschemas().size()) {
        state.addChange(SUB_SCHEMA_CHANGED);
    } else {
        if (!combinedSchemaOriginal.getCriterion().equals(combinedSchemaUpdate.getCriterion())) {
            state.addChange(COMPOSITION_METHOD_CHANGED);
        } else {
            final Iterator<Schema> originalIterator = combinedSchemaOriginal.getSubschemas().iterator();
            final Iterator<Schema> updateIterator = combinedSchemaUpdate.getSubschemas().iterator();
            int index = 0;
            while (originalIterator.hasNext()) {
                state.runOnPath(validationCriteria(combinedSchemaOriginal.getCriterion()) + "/" + index, () -> {
                    SchemaDiff.recursiveCheck(originalIterator.next(), updateIterator.next(), state);
                });
                index += 1;
            }
        }
    }
}
 
Example #3
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 5 votes vote down vote up
private CombinedSchema.Builder buildAnyOfSchemaForMultipleTypes() {
    JsonArray subtypeJsons = require("type").requireArray();
    Collection<Schema> subschemas = new ArrayList<>(subtypeJsons.length());
    subtypeJsons.forEach((j, raw) -> {
        subschemas.add(loadForExplicitType(raw.requireString()).build());
    });
    return CombinedSchema.anyOf(subschemas);
}
 
Example #4
Source File: CombinedSchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void combinedSchemaWithExplicitBaseSchema() {
    CombinedSchema actual = (CombinedSchema) SchemaLoader
            .load(get("combinedSchemaWithExplicitBaseSchema"));
    assertEquals(1, actual.getSubschemas().stream()
            .filter(schema -> schema instanceof StringSchema).count());
    assertEquals(1, actual.getSubschemas().stream()
            .filter(schema -> schema instanceof CombinedSchema).count());
}
 
Example #5
Source File: CombinedSchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void combinedSchemaWithBaseSchema() {
    CombinedSchema actual = (CombinedSchema) SchemaLoader.load(get("combinedSchemaWithBaseSchema"));
    assertEquals(1, actual.getSubschemas().stream()
            .filter(schema -> schema instanceof StringSchema).count());
    assertEquals(1, actual.getSubschemas().stream()
            .filter(schema -> schema instanceof CombinedSchema).count());
}
 
Example #6
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 #7
Source File: JsonSchemaWrapperVisitor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
public void visitCombinedSchema(CombinedSchemaWrapper combinedSchema) {
    visitSchema(combinedSchema);
    // Assuming constants, i.e. we can use '==' operator
    final ValidationCriterion criterion = combinedSchema.getCriterion();
    if (CombinedSchema.ALL_CRITERION == criterion) {
        visitAllOfCombinedSchema(combinedSchema);
    } else if (CombinedSchema.ANY_CRITERION == criterion) {
        visitAnyOfCombinedSchema(combinedSchema);
    } else if (CombinedSchema.ONE_CRITERION == criterion) {
        visitOneOfCombinedSchema(combinedSchema);
    } else {
        throw new IllegalStateException("Could not determine if the combined schema is " +
            "'allOf', 'anyOf', or 'oneOf': " + combinedSchema);
    }
}
 
Example #8
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void implicitAnyOfLoadsTypeProps() {
    CombinedSchema schema = (CombinedSchema) SchemaLoader.load(get("multipleTypesWithProps"));
    StringSchema stringSchema = schema.getSubschemas().stream()
            .filter(sub -> sub instanceof StringSchema)
            .map(sub -> (StringSchema) sub)
            .findFirst().orElseThrow(() -> new AssertionError("no StringSchema"));
    NumberSchema numSchema = schema.getSubschemas().stream()
            .filter(sub -> sub instanceof NumberSchema)
            .map(sub -> (NumberSchema) sub)
            .findFirst()
            .orElseThrow(() -> new AssertionError("no NumberSchema"));
    assertEquals(3, stringSchema.getMinLength().intValue());
    assertEquals(5, numSchema.getMinimum().intValue());
}
 
Example #9
Source File: CombinedSchemaDiff.java    From nakadi with MIT License 5 votes vote down vote up
private static String validationCriteria(final CombinedSchema.ValidationCriterion criterion) {
    if (criterion.equals(CombinedSchema.ALL_CRITERION)) {
        return "allOf";
    } else if (criterion.equals(CombinedSchema.ANY_CRITERION)) {
        return "anyOf";
    } else {
        return "oneOf";
    }
}
 
Example #10
Source File: WrapUtil.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
public static SchemaWrapper wrap(Schema schema) {
    if (schema == null)
        return null;

    if (schema instanceof ObjectSchema) {
        return new ObjectSchemaWrapper((ObjectSchema) schema);
    } else if (schema instanceof ArraySchema) {
        return new ArraySchemaWrapper((ArraySchema) schema);
    } else if (schema instanceof StringSchema) {
        return new StringSchemaWrapper((StringSchema) schema);
    } else if (schema instanceof EmptySchema && !(schema instanceof TrueSchema)) {
        return new EmptySchemaWrapper((EmptySchema) schema);
    } else if (schema instanceof TrueSchema) {
        return new TrueSchemaWrapper((TrueSchema) schema);
    } else if (schema instanceof FalseSchema) {
        return new FalseSchemaWrapper((FalseSchema) schema);
    } else if (schema instanceof BooleanSchema) {
        return new BooleanSchemaWrapper((BooleanSchema) schema);
    } else if (schema instanceof ConstSchema) {
        return new ConstSchemaWrapper((ConstSchema) schema);
    } else if (schema instanceof EnumSchema) {
        return new EnumSchemaWrapper((EnumSchema) schema);
    } else if (schema instanceof NullSchema) {
        return new NullSchemaWrapper((NullSchema) schema);
    } else if (schema instanceof NotSchema) {
        return new NotSchemaWrapper((NotSchema) schema);
    } else if (schema instanceof ReferenceSchema) {
        return new ReferenceSchemaWrapper((ReferenceSchema) schema);
    } else if (schema instanceof CombinedSchema) {
        return new CombinedSchemaWrapper((CombinedSchema) schema);
    } else if (schema instanceof ConditionalSchema) {
        return new ConditionalSchemaWrapper((ConditionalSchema) schema);
    } else if (schema instanceof NumberSchema) {
        return new NumberSchemaWrapper((NumberSchema) schema);
    } else {
        throw new IllegalStateException("No wrapper for an underlying schema type '" + schema.getClass() + "': " + schema);
    }
}
 
Example #11
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void commonPropsGoIntoWrappingAllOf() {
    CombinedSchema actual = (CombinedSchema) SchemaLoader.load(get("syntheticAllOfWithCommonProps"));
    assertEquals(CombinedSchema.ALL_CRITERION, actual.getCriterion());
    assertEquals("http://id", actual.getId());
    assertEquals("my title", actual.getTitle());
    assertEquals("my description", actual.getDescription());
    assertNull(actual.getSubschemas().iterator().next().getId());
}
 
Example #12
Source File: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void visitCombinedSchema(CombinedSchemaWrapper schema) {
    if (original instanceof FalseSchema)
        return; // FalseSchema matches nothing

    if (!(original instanceof CombinedSchema)) {
        ctx.addDifference(SUBSCHEMA_TYPE_CHANGED, original, schema);
        return;
    }
    schema.accept(new CombinedSchemaDiffVisitor(ctx, (CombinedSchema) original));
}
 
Example #13
Source File: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
/**
 * In case of e.g. enum of strings (with type property defined as "string"),
 * the schema is not an EnumSchema or a StringSchema, but a CombinedSchema of both.
 * <p>
 * If original is Combined and updated is not, the backwards compatibility is
 * satisfied iff the Combined schema contains a schema that is compatible with updated (and their type matches).
 * <p>
 * This should only work for allOf criterion however.
 */
private Schema getCompatibleSubschemaOrOriginal(Schema original, SchemaWrapper updated) {
    requireNonNull(original);
    requireNonNull(updated);
    if (original instanceof CombinedSchema) {
        Set<Schema> typeCompatible = ((CombinedSchema) original).getSubschemas().stream()
            .filter(s -> s.getClass().isInstance(updated.getWrapped()))
            .collect(Collectors.toSet());
        if (ALL_CRITERION.equals(((CombinedSchema) original).getCriterion()) && typeCompatible.size() == 1)
            return typeCompatible.stream().findAny().get();
    }
    return original;
}
 
Example #14
Source File: DefinesPropertyTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void definesPropertyIfSubschemaMatchCountIsAcceptedByCriterion() {
    CombinedSchema subject = CombinedSchema.builder()
            .subschema(ObjectSchema.builder().addPropertySchema("a", BooleanSchema.INSTANCE).build())
            .subschema(ObjectSchema.builder().addPropertySchema("b", BooleanSchema.INSTANCE).build())
            .criterion((subschemaCount, matchingSubschemaCount) -> {
                if (matchingSubschemaCount == 1 && subschemaCount == 2) {
                    // dummy exception
                    throw new ValidationException(Object.class, new Object());
                }
            })
            .build();
    assertFalse(subject.definesProperty("a"));
}
 
Example #15
Source File: CombinedSchemaMatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaMatchEvent(CombinedSchema schema, Schema subSchema,
        Object instance) {
    super(schema, subSchema, instance);
}
 
Example #16
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void neverMatchingAnyOf() {
    assertTrue(SchemaLoader.load(get("anyOfNeverMatches")) instanceof CombinedSchema);
}
 
Example #17
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void multipleTypes() {
    assertTrue(SchemaLoader.load(get("multipleTypes")) instanceof CombinedSchema);
}
 
Example #18
Source File: CombinedSchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void combinedSchemaWithMultipleBaseSchemas() {
    Schema actual = SchemaLoader.load(get("combinedSchemaWithMultipleBaseSchemas"));
    assertTrue(actual instanceof CombinedSchema);
}
 
Example #19
Source File: CombinedSchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void combinedSchemaLoading() {
    CombinedSchema actual = (CombinedSchema) SchemaLoader.load(get("combinedSchema"));
    Assert.assertNotNull(actual);
}
 
Example #20
Source File: CombinedSchemaMismatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaMismatchEvent(CombinedSchema schema, Schema subSchema, Object instance, ValidationException failure) {
    super(schema, subSchema, instance);
    this.failure = failure;
}
 
Example #21
Source File: CombinedSchemaValidationEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaValidationEvent(CombinedSchema schema, Schema subSchema, Object instance) {
    super(schema, instance);
    this.subSchema = subSchema;
}
 
Example #22
Source File: CombinedSchemaLoader.java    From json-schema with Apache License 2.0 4 votes vote down vote up
private CombinedSchema.Builder loadCombinedSchemaForKeyword(JsonObject schemaJson, String key) {
    Collection<Schema> subschemas = new ArrayList<>();
    schemaJson.require(key).requireArray()
            .forEach((i, subschema) -> subschemas.add(defaultLoader.loadChild(subschema).build()));
    return COMB_SCHEMA_PROVIDERS.get(key).apply(subschemas);
}
 
Example #23
Source File: SchemaDiff.java    From nakadi with MIT License 4 votes vote down vote up
static void recursiveCheck(
        final Schema originalIn,
        final Schema updateIn,
        final SchemaDiffState state) {

    if (originalIn == null && updateIn == null) {
        return;
    }

    if (updateIn == null) {
        state.addChange(SCHEMA_REMOVED);
        return;
    }

    if (originalIn == null) {
        state.addChange(SCHEMA_REMOVED);
        return;
    }

    final Schema original;
    final Schema update;
    if (!originalIn.getClass().equals(updateIn.getClass())) {
        // Tricky part. EmptySchema is the same as an empty ObjectSchema.
        if (originalIn instanceof EmptySchema && updateIn instanceof ObjectSchema) {
            original = replaceWithEmptyObjectSchema(originalIn);
            update = updateIn;
        } else if (typeNarrowed(originalIn, updateIn)) {
            state.addChange(TYPE_NARROWED);
            return;
        } else {
            state.addChange(TYPE_CHANGED);
            return;
        }
    } else {
        original = originalIn;
        update = updateIn;
    }

    state.analyzeSchema(originalIn, () -> {
        if (!Objects.equals(original.getId(), update.getId())) {
            state.addChange(ID_CHANGED);
        }

        if (!Objects.equals(original.getTitle(), update.getTitle())) {
            state.addChange(TITLE_CHANGED);
        }

        if (!Objects.equals(original.getDescription(), update.getDescription())) {
            state.addChange(DESCRIPTION_CHANGED);
        }

        if (original instanceof StringSchema) {
            StringSchemaDiff.recursiveCheck((StringSchema) original, (StringSchema) update, state);
        } else if (original instanceof NumberSchema) {
            NumberSchemaDiff.recursiveCheck((NumberSchema) original, (NumberSchema) update, state);
        } else if (original instanceof EnumSchema) {
            EnumSchemaDiff.recursiveCheck((EnumSchema) original, (EnumSchema) update, state);
        } else if (original instanceof CombinedSchema) {
            CombinedSchemaDiff.recursiveCheck((CombinedSchema) original, (CombinedSchema) update, state);
        } else if (original instanceof ObjectSchema) {
            ObjectSchemaDiff.recursiveCheck((ObjectSchema) original, (ObjectSchema) update, state);
        } else if (original instanceof ArraySchema) {
            ArraySchemaDiff.recursiveCheck((ArraySchema) original, (ArraySchema) update, state);
        } else if (original instanceof ReferenceSchema) {
            ReferenceSchemaDiff.recursiveCheck((ReferenceSchema) original, (ReferenceSchema) update, state);
        }
    });
}
 
Example #24
Source File: CombinedSchemaWrapper.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaWrapper(CombinedSchema wrapped) {
    this.wrapped = wrapped;
}
 
Example #25
Source File: CombinedSchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaDiffVisitor(DiffContext ctx, CombinedSchema original) {
    this.ctx = ctx;
    this.original = original;
}