org.everit.json.schema.ArraySchema Java Examples

The following examples show how to use org.everit.json.schema.ArraySchema. 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: ArraySchemaLoader.java    From json-schema with Apache License 2.0 6 votes vote down vote up
ArraySchema.Builder load() {
    ArraySchema.Builder builder = ArraySchema.builder();
    ls.schemaJson().maybe("minItems").map(JsonValue::requireInteger).ifPresent(builder::minItems);
    ls.schemaJson().maybe("maxItems").map(JsonValue::requireInteger).ifPresent(builder::maxItems);
    ls.schemaJson().maybe("uniqueItems").map(JsonValue::requireBoolean).ifPresent(builder::uniqueItems);
    ls.schemaJson().maybe("additionalItems").ifPresent(maybe -> {
        maybe.canBe(Boolean.class, builder::additionalItems)
                .or(JsonObject.class, obj -> builder.schemaOfAdditionalItems(defaultLoader.loadChild(obj).build()))
                .requireAny();
    });
    ls.schemaJson().maybe("items").ifPresent(items -> {
        items.canBeSchema(itemSchema -> builder.allItemSchema(defaultLoader.loadChild(itemSchema).build()))
                .or(JsonArray.class, arr -> buildTupleSchema(builder, arr))
                .requireAny();
    });
    if (config.specVersion != DRAFT_4) {
        ls.schemaJson().maybe("contains").ifPresent(containedRawSchema -> addContainedSchema(builder, containedRawSchema));
    }
    return builder;
}
 
Example #2
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 #3
Source File: ArraySchemaDiff.java    From nakadi with MIT License 5 votes vote down vote up
private static void compareAttributes(
        final ArraySchema original, final ArraySchema update, final SchemaDiffState state) {
    if (!Objects.equals(original.getMaxItems(), update.getMaxItems())) {
        state.addChange("maxItems", ATTRIBUTE_VALUE_CHANGED);
    }

    if (!Objects.equals(original.getMinItems(), update.getMinItems())) {
        state.addChange("minItems", ATTRIBUTE_VALUE_CHANGED);
    }

    if (original.needsUniqueItems() != update.needsUniqueItems()) {
        state.addChange("uniqueItems", ATTRIBUTE_VALUE_CHANGED);
    }
}
 
Example #4
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void sniffByContains() {
    JSONObject schema = new JSONObject();
    schema.put("contains", new JSONObject());
    Schema actual = loadAsV6(schema);
    assertTrue(actual instanceof ArraySchema);
}
 
Example #5
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void sniffByContainsDoesNotAffectV4() {
    JSONObject schema = new JSONObject();
    schema.put("contains", new JSONObject());
    Schema actual = SchemaLoader.load(schema);
    assertFalse(actual instanceof ArraySchema);
}
 
Example #6
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void tupleSchema() {
    ArraySchema actual = (ArraySchema) SchemaLoader.load(get("tupleSchema"));
    assertFalse(actual.permitsAdditionalItems());
    assertNull(actual.getAllItemSchema());
    assertEquals(2, actual.getItemSchemas().size());
    assertEquals(BooleanSchema.INSTANCE, actual.getItemSchemas().get(0));
    assertEquals(NullSchema.INSTANCE, actual.getItemSchemas().get(1));
}
 
Example #7
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void arraySchema() {
    ArraySchema actual = (ArraySchema) SchemaLoader.load(get("arraySchema"));
    assertNotNull(actual);
    assertEquals(2, actual.getMinItems().intValue());
    assertEquals(3, actual.getMaxItems().intValue());
    assertTrue(actual.needsUniqueItems());
    assertEquals(NullSchema.INSTANCE, actual.getAllItemSchema());
}
 
