Java Code Examples for com.github.javaparser.resolution.types.ResolvedType

The following examples show how to use com.github.javaparser.resolution.types.ResolvedType. These examples are extracted from open source projects. 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 Project: apigcc   Source File: FieldHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 获取真实的属性类型
 * @param parent
 * @param field
 * @return
 */
public static ResolvedType getActuallyType(ResolvedReferenceType parent, ResolvedFieldDeclaration field) {
    ResolvedType type = field.getType();
    if (type.isReferenceType()) {
        //将父类的T,传递给 属性的T
        return ClassHelper.useClassTypeParameter(parent, type.asReferenceType());
    }
    if (type.isTypeVariable()) {
        //类型为T,这种泛型
        Optional<ResolvedType> optional = ClassHelper.getTypeParameter(parent, field.getType().asTypeParameter().getName());
        if (optional.isPresent()) {
            return optional.get();
        }
    }
    return type;
}
 
Example 2
Source Project: Recaf   Source File: JavaParserUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Converts the resolved type to an internal representation.
 * If the type is an array the component type's internal name is returned.
 * Primitives return their boxed names.
 *
 * @param type
 * 		JavaParser resolved type.
 *
 * @return Internalized representation.
 */
public static String toInternal(ResolvedType type) {
	if(type.isVoid() || type.isPrimitive())
		return type.asPrimitive().getBoxTypeQName().replace(".", "/");
	if(type.isArray())
		return toInternal(type.asArrayType().getComponentType());
	if(type.isReference()) {
		if(type.asReferenceType().getTypeDeclaration() != null)
			return toInternal(type.asReferenceType().getTypeDeclaration().get());
		else
			return type.asReferenceType().getQualifiedName().replace(".", "/");
	}
	// The above cases should have internalized the name...
	// If not lets be alerted of a uncaught case.
	throw new IllegalStateException("Cannot internalize type: " + type);
}
 
Example 3
Source Project: Recaf   Source File: JavaParserUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be an object type.
 * @return Internal descriptor from type, assuming the type is available.
 */
