Java源码示例:io.swagger.v3.core.converter.AnnotatedType

示例1
/**
 * 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")));
}
 
示例2
@Override
public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (chain.hasNext() && type != null && type.getType() instanceof CollectionType
			&& "_embedded".equalsIgnoreCase(type.getPropertyName())) {
		Schema<?> schema = chain.next().resolve(type, context, chain);
		if (schema instanceof ArraySchema) {
			Class<?> entityType = getEntityType(type);
			String entityClassName = linkRelationProvider.getCollectionResourceRelFor(entityType).value();

			return new ObjectSchema()
					.name("_embedded")
					.addProperties(entityClassName, schema);
		}
	}
	return chain.hasNext() ? chain.next().resolve(type, context, chain) : null;
}
 
示例3
@Override
public Schema customize(Schema property, AnnotatedType type) {
	Annotation[] ctxAnnotations = type.getCtxAnnotations();
	if (ctxAnnotations == null) {
		return property;
	}

	Optional<CustomizedProperty> propertyAnnotation = Stream.of(ctxAnnotations)
			.filter(CustomizedProperty.class::isInstance)
			.findFirst()
			.map(CustomizedProperty.class::cast);

	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType.getRawClass().equals(Duration.class)) {
		property = new StringSchema().format("duration").properties(Collections.emptyMap());
	}
	return property;
}
 
示例4
/**
 * Compose polymorphic schema schema.
 *
 * @param type the type
 * @param schema the schema
 * @param schemas the schemas
 * @return the schema
 */
private Schema composePolymorphicSchema(AnnotatedType type, Schema schema, Collection<Schema> schemas) {
	String ref = schema.get$ref();
	List<Schema> composedSchemas = schemas.stream()
			.filter(s -> s instanceof ComposedSchema)
			.map(s -> (ComposedSchema) s)
			.filter(s -> s.getAllOf() != null)
			.filter(s -> s.getAllOf().stream().anyMatch(s2 -> ref.equals(s2.get$ref())))
			.map(s -> new Schema().$ref(AnnotationsUtils.COMPONENTS_REF + s.getName()))
			.collect(Collectors.toList());
	if (composedSchemas.isEmpty()) return schema;

	ComposedSchema result = new ComposedSchema();
	if (isConcreteClass(type)) result.addOneOfItem(schema);
	composedSchemas.forEach(result::addOneOfItem);
	return result;
}
 
