io.swagger.v3.oas.models.media.MapSchema Java Examples

The following examples show how to use io.swagger.v3.oas.models.media.MapSchema. 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: SpringDocHateoasConfiguration.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an OpenApiCustomiser and a jackson mixin to ensure the definition of `Links` matches the serialized
 * output. This is done because the customer serializer converts the data to a map before serializing it.
 *
 * @param halProvider the hal provider
 * @return the open api customiser
 * @see org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider) org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
OpenApiCustomiser linksSchemaCustomiser(HateoasHalProvider halProvider) {
	if (!halProvider.isHalEnabled()) {
		return openApi -> {
		};
	}
	Json.mapper().addMixIn(RepresentationModel.class, RepresentationModelLinksOASMixin.class);

	ResolvedSchema resolvedLinkSchema = ModelConverters.getInstance()
			.resolveAsResolvedSchema(new AnnotatedType(Link.class));

	return openApi -> openApi
			.schema("Link", resolvedLinkSchema.schema)
			.schema("Links", new MapSchema()
					.additionalProperties(new StringSchema())
					.additionalProperties(new ObjectSchema().$ref(AnnotationsUtils.COMPONENTS_REF +"Link")));
}
 
Example #2
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private Set<String> collectImportsFromSchema(Schema schema) {
    Set<String> imports = new HashSet<>();
    if (GeneratorUtils.isNotBlank(schema.get$ref())) {
        imports.add(getSimpleRef(schema.get$ref()));
    }
    if (schema instanceof ArraySchema) {
        imports.addAll(collectImportsFromSchema(
                ((ArraySchema) schema).getItems()));
    } else if (schema instanceof MapSchema
            || schema.getAdditionalProperties() instanceof Schema) {
        imports.addAll(collectImportsFromSchema(
                (Schema) schema.getAdditionalProperties()));
    } else if (schema instanceof ComposedSchema) {
        for (Schema child : ((ComposedSchema) schema).getAllOf()) {
            imports.addAll(collectImportsFromSchema(child));
        }
    }
    if (schema.getProperties() != null) {
        schema.getProperties().values().forEach(
                o -> imports.addAll(collectImportsFromSchema((Schema) o)));
    }
    return imports;
}
 
Example #3
Source File: SchemaResolverTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNotNullableMap_When_GivenTypeIsAMap() {
    ResolvedType resolvedType = mockReferencedTypeOf(Map.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();
    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = new LinkedList<>();
    pairs.add(null);
    pairs.add(new Pair<>(null, mockReferencedTypeOf(Number.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof MapSchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            schema.getAdditionalProperties() instanceof NumberSchema);

    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example #4
Source File: JavaResteasyEapServerCodegenModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a simple java model with java8 types")
public void mapModelTest() {
    final Schema model = new Schema()
            .description("A model with a map")
            .addProperties("map", new MapSchema());

    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    assertEquals(cm.vars.get(0).baseType, "Map");
    assertTrue(cm.imports.contains("HashMap"));
}
 
Example #5
Source File: JavaJaxrsResteasyServerCodegenModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a simple java model with java8 types")
public void mapModelTest() {
    final Schema model = new Schema()
            .description("A model with a map")
            .addProperties("map", new MapSchema());

    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    assertEquals(cm.vars.get(0).baseType, "Map");
    assertTrue(cm.imports.contains("HashMap"));
}
 
Example #6
Source File: DartDioModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("translations", new MapSchema()
                    .additionalProperties(new StringSchema()))
            .addRequiredItem("id");
    final DefaultCodegen codegen = new DartDioClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "translations");
    Assert.assertEquals(property1.dataType, "BuiltMap<String, String>");
    Assert.assertEquals(property1.name, "translations");
    Assert.assertEquals(property1.baseType, "BuiltMap");
    Assert.assertEquals(property1.containerType, "map");
    Assert.assertFalse(property1.required);
    Assert.assertTrue(property1.isContainer);
    Assert.assertTrue(property1.isPrimitiveType);
}
 
Example #7
Source File: DartDioModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a model with complex map property")
public void complexMapSchema() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("children", new MapSchema()
                    .additionalProperties(new Schema().$ref("#/definitions/Children")));
    final DefaultCodegen codegen = new DartDioClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 1);
    // {{imports}} is not used in template
    //Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "children");
    Assert.assertEquals(property1.complexType, "Children");
    Assert.assertEquals(property1.dataType, "BuiltMap<String, Children>");
    Assert.assertEquals(property1.name, "children");
    Assert.assertEquals(property1.baseType, "BuiltMap");
    Assert.assertEquals(property1.containerType, "map");
    Assert.assertFalse(property1.required);
    Assert.assertTrue(property1.isContainer);
}
 