private static String typeToDesc(ResolvedType type) {
	String qualified = null;
	if(type instanceof ResolvedTypeVariable)
		qualified = ((ResolvedTypeVariable) type).qualifiedName();
	else if(type instanceof ResolvedTypeParameterDeclaration)
		qualified = type.asTypeParameter().getQualifiedName();
	else if(type.isPrimitive())
		return primTypeToDesc(type.asPrimitive());
	else if(type.isVoid())
		return "V";
	else
		qualified = toInternal(type);
	if(qualified == null)
		return null;
	// Substring out generics
	if(qualified.contains("<") && qualified.contains(">"))
		qualified = qualified.substring(0, qualified.indexOf('<'));
	StringBuilder sbDesc = new StringBuilder();
	for(int i = 0; i < type.arrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append("L");
	sbDesc.append(qualified.replace('.', '/'));
	sbDesc.append(";");
	return sbDesc.toString();
}
 
Example 4
Source Project: JRemapper   Source File: ParserTypeUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be an object type.
 * @return Internal descriptor from type, assuming the type is available.
 */
private static String typeToDesc(ResolvedType type) {
	String qualified = null;
	if (type instanceof ResolvedTypeVariable) {
		qualified = ((ResolvedTypeVariable) type).qualifiedName();
	} else if (type instanceof ResolvedTypeParameterDeclaration) {
		qualified = type.asTypeParameter().getQualifiedName();;
	} else if(type.isPrimitive()) {
		return primTypeToDesc(type.asPrimitive());
	} else if(type.isVoid()) {
		return "V";
	} else {
		qualified = type.describe();
	}
	if (qualified == null)
		return null;
	StringBuilder sbDesc = new StringBuilder();
	for (int i = 0; i < type.arrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append("L");
	sbDesc.append(qualified.replace('.', '/'));
	sbDesc.append(";");
	return sbDesc.toString();
}
 
Example 5
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnArraySchema_When_GivenTypeIsAnArray() {
    ResolvedType arrayType = mock(ResolvedType.class);
    ResolvedArrayType arrayResolvedType = mock(ResolvedArrayType.class);
    ResolvedType stringType = mockReferencedTypeOf(String.class);

    when(arrayType.isArray()).thenReturn(true);
    when(arrayType.asArrayType()).thenReturn(arrayResolvedType);
    when(arrayResolvedType.getComponentType()).thenReturn(stringType);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(arrayType);
    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 6
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNotNullableArray_When_GivenTypeIsAListString() {
    ResolvedType resolvedType = mockReferencedTypeOf(Collection.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(String.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 7
Source Project: flow   Source File: SchemaResolverTest.java    License: 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 8
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNullableOptional_When_GivenTypeIsAnOptionalString() {
    ResolvedType resolvedType = mockReferencedTypeOf(Optional.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(String.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof StringSchema);
    Assert.assertTrue(schema.getNullable());

    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 9
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNullableOptional_When_GivenTypeIsAnOptionalBean() {
    ResolvedType resolvedType = mockReferencedTypeOf(Optional.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(TestBean.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof ComposedSchema);
    Assert.assertTrue(schema.getNullable());
    Assert.assertEquals(1, ((ComposedSchema) schema).getAllOf().size());
    String beanRef = schemaResolver
            .getFullQualifiedNameRef(TestBean.class.getCanonicalName());
    Assert.assertEquals(beanRef,
            ((ComposedSchema) schema).getAllOf().get(0).get$ref());

    Assert.assertEquals(1, schemaResolver.getFoundTypes().size());
}
 
Example 10
Source Project: apigcc   Source File: SpringComponentResolver.java    License: MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(ResolvedType type) {

    Optional<ResolvedType> optional = ClassHelper.getTypeParameter(type.asReferenceType(), 0);
    return optional
            .map(Apigcc.getInstance().getTypeResolvers()::resolve)
            .orElseGet(UnAvailableTypeDescription::new);
}
 
Example 11
Source Project: apigcc   Source File: ObjectTypeResolver.java    License: MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(ResolvedType type) {
    ObjectTypeDescription typeDescription = new ObjectTypeDescription();

    ResolvedReferenceType referenceType = type.asReferenceType();
    typeDescription.setType(referenceType.getTypeDeclaration().getName());
    if (!ReferenceContext.getInstance().push(referenceType.describe())) {
        //类型解析缓冲池,防止循环引用
        return typeDescription;
    }

    //解析父类属性,并合并至当前
    for (ResolvedReferenceType directAncestor : referenceType.getDirectAncestors()) {
        TypeDescription ancestorDescription = Apigcc.getInstance().getTypeResolvers().resolve(directAncestor);
        if (ancestorDescription.isAvailable() && ancestorDescription.isObject()) {
            typeDescription.merge(ancestorDescription.asObject());
        }
    }

    //TODO fix use access method
    for (ResolvedFieldDeclaration declaredField : referenceType.getTypeDeclaration().getDeclaredFields()) {
        if (declaredField.isStatic()) {
            continue;
        }
        ResolvedType fieldType = FieldHelper.getActuallyType(referenceType, declaredField);

        TypeDescription fieldDescription = Apigcc.getInstance().getTypeResolvers().resolve(fieldType);
        fieldDescription.setKey(declaredField.getName());

        JsonPropertyHelper.getJsonName(declaredField).ifPresent(fieldDescription::setKey);
        CommentHelper.getComment(declaredField).ifPresent(fieldDescription::accept);
        fieldDescription.addConditions(ValidationHelper.getValidations(declaredField));
        FieldHelper.getInitializerValue(declaredField).ifPresent(fieldDescription::setDefaultValue);

        typeDescription.add(fieldDescription);
    }

    ReferenceContext.getInstance().remove(referenceType.describe());
    return typeDescription;
}
 
Example 12
Source Project: apigcc   Source File: TypeResolvers.java    License: MIT License 5 votes vote down vote up
/**
 * 解析类型信息
 *
 * @param type
 * @return
 */
public TypeDescription resolve(ResolvedType type) {
    for (TypeResolver typeResolver : resolvers) {
        if (typeResolver.accept(type)) {
            return typeResolver.resolve(type);
        }
    }

    if (finalTypeResolver.accept(type)) {
        return finalTypeResolver.resolve(type);
    }

    return new UnAvailableTypeDescription();
}
 
Example 13
Source Project: apigcc   Source File: CollectionTypeResolver.java    License: MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(ResolvedType type) {
    Optional<ResolvedType> optional = ClassHelper.getTypeParameter(type.asReferenceType(), 0);
    return new ArrayTypeDescription(optional
            .map(Apigcc.getInstance().getTypeResolvers()::resolve)
            .orElseGet(UnAvailableTypeDescription::new));
}
 
Example 14
Source Project: apigcc   Source File: PrimitiveTypeResolver.java    License: MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(ResolvedType type) {
    if (type.isPrimitive()) {
        return new PrimitiveTypeDescription(type.asPrimitive());
    } else {
        return new PrimitiveTypeDescription(type.asReferenceType());
    }
}
 
Example 15
Source Project: apigcc   Source File: PrimitiveTypeResolver.java    License: MIT License 5 votes vote down vote up
/**
 * 包装类型判断
 *
 * @param type
 * @return
 */
private boolean isBoxing(ResolvedType type) {
    if (!type.isReferenceType()) {
        return false;
    }
    String id = type.asReferenceType().getId();
    return list.contains(id);
}
 
Example 16
Source Project: apigcc   Source File: EnumTypeResolver.java    License: MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(ResolvedType type) {
    ResolvedEnumDeclaration enumDeclaration = type.asReferenceType().getTypeDeclaration().asEnum();
    TypeDescription description = new StringTypeDescription(enumDeclaration.getName(), "");
    String desc = enumDeclaration.getEnumConstants().stream().map(ResolvedEnumConstantDeclaration::getName).collect(Collectors.joining(",", "[", "]"));
    description.addRemark(desc);
    return description;
}
 
Example 17
Source Project: apigcc   Source File: ClassHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取泛型信息
 * @param referenceType
 * @param index 位置信息
 * @return
 */
public static Optional<ResolvedType> getTypeParameter(ResolvedReferenceType referenceType, int index){
    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParameters = referenceType.getTypeParametersMap();
    if(typeParameters.size()>index){
        Pair<ResolvedTypeParameterDeclaration, ResolvedType> pair = typeParameters.get(index);
        return Optional.of(pair.b);
    }
    return Optional.empty();
}
 
Example 18
Source Project: apigcc   Source File: ClassHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取泛型信息
 * @param referenceType
 * @param a 如 T E 等
 * @return
 */
public static Optional<ResolvedType> getTypeParameter(ResolvedReferenceType referenceType, String a){
    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParameters = referenceType.getTypeParametersMap();
    for (Pair<ResolvedTypeParameterDeclaration, ResolvedType> pair : typeParameters) {
        if(Objects.equals(pair.a.getName(),a)){
            return Optional.of(pair.b);
        }
    }
    return Optional.empty();
}
 
Example 19
Source Project: apigcc   Source File: ClassHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 使用父类的泛型 解析当前类
 * @param parent
 * @param field
 */
public static ResolvedType useClassTypeParameter(ResolvedReferenceType parent, ResolvedReferenceType field){
    for (Pair<ResolvedTypeParameterDeclaration, ResolvedType> pair : field.getTypeParametersMap()) {
        if(pair.b.isTypeVariable()){
            Optional<ResolvedType> typeParameter = getTypeParameter(parent, pair.b.asTypeVariable().describe());
            if (typeParameter.isPresent()) {
                return field.replaceTypeVariables(pair.b.asTypeVariable().asTypeParameter(), typeParameter.get());
            }
        }
    }
    return field;
}
 
Example 20
Source Project: JRemapper   Source File: ParserTypeUtil.java    License: MIT License 5 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be a primitive.
 * @return Internal descriptor.
 */
private static String primTypeToDesc(ResolvedType type) {
	String desc = null;
	switch (type.describe()) {
		case "boolean":
			desc = "Z";
			break;
		case "int":
			desc = "I";
			break;
		case "long":
			desc = "J";
			break;
		case "short":
			desc = "S";
			break;
		case "byte":
			desc = "B";
			break;
		case "double":
			desc = "D";
			break;
		case "float":
			desc = "F";
			break;
		case "void":
			desc = "V";
			break;
		default:
			throw new RuntimeException("Unknown primitive type field '" + type.describe() + "'");
	}
	StringBuilder sbDesc = new StringBuilder();
	for (int i = 0; i < type.arrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append(desc);
	return sbDesc.toString();
}
 
Example 21
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
Schema parseResolvedTypeToSchema(ResolvedType resolvedType) {
    if (resolvedType.isArray()) {
        return createArraySchema(resolvedType);
    }
    if (isNumberType(resolvedType)) {
        return new NumberSchema();
    } else if (isStringType(resolvedType)) {
        return new StringSchema();
    } else if (isCollectionType(resolvedType)) {
        return createCollectionSchema(resolvedType.asReferenceType());
    } else if (isBooleanType(resolvedType)) {
        return new BooleanSchema();
    } else if (isMapType(resolvedType)) {
        return createMapSchema(resolvedType);
    } else if (isDateType(resolvedType)) {
        return new DateSchema();
    } else if (isDateTimeType(resolvedType)) {
        return new DateTimeSchema();
    } else if (isOptionalType(resolvedType)) {
        return createOptionalSchema(resolvedType.asReferenceType());
    } else if (isUnhandledJavaType(resolvedType)) {
        return new ObjectSchema();
    } else if (isTypeOf(resolvedType, Enum.class)) {
        return createEnumTypeSchema(resolvedType);
    }
    return createUserBeanSchema(resolvedType);
}
 
Example 22
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Schema createCollectionSchema(ResolvedReferenceType type) {
    ArraySchema array = new ArraySchema();
    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParametersMap = type
            .getTypeParametersMap();
    if (!typeParametersMap.isEmpty()) {
        ResolvedType collectionParameterType = typeParametersMap.get(0).b;
        array.items(parseResolvedTypeToSchema(collectionParameterType));
    }
    return array;
}
 
Example 23
Source Project: flow   Source File: SchemaResolver.java    License: 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 24
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isNumberType(ResolvedType type) {
    if (type.isPrimitive()) {
        ResolvedPrimitiveType resolvedPrimitiveType = type.asPrimitive();
        return resolvedPrimitiveType != ResolvedPrimitiveType.BOOLEAN
                && resolvedPrimitiveType != ResolvedPrimitiveType.CHAR;
    } else {
        return isTypeOf(type, Number.class);
    }
}
 
Example 25
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isBooleanType(ResolvedType type) {
    if (type.isPrimitive()) {
        return type.asPrimitive() == ResolvedPrimitiveType.BOOLEAN;
    } else {
        return isTypeOf(type, Boolean.class);
    }
}
 
Example 26
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isStringType(ResolvedType type) {
    if (type.isPrimitive()) {
        return type.asPrimitive() == ResolvedPrimitiveType.CHAR;
    } else {
        return isTypeOf(type, String.class, Character.class);
    }
}
 
Example 27
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isTypeOf(ResolvedType type, Class... clazz) {
    if (!type.isReferenceType()) {
        return false;
    }
    List<String> classes = Arrays.stream(clazz).map(Class::getName)
            .collect(Collectors.toList());
    return classes.contains(type.asReferenceType().getQualifiedName())
            || type.asReferenceType().getAllAncestors().stream()
                    .map(ResolvedReferenceType::getQualifiedName)
                    .anyMatch(classes::contains);
}
 
Example 28
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Schema createEnumTypeSchema(ResolvedType resolvedType) {
    ResolvedReferenceType type = resolvedType.asReferenceType();
    List<String> entries = type
            .getTypeDeclaration().asEnum().getEnumConstants().stream()
            .map(ResolvedEnumConstantDeclaration::getName)
            .collect(Collectors.toList());
    String qualifiedName = type.getQualifiedName();
    foundTypes.put(qualifiedName, type);
    StringSchema schema = new StringSchema();
    schema.name(qualifiedName);
    schema.setEnum(entries);
    schema.$ref(getFullQualifiedNameRef(qualifiedName));
    return schema;
}
 
Example 29
Source Project: flow   Source File: SchemaResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Schema createUserBeanSchema(ResolvedType resolvedType) {
    if (resolvedType.isReferenceType()) {
        String qualifiedName = resolvedType.asReferenceType()
                .getQualifiedName();
        foundTypes.put(qualifiedName, resolvedType.asReferenceType());
        return new ObjectSchema().name(qualifiedName)
                .$ref(getFullQualifiedNameRef(qualifiedName));
    }
    return new ObjectSchema();
}
 
Example 30
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_ReturnNotNullableNumberSchema_When_GivenTypeIsAPrimitiveInt() {
    ResolvedType numberType = mockPrimitiveTypeOf(
            ResolvedPrimitiveType.INT);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(numberType);
    Assert.assertTrue(schema instanceof NumberSchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}