Java Code Examples for com.fasterxml.classmate.ResolvedType#getErasedType()

The following examples show how to use com.fasterxml.classmate.ResolvedType#getErasedType() . 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: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
    Class<?> targetSuperType = javaType.getErasedType();
    JsonTypeInfo typeInfoAnnotation;
    do {
        typeInfoAnnotation = targetSuperType.getAnnotation(JsonTypeInfo.class);
        targetSuperType = targetSuperType.getSuperclass();
    } while (typeInfoAnnotation == null && targetSuperType != null);

    if (typeInfoAnnotation == null || javaType.getErasedType().getDeclaredAnnotation(JsonSubTypes.class) != null) {
        return null;
    }
    ObjectNode definition = this.createSubtypeDefinition(javaType, typeInfoAnnotation, null, context);
    if (definition == null) {
        return null;
    }
    return new CustomDefinition(definition, CustomDefinition.DefinitionType.STANDARD, CustomDefinition.AttributeInclusion.NO);
}
 
Example 2
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the appropriate type identifier according to {@link JsonTypeInfo#use()}.
 *
 * @param javaType specific subtype to identify
 * @param typeInfoAnnotation annotation for determining what kind of identifier to use
 * @return type identifier (or {@code null} if no supported value could be found)
 */
private String getTypeIdentifier(ResolvedType javaType, JsonTypeInfo typeInfoAnnotation) {
    Class<?> erasedTargetType = javaType.getErasedType();
    final String typeIdentifier;
    switch (typeInfoAnnotation.use()) {
    case NAME:
        typeIdentifier = Optional.ofNullable(erasedTargetType.getAnnotation(JsonTypeName.class))
                .map(JsonTypeName::value)
                .filter(name -> !name.isEmpty())
                .orElseGet(() -> getUnqualifiedClassName(erasedTargetType));
        break;
    case CLASS:
        typeIdentifier = erasedTargetType.getName();
        break;
    default:
        typeIdentifier = null;
    }
    return typeIdentifier;
}
 
Example 3
Source File: SchemaGeneratorSubtypesTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Override
public List<ResolvedType> findSubtypes(ResolvedType declaredType, SchemaGenerationContext context) {
    if (declaredType.getErasedType() == TestSuperClass.class) {
        return subtypes.stream()
                .map(subtype -> {
                    try {
                        return context.getTypeContext().resolveSubtype(declaredType, subtype);
                    } catch (IllegalArgumentException ex) {
                        // possible reasons are mainly:
                        // 1. Conflicting type parameters between declared super type and this particular subtype
                        // 2. Extra generic introduced in subtype that is not present in supertype, i.e. which cannot be resolved
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
    return null;
}
 
Example 4
Source File: ApiParamReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(ParameterContext context) {
    ResolvedType resolvedType = context.resolvedMethodParameter().getParameterType();
    Class erasedType = resolvedType.getErasedType();
    if (isGeneratedType(erasedType)) {
        context.parameterBuilder()
                .parameterType("body").name(erasedType.getSimpleName())
                .description("Not a real parameter, it is a parameter generated after assembly.");
        return;
    }
    Optional<ApiParam> optional = readApiParam(context);
    if (optional.isPresent()) {
        ApiParam apiParam = optional.get();
        List<VendorExtension> extensions = buildExtensions(resolvedType);
        context.parameterBuilder().name(emptyToNull(apiParam.name()))
                .description(emptyToNull(resolver.resolve(apiParam.value())))
                .parameterType(TypeUtils.isComplexObjectType(erasedType) ? "body" : "query")
                .order(SWAGGER_PLUGIN_ORDER)
                .hidden(false)
                .parameterAccess(emptyToNull(apiParam.access()))
                .defaultValue(emptyToNull(apiParam.defaultValue()))
                .allowMultiple(apiParam.allowMultiple())
                .allowEmptyValue(apiParam.allowEmptyValue())
                .required(apiParam.required())
                .scalarExample(new Example(apiParam.example()))
                .complexExamples(examples(apiParam.examples()))
                .collectionFormat(apiParam.collectionFormat())
                .vendorExtensions(extensions);
    }
}
 
Example 5
Source File: DefaultParamPlugin.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
private Class<?> resolveParamType(ResolvedType resolvedType) {
	if (TypeUtil.isSimpleType(resolvedType)) {
		return resolvedType.getErasedType();
	} else {
		List<ResolvedType> collectionResolvedTypes = TypeUtil.resolveGenericType(Collection.class, resolvedType);
		if (collectionResolvedTypes == null) {
			return null;
		} else {
			ResolvedType collectionResolvedType = collectionResolvedTypes.get(0);
			if (TypeUtil.isComplexType(collectionResolvedType)) {
				return null;
			} else {
				return collectionResolvedType.getErasedType();
			}
		}
	}
}
 
Example 6
Source File: TypeContext.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Constructing a string that fully represents the given type (including possible type parameters and their actual types).
 *
 * @param type the type to represent
 * @param simpleClassNames whether simple class names should be used (otherwise: full package names are included)
 * @return resulting string
 */
private String getTypeDescription(ResolvedType type, boolean simpleClassNames) {
    Class<?> erasedType = type.getErasedType();
    String result = simpleClassNames ? erasedType.getSimpleName() : erasedType.getTypeName();
    List<ResolvedType> typeParameters = type.getTypeParameters();
    if (!typeParameters.isEmpty()) {
        result += typeParameters.stream()
                .map(parameterType -> this.getTypeDescription(parameterType, simpleClassNames))
                .collect(Collectors.joining(", ", "<", ">"));
    }
    return result;
}
 
Example 7
Source File: EnumModule.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Look-up the given enum type's constant values.
 *
 * @param enumType targeted enum type
 * @param enumConstantToString how to derive a plain string representation from an enum constant value
 * @return collection containing constant enum values
 */
private static List<String> extractEnumValues(ResolvedType enumType, Function<Enum<?>, String> enumConstantToString) {
    Class<?> erasedType = enumType.getErasedType();
    if (erasedType.getEnumConstants() == null) {
        return null;
    }
    return Stream.of(erasedType.getEnumConstants())
            .map(enumConstant -> enumConstantToString.apply((Enum<?>) enumConstant))
            .collect(Collectors.toList());
}
 
Example 8
Source File: AttributeCollector.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Setter for "{@link SchemaKeyword#TAG_ADDITIONAL_PROPERTIES}" attribute.
 *
 * @param node schema node to set attribute on
 * @param additionalProperties attribute value to set
 * @param generationContext generation context, including configuration to apply when looking-up attribute values
 * @return this instance (for chaining)
 */
public AttributeCollector setAdditionalProperties(ObjectNode node, Type additionalProperties, SchemaGenerationContext generationContext) {
    if (additionalProperties == Void.class || additionalProperties == Void.TYPE) {
        node.put(generationContext.getKeyword(SchemaKeyword.TAG_ADDITIONAL_PROPERTIES), false);
    } else if (additionalProperties != null) {
        ResolvedType targetType = generationContext.getTypeContext().resolve(additionalProperties);
        if (targetType.getErasedType() != Object.class) {
            ObjectNode additionalPropertiesSchema = generationContext.createDefinitionReference(targetType);
            node.set(generationContext.getKeyword(SchemaKeyword.TAG_ADDITIONAL_PROPERTIES),
                    additionalPropertiesSchema);
        }
    }
    return this;
}
 
Example 9
Source File: SchemaGeneratorCustomDefinitionsTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
@Parameters(source = SchemaVersion.class)
public void testGenerateSchema_CustomInlineStandardDefinition(SchemaVersion schemaVersion) throws Exception {
    CustomDefinitionProviderV2 customDefinitionProvider = new CustomDefinitionProviderV2() {
        @Override
        public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
            if (javaType.getErasedType() == Integer.class) {
                // using SchemaGenerationContext.createStandardDefinition() to avoid endless loop with this custom definition
                ObjectNode standardDefinition = context.createStandardDefinition(context.getTypeContext().resolve(Integer.class), this);
                standardDefinition.put("$comment", "custom override of Integer");
                standardDefinition.put(context.getKeyword(SchemaKeyword.TAG_TITLE), "custom title");
                return new CustomDefinition(standardDefinition);
            }
            return null;
        }
    };
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
    configBuilder.forTypesInGeneral()
            .withTitleResolver(_scope -> "type title")
            .withDescriptionResolver(_scope -> "type description")
            .withCustomDefinitionProvider(customDefinitionProvider);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(Integer.class);
    Assert.assertEquals(4, result.size());
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_INTEGER.forVersion(schemaVersion),
            result.get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion)).asText());
    Assert.assertEquals("custom override of Integer", result.get("$comment").asText());
    Assert.assertEquals("custom title", result.get(SchemaKeyword.TAG_TITLE.forVersion(schemaVersion)).asText());
    Assert.assertEquals("type description", result.get(SchemaKeyword.TAG_DESCRIPTION.forVersion(schemaVersion)).asText());
}
 
Example 10
Source File: SchemaGeneratorSubtypesTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
private List<ResolvedType> determineTargetTypeOverrides(FieldScope field) {
    ResolvedType declaredType = field.getType();
    if (declaredType.getErasedType() == Object.class && field.getName().startsWith("numberOrString")) {
        // TypeContext::resolve() would have been sufficient here, but in advanced scenarios TypeContext::resolveSubType() is more appropriate
        return Stream.of(Number.class, String.class)
                .map(specificSubtype -> field.getContext().resolveSubtype(declaredType, specificSubtype))
                .collect(Collectors.toList());
    }
    return null;
}
 
Example 11
Source File: CustomAccessorsProvider.java    From chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the constructors in the given type
 *
 * @param resolvedType the type to search
 */
public com.google.common.collect.ImmutableList<ResolvedConstructor> constructorsIn(ResolvedType resolvedType) {
    MemberResolver resolver = new MemberResolver(typeResolver);
    resolver.setIncludeLangObject(false);
    if (resolvedType.getErasedType() == Object.class) {
        return ImmutableList.of();
    }
    ResolvedTypeWithMembers typeWithMembers = resolver.resolve(resolvedType, null, null);
    return FluentIterable
            .from(newArrayList(typeWithMembers.getConstructors())).toList();
}
 
Example 12
Source File: SimplifiedOptionalModule.java    From jsonschema-generator with Apache License 2.0 4 votes vote down vote up
private static boolean isOptional(ResolvedType type) {
    return type.getErasedType() == Optional.class;
}
 
Example 13
Source File: EnumModule.java    From jsonschema-generator with Apache License 2.0 4 votes vote down vote up
private static boolean isEnum(ResolvedType type) {
    return type.getErasedType() == Enum.class;
}
 
Example 14
Source File: FlattenedOptionalModule.java    From jsonschema-generator with Apache License 2.0 4 votes vote down vote up
private static boolean isOptional(ResolvedType type) {
    return type.getErasedType() == Optional.class;
}
 
Example 15
Source File: HandlerMethodResolverWrapper.java    From summerframework with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
boolean bothAreVoids(ResolvedType candidateMethodReturnValue, Type returnType) {
    return (Void.class == candidateMethodReturnValue.getErasedType()
        || Void.TYPE == candidateMethodReturnValue.getErasedType())
        && (Void.TYPE == returnType || Void.class == returnType);
}
 
Example 16
Source File: SwaggerConfiguration.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Override
public boolean appliesTo(ResolvedType type) {
    return type.getErasedType() == genericType && !type.getTypeBindings().isEmpty() && boundTypeIndex <= type.getTypeBindings().size() - 1;
}