Example #8
Source File: AbstractGoCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void getTypeDeclarationTest() {
    final AbstractGoCodegen codegen = new P_AbstractGoCodegen();

    // Create an alias to an array schema
    Schema<?> nestedArraySchema = new ArraySchema().items(new IntegerSchema().format("int32"));
    codegen.setOpenAPI(new OpenAPI().components(new Components().addSchemas("NestedArray", nestedArraySchema)));

    // Create an array schema with item type set to the array alias
    Schema<?> schema = new ArraySchema().items(new Schema().$ref("#/components/schemas/NestedArray"));

    ModelUtils.setGenerateAliasAsModel(false);
    String defaultValue = codegen.getTypeDeclaration(schema);
    Assert.assertEquals(defaultValue, "[][]int32");

    ModelUtils.setGenerateAliasAsModel(true);
    defaultValue = codegen.getTypeDeclaration(schema);
    Assert.assertEquals(defaultValue, "[]NestedArray");

    // Create a map schema with additionalProperties type set to array alias
    schema = new MapSchema().additionalProperties(new Schema().$ref("#/components/schemas/NestedArray"));

    ModelUtils.setGenerateAliasAsModel(false);
    defaultValue = codegen.getTypeDeclaration(schema);
    Assert.assertEquals(defaultValue, "map[string][]int32");

    ModelUtils.setGenerateAliasAsModel(true);
    defaultValue = codegen.getTypeDeclaration(schema);
    Assert.assertEquals(defaultValue, "map[string]NestedArray");
}
 
Example #9
Source File: DataGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public boolean isSupported(Schema<?> schema) {
    return schema instanceof ArraySchema
            || schema instanceof BooleanSchema
            || schema instanceof FileSchema
            || schema instanceof IntegerSchema
            || schema instanceof MapSchema
            || schema instanceof NumberSchema
            || schema instanceof StringSchema;
}
 
Example #10
Source File: SchemaResolver.java    From flow with Apache License 2.0 5 votes vote down vote up
private Schema createMapSchema(ResolvedType type) {
    Schema mapSchema = new MapSchema();
    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParametersMap = type
            .asReferenceType().getTypeParametersMap();
    if (typeParametersMap.size() == 2) {
        // Assumed that Map always has the first type parameter as `String`
        // and
        // the second is for its value type
        ResolvedType mapValueType = typeParametersMap.get(1).b;
        mapSchema.additionalProperties(
                parseResolvedTypeToSchema(mapValueType));
    }
    return mapSchema;
}
 
Example #11
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Map<String, ResolvedReferenceType> collectUsedTypesFromSchema(
        Schema schema) {
    Map<String, ResolvedReferenceType> map = new HashMap<>();
    if (GeneratorUtils.isNotBlank(schema.getName())
            || GeneratorUtils.isNotBlank(schema.get$ref())) {
        String name = GeneratorUtils.firstNonBlank(schema.getName(),
                schemaResolver.getSimpleRef(schema.get$ref()));
        ResolvedReferenceType resolvedReferenceType = schemaResolver
                .getFoundTypeByQualifiedName(name);
        if (resolvedReferenceType != null) {
            map.put(name, resolvedReferenceType);
        } else {
            getLogger().info(
                    "Can't find the type information of class '{}'. "
                            + "This might result in a missing schema in the generated OpenAPI spec.",
                    name);
        }
    }
    if (schema instanceof ArraySchema) {
        map.putAll(collectUsedTypesFromSchema(
                ((ArraySchema) schema).getItems()));
    } else if (schema instanceof MapSchema
            && schema.getAdditionalProperties() != null) {
        map.putAll(collectUsedTypesFromSchema(
                (Schema) schema.getAdditionalProperties()));
    } else if (schema instanceof ComposedSchema
            && ((ComposedSchema) schema).getAllOf() != null) {
            for (Schema child : ((ComposedSchema) schema).getAllOf()) {
                map.putAll(collectUsedTypesFromSchema(child));
            }
    }
    if (schema.getProperties() != null) {
        schema.getProperties().values().forEach(
                o -> map.putAll(collectUsedTypesFromSchema((Schema) o)));
    }
    return map;
}
 
