io.swagger.v3.core.converter.ModelConverters Java Examples

The following examples show how to use io.swagger.v3.core.converter.ModelConverters. 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: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertDoubleArrayBodyParam() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class);

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType().schema(new ArraySchema()
                            .items(new ArraySchema().items(new StringSchema())))));


    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertNotNull(jt);

    assertEquals(jt.getRawClass(), List[].class);
    JavaType inner = jt.getContentType();
    assertEquals(inner.getRawClass(), List.class);
    assertEquals(inner.getContentType().getRawClass(), String.class);

}
 
Example #3
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Extract schema schema.
 *
 * @param components the components
 * @param returnType the return type
 * @param jsonView the json view
 * @param annotations the annotations
 * @return the schema
 */
public static Schema extractSchema(Components components, Type returnType, JsonView jsonView, Annotation[] annotations) {
	Schema schemaN = null;
	ResolvedSchema resolvedSchema = null;
	try {
		resolvedSchema = ModelConverters.getInstance()
				.resolveAsResolvedSchema(
						new AnnotatedType(returnType).resolveAsRef(true).jsonViewAnnotation(jsonView).ctxAnnotations(annotations));
	}
	catch (Exception e) {
		LOGGER.warn(Constants.GRACEFUL_EXCEPTION_OCCURRED, e);
		return null;
	}
	if (resolvedSchema.schema != null) {
		schemaN = resolvedSchema.schema;
		Map<String, Schema> schemaMap = resolvedSchema.referencedSchemas;
		if (schemaMap != null) {
			for (Map.Entry<String, Schema> entry : schemaMap.entrySet()) {
				Map<String, Schema> componentSchemas = components.getSchemas();
				if (componentSchemas == null) {
					componentSchemas = new LinkedHashMap<>();
					componentSchemas.put(entry.getKey(), entry.getValue());
				}
				else if (!componentSchemas.containsKey(entry.getKey())) {
					componentSchemas.put(entry.getKey(), entry.getValue());
				}
				components.setSchemas(componentSchemas);
			}
		}
	}
	return schemaN;
}
 
Example #4
Source File: ModelConverterRegistrar.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets registered converter same as.
 *
 * @param modelConverter the model converter
 * @return the registered converter same as
 */
private Optional<ModelConverter> getRegisteredConverterSameAs(ModelConverter modelConverter) {
	try {
		Field convertersField = FieldUtils.getDeclaredField(ModelConverters.class, "converters", true);
		List<ModelConverter> modelConverters = (List<ModelConverter>) convertersField.get(modelConvertersInstance);
		return modelConverters.stream()
				.filter(registeredModelConverter -> isSameConverter(registeredModelConverter, modelConverter))
				.findFirst();
	}
	catch (IllegalAccessException exception) {
		LOGGER.warn(exception.getMessage());
	}
	return Optional.empty();
}
 
Example #5
Source File: QuerydslPredicateOperationCustomizer.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/***
 * Constructs the parameter
 * @param type The type of the parameter
 * @param name The name of the parameter
 * @return The swagger parameter
 */
private io.swagger.v3.oas.models.parameters.Parameter buildParam(Type type, String name) {
	io.swagger.v3.oas.models.parameters.Parameter parameter = new io.swagger.v3.oas.models.parameters.Parameter();

	if (StringUtils.isBlank(parameter.getName())) {
		parameter.setName(name);
	}

	if (StringUtils.isBlank(parameter.getIn())) {
		parameter.setIn("query");
	}

	if (parameter.getSchema() == null) {
		Schema<?> schema = null;
		PrimitiveType primitiveType = PrimitiveType.fromType(type);
		if (primitiveType != null) {
			schema = primitiveType.createProperty();
		}
		else {
			ResolvedSchema resolvedSchema = ModelConverters.getInstance()
					.resolveAsResolvedSchema(
							new io.swagger.v3.core.converter.AnnotatedType(type).resolveAsRef(true));
			// could not resolve the schema or this schema references other schema
			// we dont want this since there's no reference to the components in order to register a new schema if it doesnt already exist
			// defaulting to string
			if (resolvedSchema == null || !resolvedSchema.referencedSchemas.isEmpty()) {
				schema = PrimitiveType.fromType(String.class).createProperty();
			}
			else {
				schema = resolvedSchema.schema;
			}
		}
		parameter.setSchema(schema);
	}
	return parameter;
}
 