Example #8
Source File: ArraySchemaDiff.java    From nakadi with MIT License 5 votes vote down vote up
private static void compareAdditionalItems(
        final ArraySchema original, final ArraySchema update, final SchemaDiffState state) {
    state.runOnPath("additionalItems", () -> {
        if (original.permitsAdditionalItems() != update.permitsAdditionalItems()) {
            state.addChange(ADDITIONAL_ITEMS_CHANGED);
        } else {
            SchemaDiff.recursiveCheck(original.getSchemaOfAdditionalItems(), update.getSchemaOfAdditionalItems(),
                    state);
        }
    });
}
 
Example #9
Source File: JsonSchemaFromFieldDescriptorsGeneratorTest.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Test
public void should_generate_schema_for_top_level_array() {
    givenFieldDescriptorWithTopLevelArray();

    whenSchemaGenerated();

    then(schema).isInstanceOf(ArraySchema.class);
    then(((ArraySchema) schema).getAllItemSchema().definesProperty("id")).isTrue();
    thenSchemaIsValid();
    thenSchemaValidatesJson("[{\"id\": \"some\"}]");
}
 
Example #10
Source File: JsonSchemaFromFieldDescriptorsGenerator.java    From restdocs-raml with MIT License 5 votes vote down vote up
private void handleEndOfPath(ObjectSchema.Builder builder, String propertyName, FieldDescriptor fieldDescriptor) {

        if (fieldDescriptor.isIgnored()) {
            // We don't need to render anything
        } else {
            if (isRequired(fieldDescriptor)) {
                builder.addRequiredProperty(propertyName);
            }
            if (fieldDescriptor.getType().equals(JsonFieldType.NULL) || fieldDescriptor.getType().equals(JsonFieldType.VARIES)) {
                builder.addPropertySchema(propertyName, NullSchema.builder()
                        .description((String) fieldDescriptor.getDescription())
                        .build());
            } else if (fieldDescriptor.getType().equals(JsonFieldType.OBJECT)) {
                builder.addPropertySchema(propertyName, ObjectSchema.builder()
                        .description((String) fieldDescriptor.getDescription())
                        .build());

            } else if (fieldDescriptor.getType().equals(JsonFieldType.ARRAY)) {
                builder.addPropertySchema(propertyName, ArraySchema.builder()
                        .description((String) fieldDescriptor.getDescription())
                        .build());
            } else if (fieldDescriptor.getType().equals(JsonFieldType.BOOLEAN)) {
                builder.addPropertySchema(propertyName, BooleanSchema.builder()
                        .description((String) fieldDescriptor.getDescription())
                        .build());
            } else if (fieldDescriptor.getType().equals(JsonFieldType.NUMBER)) {
                builder.addPropertySchema(propertyName, NumberSchema.builder()
                        .description((String) fieldDescriptor.getDescription())
                        .build());
            } else if (fieldDescriptor.getType().equals(JsonFieldType.STRING)) {
                builder.addPropertySchema(propertyName, StringSchema.builder()
                        .minLength(minLengthString(fieldDescriptor))
                        .maxLength(maxLengthString(fieldDescriptor))
                        .description((String) fieldDescriptor.getDescription())
                        .build());
            } else {
                throw new IllegalArgumentException("unknown field type " + fieldDescriptor.getType());
            }
        }
    }
 
Example #11
Source File: JsonSchemaFromFieldDescriptorsGenerator.java    From restdocs-raml with MIT License 5 votes vote down vote up
private void processRemainingSegments(ObjectSchema.Builder builder, String propertyName, List<String> traversedSegments, List<JsonFieldPath> fields, String description) {
    List<String> remainingSegments = fields.get(0).remainingSegments(traversedSegments);
    if (remainingSegments.size() > 0 && isArraySegment(remainingSegments.get(0))) {
        traversedSegments.add(remainingSegments.get(0));
        builder.addPropertySchema(propertyName, ArraySchema.builder()
                .allItemSchema(traverse(traversedSegments, fields, ObjectSchema.builder()))
                .description(description)
                .build());
    } else {
        builder.addPropertySchema(propertyName, traverse(traversedSegments, fields, (ObjectSchema.Builder) ObjectSchema.builder()
                .description(description)));
    }
}
 