Example #12
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdditionalPropertiesBoolean() {
    String yaml =
        "openapi: 3.0.0\n" +
        "info:\n" +
        "  title: Test\n" +
        "  version: 1.0.0\n" +
        "paths:\n" +
        "  \"/store/inventory\":\n" +
        "    post:\n" +
        "      requestBody:\n" +
        "        content:\n" +
        "          application/json:\n" +
        "            schema:\n" +
        "              additionalProperties: true\n" +
        "      responses:\n" +
        "        '200':\n" +
        "          description: successful operation\n" +
        "          content:\n" +
        "            application/json:\n" +
        "              schema:\n" +
        "                additionalProperties: false\n";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    assertEquals(result.getMessages(), emptyList());
    
    OpenAPI openAPI = result.getOpenAPI();

    Schema body = openAPI.getPaths().get("/store/inventory").getPost().getRequestBody().getContent().get("application/json").getSchema();
    assertEquals(body.getAdditionalProperties(), Boolean.TRUE);
    assertEquals(body.getClass(), MapSchema.class);

    Schema response = openAPI.getPaths().get("/store/inventory").getPost().getResponses().get("200").getContent().get("application/json").getSchema();
    assertEquals(response.getAdditionalProperties(), Boolean.FALSE);
    assertEquals(response.getClass(), ObjectSchema.class);
}
 
Example #13
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1071() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);

    SwaggerParseResult parseResult = new OpenAPIV3Parser().readLocation("issue-1071.yaml", null, options);
    OpenAPI apispec = parseResult.getOpenAPI();
    assertNotNull(apispec);
    Schema test = apispec.getPaths().get("/mapschema").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(test instanceof MapSchema);
}
 
Example #14
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1071True() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseResult = new OpenAPIV3Parser().readLocation("issue-1071-true.yaml", null, options);
    OpenAPI apispec = parseResult.getOpenAPI();
    assertNotNull(apispec);
    Schema test = apispec.getPaths().get("/mapschema").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(test instanceof MapSchema);
    assertTrue(test.getAdditionalProperties() instanceof Boolean);
    assertTrue((Boolean)test.getAdditionalProperties());
}
 
Example #15
Source File: DataGenerator.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
private static boolean isMap(Schema<?> schema) {
    return schema instanceof MapSchema;
}
 
Example #16
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private void assertSchema(Schema actualSchema,
        Class<?> expectedSchemaClass) {
    if (assertSpecificJavaClassSchema(actualSchema, expectedSchemaClass)) {
        return;
    }

    if (actualSchema.get$ref() != null) {
        assertNull(actualSchema.getProperties());
        schemaReferences.add(actualSchema.get$ref());
    } else {
        if (actualSchema instanceof StringSchema) {
            assertTrue(String.class.isAssignableFrom(expectedSchemaClass)
                    || Enum.class.isAssignableFrom(expectedSchemaClass));
        } else if (actualSchema instanceof BooleanSchema) {
            assertTrue((boolean.class.isAssignableFrom(expectedSchemaClass)
                    || Boolean.class
                            .isAssignableFrom(expectedSchemaClass)));
        } else if (actualSchema instanceof NumberSchema) {
            assertTrue(JSON_NUMBER_CLASSES.stream()
                    .anyMatch(jsonNumberClass -> jsonNumberClass
                            .isAssignableFrom(expectedSchemaClass)));
        } else if (actualSchema instanceof ArraySchema) {
            if (expectedSchemaClass.isArray()) {
                assertSchema(((ArraySchema) actualSchema).getItems(),
                        expectedSchemaClass.getComponentType());
            } else {
                assertTrue(Collection.class
                        .isAssignableFrom(expectedSchemaClass));
            }
        } else if (actualSchema instanceof MapSchema) {
            assertTrue(Map.class.isAssignableFrom(expectedSchemaClass));
        } else if (actualSchema instanceof DateTimeSchema) {
            assertTrue(Instant.class.isAssignableFrom(expectedSchemaClass)
                    || LocalDateTime.class
                            .isAssignableFrom(expectedSchemaClass));
        } else if (actualSchema instanceof DateSchema) {
            assertTrue(Date.class.isAssignableFrom(expectedSchemaClass)
                    || LocalDate.class
                            .isAssignableFrom(expectedSchemaClass));
        } else if (actualSchema instanceof ComposedSchema) {
            List<Schema> allOf = ((ComposedSchema) actualSchema).getAllOf();
            if (allOf.size() > 1) {
                // Inherited schema
                for (Schema schema : allOf) {
                    if (expectedSchemaClass.getCanonicalName()
                            .equals(schema.getName())) {
                        assertSchemaProperties(expectedSchemaClass, schema);
                        break;
                    }
                }
            } else {
                // Nullable schema for referring schema object
                assertEquals(1, allOf.size());
                assertEquals(expectedSchemaClass.getCanonicalName(),
                        allOf.get(0).getName());
            }
        } else if (actualSchema instanceof ObjectSchema) {
            assertSchemaProperties(expectedSchemaClass, actualSchema);
        } else {
            throw new AssertionError(
                    String.format("Unknown schema '%s' for class '%s'",
                            actualSchema.getClass(), expectedSchemaClass));
        }
    }
}