org.everit.json.schema.StringSchema Java Examples

The following examples show how to use org.everit.json.schema.StringSchema. 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: SchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void visitStringSchema(StringSchemaWrapper stringSchema) {
    Schema subschema = getCompatibleSubschemaOrOriginal(original, stringSchema); // In case of enum

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

    if (!(subschema instanceof StringSchema)) {
        ctx.addDifference(SUBSCHEMA_TYPE_CHANGED, subschema, stringSchema);
        return;
    }
    // ctx is assumed to already contain the path
    stringSchema.accept(new StringSchemaDiffVisitor(ctx, (StringSchema) subschema));
}
 
Example #2
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void sniffByFormat() {
    JSONObject schema = new JSONObject();
    schema.put("format", "hostname");
    Schema actual = SchemaLoader.builder().schemaJson(schema).build().load().build();
    assertTrue(actual instanceof StringSchema);
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: StringSchemaLoader.java    From json-schema with Apache License 2.0 5 votes vote down vote up
public StringSchema.Builder load() {
    StringSchema.Builder builder = StringSchema.builder();
    ls.schemaJson().maybe("minLength").map(JsonValue::requireInteger).ifPresent(builder::minLength);
    ls.schemaJson().maybe("maxLength").map(JsonValue::requireInteger).ifPresent(builder::maxLength);
    ls.schemaJson().maybe("pattern").map(JsonValue::requireString)
            .map(ls.config.regexpFactory::createHandler)
            .ifPresent(builder::pattern);
    ls.schemaJson().maybe("format").map(JsonValue::requireString)
            .ifPresent(format -> addFormatValidator(builder, format));
    return builder;
}
 
Example #8
Source File: StringSchemaDiff.java    From nakadi with MIT License 5 votes vote down vote up
static void recursiveCheck(final StringSchema stringSchemaOriginal, final StringSchema stringSchemaUpdate,
                           final SchemaDiffState state) {
    if (!Objects.equals(stringSchemaOriginal.getMaxLength(), stringSchemaUpdate.getMaxLength())) {
        state.addChange("maxLength", ATTRIBUTE_VALUE_CHANGED);
    } else if (!Objects.equals(stringSchemaOriginal.getMinLength(), stringSchemaUpdate.getMinLength())) {
        state.addChange("minLength", ATTRIBUTE_VALUE_CHANGED);
    } else if (stringSchemaOriginal.getPattern() != null && stringSchemaUpdate.getPattern() != null
            && !stringSchemaOriginal.getPattern().pattern().equals(stringSchemaUpdate.getPattern().pattern())) {
        state.addChange("pattern", ATTRIBUTE_VALUE_CHANGED);
    }
}
 
Example #9
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 #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: 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 #12
Source File: SchemaExtractor.java    From json-schema with Apache License 2.0 4 votes vote down vote up
StringSchema.Builder buildStringSchema() {
    PropertySnifferSchemaExtractor.STRING_SCHEMA_PROPS.forEach(consumedKeys::keyConsumed);
    return new StringSchemaLoader(schemaJson.ls, config().formatValidators).load();
}
 
Example #13
Source File: StringSchemaLoader.java    From json-schema with Apache License 2.0 4 votes vote down vote up
private void addFormatValidator(StringSchema.Builder builder, String formatName) {
    FormatValidator formatValidator = formatValidators.get(formatName);
    if (formatValidator != null) {
        builder.formatValidator(formatValidator);
    }
}
 
Example #14
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 #15
Source File: StringSchemaWrapper.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public StringSchemaWrapper(StringSchema wrapped) {
    this.wrapped = wrapped;
}
 
Example #16
Source File: StringSchemaDiffVisitor.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
public StringSchemaDiffVisitor(DiffContext ctx, StringSchema original) {
    this.ctx = ctx;
    this.original = original;
}
 
Example #17
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void stringSchema() {
    StringSchema actual = (StringSchema) SchemaLoader.load(get("stringSchema"));
    assertEquals(2, actual.getMinLength().intValue());
    assertEquals(3, actual.getMaxLength().intValue());
}
 
Example #18
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void stringSchemaWithFormat() {
    StringSchema subject = (StringSchema) SchemaLoader.load(get("stringSchemaWithFormat"));
    TestSupport.expectFailure(subject, "asd");
}