Example #6
Source File: ResourceIdentifierTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void generateOpenAPISchemaShouldContainTheKindProperty() {
    final ModelConverters converters = ModelConverters.getInstance();
    final ResolvedSchema resolvedSchema = converters.resolveAsResolvedSchema(new AnnotatedType(ResourceIdentifier.class));

    @SuppressWarnings("unchecked")
    final Map<String, ?> properties = resolvedSchema.schema.getProperties();
    assertThat(properties).containsKey("kind");
}
 
Example #7
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertComplexArrayBodyParam() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class);

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType().schema(new ArraySchema()
                            .items(new Schema().$ref("#/components/schemas/Person")))));



    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertEquals(jt.getRawClass(), Person[].class);
}
 
Example #8
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertPrimitiveArrayBodyParam() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class);

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType().schema(new ArraySchema()
                            .items(new StringSchema()))));


    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertNotNull(jt);
    assertEquals(jt.getRawClass(), String[].class);
}
 
Example #9
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadModel() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().readAll(User.class);
    Object o = ExampleBuilder.fromSchema(new Schema().$ref("User"), definitions);

    String str = new XmlExampleSerializer().serialize((Example) o);
    assertEqualsIgnoreLineEnding(str, "<?xml version='1.1' encoding='UTF-8'?><user><id>0</id><user>string</user><children><child>string</child></children></user>");
}
 
Example #10
Source File: ResponseModelTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexModel() throws Exception {
    Schema property = new Schema().$ref("User");
    Map<String, Schema> definitions = ModelConverters.getInstance().readAll(User.class);
    Object o = ExampleBuilder.fromSchema(property, definitions);

    ObjectExample n = Json.mapper().convertValue(o, ObjectExample.class);
    assertNotNull(n);
}
 
Example #11
Source File: GenerateRestClients.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
private static void addSchemas(OpenAPI openAPI, Class<?> clazz) {
    ModelConverters.getInstance().readAll(clazz).forEach(openAPI::schema);
}
 
Example #12
Source File: JaxRs2Extension.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public ResolvedParameter extractParameters(
        final List<Annotation> annotations,
        final Type type,
        final Set<Type> typesToSkip,
        final Components components,
        final Consumes classConsumes,
        final Consumes methodConsumes,
        final boolean includeRequestBody,
        final JsonView jsonViewAnnotation,
        final Iterator<OpenAPIExtension> chain) {

    if (shouldIgnoreType(type, typesToSkip)) {
        return new ResolvedParameter();
    }

    List<Parameter> parameters = annotations.stream().
            filter(annotation -> annotation instanceof MatrixParam).
            map(annotation -> {
                MatrixParam param = (MatrixParam) annotation;
                Parameter mp = new PathParameter().name(param.value());
                mp.setStyle(Parameter.StyleEnum.MATRIX);

                ResolvedSchema resolvedSchema = ModelConverters.getInstance().readAllAsResolvedSchema(type);
                if (resolvedSchema != null) {
                    mp.setSchema(resolvedSchema.schema);
                }
                applyBeanValidatorAnnotations(mp, annotations);

                return mp;
            }).collect(Collectors.toList());

    // Only call down to the other items in the chain if no parameters were produced
    if (parameters.isEmpty()) {
        return super.extractParameters(
                annotations, type, typesToSkip, components, classConsumes,
                methodConsumes, includeRequestBody, jsonViewAnnotation, chain);
    }

    ResolvedParameter resolved = new ResolvedParameter();
    resolved.parameters = parameters;
    return resolved;
}