示例5
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isResponseTypeWrapper(cls)) {
			JavaType innerType = javaType.getBindings().getBoundType(0);
			if (innerType == null)
				return new StringSchema();
			else if (innerType.getBindings() != null && isResponseTypeWrapper(innerType.getRawClass())) {
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).ctxAnnotations(type.getCtxAnnotations()).resolveAsRef(true);
				return this.resolve(type, context, chain);
			}
			else
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).ctxAnnotations((type.getCtxAnnotations())).resolveAsRef(true);
		}
		else if (isResponseTypeToIgnore(cls))
			return null;
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
示例6
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isFluxTypeWrapper(cls)) {
			JavaType innerType = javaType.getBindings().getBoundType(0);
			if (innerType == null)
				return new StringSchema();
			else if (innerType.getBindings() != null && isResponseTypeWrapper(innerType.getRawClass())) {
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
				return this.resolve(type, context, chain);
			}
			else {
				ArrayType arrayType = ArrayType.construct(innerType, null);
				type = new AnnotatedType(arrayType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
			}
		}
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
示例7
/**
 * Gets entity type.
 *
 * @param type the type 
 * @return the entity type
 */
private Class<?> getEntityType(AnnotatedType type) {
	Class<?> containerEntityType = ((CollectionType) (type.getType())).getContentType().getRawClass();
	if (containerEntityType.isAssignableFrom(EntityModel.class)) {
		TypeBindings typeBindings = ((CollectionType) type.getType()).getContentType().getBindings() ;
		if (!CollectionUtils.isEmpty(typeBindings.getTypeParameters()))
			return typeBindings.getBoundType(0).getRawClass();
	}
	return containerEntityType;
}
 
示例8
/**
 * 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;
}
 
示例9
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (chain.hasNext()) {
		Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
		if (resolvedSchema == null || resolvedSchema.get$ref() == null) return resolvedSchema;
		return composePolymorphicSchema(type, resolvedSchema, context.getDefinedModels().values());
	}
	return null;
}
 
示例10
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (chain.hasNext()) {
		Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
		if (type.isSchemaProperty() && containsDeprecatedAnnotation(type.getCtxAnnotations()))
			resolvedSchema.setDeprecated(true);
		return resolvedSchema;
	}
	return null;
}
 
示例11
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (type.isSchemaProperty()) {
		JavaType javaType = Json.mapper().constructType(type.getType());
		Class<?> cls = javaType.getRawClass();
		if (AbstractRequestBuilder.isRequestTypeToIgnore(cls))
			return null;
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
示例12
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isFile(cls))
			return new FileSchema();
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
示例13
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (modelToSchemaMap.containsKey(cls))
			return modelToSchemaMap.get(cls);
		if (modelToClassMap.containsKey(cls))
			type = new AnnotatedType(modelToClassMap.get(cls)).resolveAsRef(true);
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
示例14
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (chain.hasNext()) {
		Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
		if (type.isSchemaProperty() && propertyCustomizers.isPresent()) {
			List<PropertyCustomizer> propertyCustomizerList = propertyCustomizers.get();
			for (PropertyCustomizer propertyCustomizer : propertyCustomizerList)
				resolvedSchema = propertyCustomizer.customize(resolvedSchema, type);
		}
		return resolvedSchema;
	}
	return null;
}
 
示例15
@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");
}
 
示例16
@Override
public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context, Iterator<ModelConverter> next)
{
    JavaType classType = TypeFactory.defaultInstance().constructType(annotatedType.getType());
    Class<?> rawClass = classType.getRawClass();
    JavaType resolvedType = classType;

    if ((rawClass != null) &&!resolvedType.isPrimitive())
    {
        if (rawClass.isAssignableFrom(ServerResponse.class))
        {
            resolvedType = classType.containedType(0);
        }
        else if (rawClass.isAssignableFrom(CompletableFuture.class))
        {
            Class<?> futureCls = classType.containedType(0).getRawClass();

            if (futureCls.isAssignableFrom(ServerResponse.class))
            {
                final JavaType futureType = TypeFactory.defaultInstance().constructType(classType.containedType(0));

                resolvedType = futureType.containedType(0);
            }
            else
            {
                resolvedType = classType.containedType(0);
            }
        }

        if (resolvedType != null)
        {
            if (resolvedType.getTypeName().contains("java.lang.Void"))
            {
                resolvedType = TypeFactory.defaultInstance().constructFromCanonical(Void.class.getName());
            }
            else if (resolvedType.getTypeName().contains("Optional"))
            {
                if (resolvedType.getTypeName().contains("java.nio.file.Path"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
                }

                if (resolvedType.getTypeName().contains("ByteBuffer"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
                }
            }
            else
            {
                if (resolvedType.getTypeName().contains("java.nio.file.Path"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
                }

                if (resolvedType.getTypeName().contains("ByteBuffer"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
                }
            }

            annotatedType.setType(resolvedType);

        }
    }

    try {

        return super.resolve(annotatedType, context, next);

    } catch (Exception e) {

        log.error("Error processing " + annotatedType + " " + classType + " " + annotatedType.getName(), e);

        return null;
    }
}
 
示例17
/**
 * Is concrete class boolean.
 *
 * @param type the type
 * @return the boolean
 */
private boolean isConcreteClass(AnnotatedType type) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	Class<?> clazz = javaType.getRawClass();
	return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface();
}
 
示例18
/**
 * Customize schema.
 *
 * @param property to be customized
 * @param type form the model class
 * @return customized property
 */
Schema customize(Schema property, AnnotatedType type);