Example #12
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 #13
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 #14
Source File: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void visitArraySchema(ArraySchemaWrapper arraySchema) {
    if (original instanceof FalseSchema)
        return; // FalseSchema matches nothing

    if (!(original instanceof ArraySchema)) {
        ctx.addDifference(SUBSCHEMA_TYPE_CHANGED, original, arraySchema);
        return;
    }
    arraySchema.accept(new ArraySchemaDiffVisitor(ctx, (ArraySchema) original));
}
 
Example #15
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void v6LoaderSupportsContains() {
    ArraySchema result = (ArraySchema) loadAsV6(get("arrayWithContains"));
    assertNotNull(result.getContainedItemSchema());
}
 
Example #16
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void itemsCanBeBooleanInV6() {
    ArraySchema actual = (ArraySchema) loadAsV6(get("itemsAsBoolean"));
    assertEquals(TrueSchema.builder().build(), actual.getAllItemSchema());
}
 
Example #17
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void v4LoaderDoesNotSupportContains() {
    ArraySchema result = (ArraySchema) SchemaLoader.load(get("arrayWithContains"));
    assertNull(result.getContainedItemSchema());
}
 
Example #18
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void arrayByItems() {
    ArraySchema actual = (ArraySchema) SchemaLoader.load(get("arrayByItems"));
    assertNotNull(actual);
}
 
Example #19
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void arrayByAdditionalItems() {
    ArraySchema actual = (ArraySchema) SchemaLoader.load(get("arrayByAdditionalItems"));
    Assert.assertFalse(actual.requiresArray());
}
 
Example #20
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void additionalItemSchema() {
    assertTrue(SchemaLoader.load(get("additionalItemSchema")) instanceof ArraySchema);
}
 
Example #21
Source File: ArraySchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public ArraySchemaDiffVisitor(DiffContext ctx, ArraySchema original) {
    this.ctx = ctx;
    this.original = original;
}
 
Example #22
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void jsonPointerInArray() {
    assertTrue(SchemaLoader.load(get("jsonPointerInArray")) instanceof ArraySchema);
}
 
Example #23
Source File: ArraySchemaLoader.java    From json-schema with Apache License 2.0 4 votes vote down vote up
private void buildTupleSchema(ArraySchema.Builder builder, JsonArray itemSchema) {
    itemSchema.forEach((i, subschema) -> {
        builder.addItemSchema(defaultLoader.loadChild(subschema).build());
    });
}
 
Example #24
Source File: ArraySchemaLoader.java    From json-schema with Apache License 2.0 4 votes vote down vote up
private void addContainedSchema(ArraySchema.Builder builder, JsonValue schemaJson) {
    builder.containsItemSchema(defaultLoader.loadChild(schemaJson).build());
}
 
Example #25
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 4 votes vote down vote up
ArraySchema.Builder buildArraySchema() {
    config().specVersion.arrayKeywords().forEach(consumedKeys::keyConsumed);
    return new ArraySchemaLoader(schemaJson.ls, config(), defaultLoader).load();
}
 
Example #26
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 #27
Source File: ArraySchemaDiff.java    From nakadi with MIT License 4 votes vote down vote up
private static void compareItemSchemaObject(
        final ArraySchema original, final ArraySchema update, final SchemaDiffState state) {
    state.runOnPath("items", () -> {
        SchemaDiff.recursiveCheck(original.getAllItemSchema(), update.getAllItemSchema(), state);
    });
}
 
Example #28
Source File: JsonSchemaFromFieldDescriptorsGeneratorTest.java    From restdocs-raml with MIT License 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void should_generate_complex_schema() throws IOException {
    givenFieldDescriptorsWithConstraints();

    whenSchemaGenerated();

    then(schema).isInstanceOf(ObjectSchema.class);
    ObjectSchema objectSchema = (ObjectSchema) schema;
    then(objectSchema.definesProperty("id"));
    then(objectSchema.getPropertySchemas().get("id")).isInstanceOf(StringSchema.class);
    then(objectSchema.getRequiredProperties()).contains("id");

    then(objectSchema.definesProperty("shippingAddress"));
    Schema shippingAddressSchema = objectSchema.getPropertySchemas().get("shippingAddress");
    then(shippingAddressSchema).isInstanceOf(ObjectSchema.class);
    then(shippingAddressSchema.getDescription()).isNotEmpty();

    then(objectSchema.definesProperty("billingAddress"));
    ObjectSchema billingAddressSchema = (ObjectSchema) objectSchema.getPropertySchemas().get("billingAddress");
    then(billingAddressSchema).isInstanceOf(ObjectSchema.class);
    then(billingAddressSchema.getDescription()).isNotEmpty();
    then(billingAddressSchema.definesProperty("firstName")).isTrue();
    then(billingAddressSchema.getRequiredProperties().contains("firstName"));
    StringSchema firstNameSchema = (StringSchema) billingAddressSchema.getPropertySchemas().get("firstName");
    then(firstNameSchema.getMinLength()).isEqualTo(1);
    then(firstNameSchema.getMaxLength()).isNull();

    then(billingAddressSchema.definesProperty("valid")).isTrue();

    then(objectSchema.getPropertySchemas().get("lineItems")).isInstanceOf(ArraySchema.class);
    ArraySchema lineItemSchema = (ArraySchema) objectSchema.getPropertySchemas().get("lineItems");
    then(lineItemSchema.getDescription()).isNull();

    then(lineItemSchema.getAllItemSchema().definesProperty("name")).isTrue();
    StringSchema nameSchema = (StringSchema) ((ObjectSchema) lineItemSchema.getAllItemSchema()).getPropertySchemas().get("name");
    then(nameSchema.getMinLength()).isEqualTo(2);
    then(nameSchema.getMaxLength()).isEqualTo(255);

    then(lineItemSchema.getAllItemSchema().definesProperty("_id")).isTrue();
    then(lineItemSchema.getAllItemSchema().definesProperty("quantity")).isTrue();
    ObjectSchema quantitySchema = (ObjectSchema) ((ObjectSchema) lineItemSchema.getAllItemSchema()).getPropertySchemas().get("quantity");
    then(quantitySchema.getRequiredProperties()).contains("value");

    then(lineItemSchema.getAllItemSchema()).isInstanceOf(ObjectSchema.class);

    thenSchemaIsValid();
    thenSchemaValidatesJson("{\n" +
            "    \"id\": \"1\",\n" +
            "    \"lineItems\": [\n" +
            "        {\n" +
            "            \"name\": \"some\",\n" +
            "            \"_id\": \"2\",\n" +
            "            \"quantity\": {\n" +
            "                \"value\": 1,\n" +
            "                \"unit\": \"PIECES\"\n" +
            "            }\n" +
            "        }\n" +
            "    ],\n" +
            "    \"billingAddress\": {\n" +
            "        \"firstName\": \"some\",\n" +
            "        \"valid\": true\n" +
            "    },\n" +
            "    \"paymentLineItem\": {\n" +
            "        \"lineItemTaxes\": [\n" +
            "            {\n" +
            "                \"value\": 1\n" +
            "            }\n" +
            "        ]\n" +
            "    }\n" +
            "}");
}
 
Example #29
Source File: ArraySchemaWrapper.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public ArraySchemaWrapper(ArraySchema wrapped) {
    this.wrapped = wrapped;
}
 
Example #30
Source File: ArraySchemaDiff.java    From nakadi with MIT License 3 votes vote down vote up
static void recursiveCheck(final ArraySchema original, final ArraySchema update, final SchemaDiffState state) {
    compareItemSchemaObject(original, update, state);

    compareItemSchemaArray(original, update, state);

    compareAdditionalItems(original, update, state);

    compareAttributes(original, update, state);
}