Java Code Examples for com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration

The following examples show how to use com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration. 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: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 6 votes vote down vote up
/**
 * @param allJavaFiles
 * @param targetClass
 * @param targetMethod
 * @return list of qualified class or interface names which are reachable via
 *         the inheritance hierarchy of the given class (ancestors, descendants,
 *         siblings, ...) and contain the given target method
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
public static Set<String> findRelatedClassesAndInterfaces(List<String> allJavaFiles,
		ClassOrInterfaceDeclaration targetClass, MethodDeclaration targetMethod)
		throws BotRefactoringException, FileNotFoundException {
	Set<ResolvedReferenceTypeDeclaration> relatedClassesAndInterfaces = new HashSet<>();
	relatedClassesAndInterfaces.add(targetClass.resolve());

	addQualifiedNamesToRelatedClassesAndInterfacesRecursively(relatedClassesAndInterfaces, allJavaFiles,
			targetClass, targetMethod);

	Set<String> result = new HashSet<>();
	for (ResolvedReferenceTypeDeclaration declaration : relatedClassesAndInterfaces) {
		result.add(declaration.getQualifiedName());
	}

	return result;
}
 
Example 2
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 6 votes vote down vote up
private static void addQualifiedNamesToRelatedClassesAndInterfacesRecursively(
		Set<ResolvedReferenceTypeDeclaration> relatedClassesAndInterfaces, List<String> allJavaFiles,
		ClassOrInterfaceDeclaration targetClass, MethodDeclaration targetMethod)
		throws FileNotFoundException, BotRefactoringException {
	Set<ResolvedReferenceTypeDeclaration> ancestorsOfTargetClass = findAllAncestors(targetClass, targetMethod);
	relatedClassesAndInterfaces.addAll(ancestorsOfTargetClass);

	for (String file : allJavaFiles) {
		List<ClassOrInterfaceDeclaration> classesOrInterfaces = RefactoringHelper
				.getAllClassesAndInterfacesFromFile(file);

		for (ClassOrInterfaceDeclaration currentClassOrInterface : classesOrInterfaces) {
			if (relatedClassesAndInterfaces.contains(currentClassOrInterface.resolve())) {
				continue;
			}
			Set<ResolvedReferenceTypeDeclaration> ancestorsOfCurrentClassOrInterface = findAllAncestors(
					currentClassOrInterface, targetMethod);
			if (!Collections.disjoint(relatedClassesAndInterfaces, ancestorsOfCurrentClassOrInterface)) {
				// descendant found
				relatedClassesAndInterfaces.add(currentClassOrInterface.resolve());
				addQualifiedNamesToRelatedClassesAndInterfacesRecursively(relatedClassesAndInterfaces, allJavaFiles,
						currentClassOrInterface, targetMethod);
			}
		}
	}
}
 
Example 3
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Get all direct and indirect ancestors of a given class if possible (if
 * ancestor is not a external dependency for example).
 * 
 * This is a modified (fallback) implementation of
 * ResolvedReferenceTypeDeclaration.getAllAncestors() that we use in case, for
 * example, that external classes are extended (which would throw an
 * UnresolvedSymbolException).
 * 
 * @param resolvedClass
 * @return ancestors
 */
private static List<ResolvedReferenceType> getAllResolvableAncestors(
		ResolvedReferenceTypeDeclaration resolvedClass) {
	List<ResolvedReferenceType> ancestors = new ArrayList<>();

	if (!(Object.class.getCanonicalName().equals(resolvedClass.getQualifiedName()))) {
		// Get all direct ancestors that can be resolved
		for (ResolvedReferenceType ancestor : resolvedClass.getAncestors(true)) {
			ancestors.add(ancestor);
			// Get indirect ancestors recursively
			for (ResolvedReferenceType inheritedAncestor : getAllResolvableAncestors(
					ancestor.getTypeDeclaration())) {
				if (!ancestors.contains(inheritedAncestor)) {
					ancestors.add(inheritedAncestor);
				}
			}
		}
	}

	return ancestors;
}
 
Example 4
Source Project: JRemapper   Source File: Input.java    License: MIT License 6 votes vote down vote up
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {
	try {
		String internal = name.replace(".", "/");
		if(hasRawClass(internal)) {
			InputStream is = new ByteArrayInputStream(getRawClass(internal));
			ResolvedReferenceTypeDeclaration dec = toTypeDeclaration(classPool.makeClass(is), getRoot());
			SymbolReference<ResolvedReferenceTypeDeclaration> solved = SymbolReference.solved(dec);
			if (solved.isSolved())
				return solved;
		}
	} catch(IOException ex) {
		throw new IllegalStateException("Failed to resolve type: " + name, ex);
	}
	return childSolver.tryToSolveType(name);
}
 
Example 5
Source Project: flow   Source File: OpenApiObjectGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method return a fully qualified name from a resolved reference type
 * which is correct for nested declaration as well. The
 * {@link ResolvedReferenceType#getQualifiedName()} returns a canonical name
 * instead of a fully qualified name, which is not correct for nested
 * classes to be used in reflection. That's why this method is implemented.
 *
 * {@see Related discussion about FullyQualifiedName and CanonicalName:
 * https://github.com/javaparser/javaparser/issues/1480}
 *
 * @param resolvedReferenceType
 *            the type to get fully qualified name
 * @return fully qualified name
 */
private String getFullyQualifiedName(
        ResolvedReferenceType resolvedReferenceType) {
    ResolvedReferenceTypeDeclaration typeDeclaration = resolvedReferenceType
            .getTypeDeclaration();
    String packageName = typeDeclaration.getPackageName();
    String canonicalName = typeDeclaration.getQualifiedName();
    if (GeneratorUtils.isBlank(packageName)) {
        return GeneratorUtils.replaceChars(canonicalName, '.', '$');
    } else {
        String name = GeneratorUtils.substringAfterLast(canonicalName,
                packageName + ".");
        return String.format("%s.%s", packageName,
                GeneratorUtils.replaceChars(name, '.', '$'));
    }
}
 
Example 6
Source Project: jeddict   Source File: BeanClass.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void load(ClassExplorer clazz) {
    super.load(clazz);
    this.getAttributes().load(clazz);

    Optional<ResolvedReferenceTypeDeclaration> superClassTypeOpt = clazz.getSuperClass();
    if (superClassTypeOpt.isPresent()) {
        ResolvedReferenceTypeDeclaration superClassType = superClassTypeOpt.get();
        Optional<BeanClass> superClassOpt = clazz.getSource().findBeanClass(superClassType);
        if (superClassOpt.isPresent()) {
            super.addSuperclass(superClassOpt.get());
        } else {
            this.setSuperclassRef(new ReferenceClass(superClassType.getQualifiedName()));
        }
    }
}
 
Example 7
Source Project: jeddict   Source File: SourceExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<Embeddable> findEmbeddable(ResolvedReferenceTypeDeclaration type) {
    Optional<Embeddable> embeddableOpt = entityMappings.findEmbeddable(type.getClassName());
    if (!embeddableOpt.isPresent()
            && (isIncludeReference() || isSelectedClass(type.getClassName()))) {
        try {
            embeddableOpt = createClass(type.getQualifiedName()).map(clazz -> {
                Embeddable embeddable = new Embeddable();
                embeddable.setClazz(clazz.getName());
                entityMappings.addEmbeddable(embeddable);
                embeddable.load(clazz);
                return embeddable;
            });
        } catch (FileNotFoundException ex) {
            addMissingClass(type.getQualifiedName());
        }
    }
    return embeddableOpt;
}
 
Example 8
Source Project: jeddict   Source File: SourceExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<Entity> findEntity(ResolvedReferenceTypeDeclaration type) {
    Optional<Entity> entityOpt = entityMappings.findEntity(type.getClassName());
    if (!entityOpt.isPresent()
            && (isIncludeReference() || isSelectedClass(type.getClassName()))) {
        try {
            entityOpt = createClass(type.getQualifiedName()).map(clazz -> {
                Entity entity = new Entity();
                entity.setClazz(clazz.getName());
                entityMappings.addEntity(entity);
                entity.load(clazz);
                return entity;
            });
        } catch (FileNotFoundException ex) {
            addMissingClass(type.getQualifiedName());
        }
    }
    return entityOpt;
}
 
Example 9
Source Project: jeddict   Source File: SourceExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<MappedSuperclass> findMappedSuperclass(ResolvedReferenceTypeDeclaration type) {
    Optional<MappedSuperclass> mappedSuperclassOpt = entityMappings.findMappedSuperclass(type.getClassName());
    if (!mappedSuperclassOpt.isPresent()
            && (isIncludeReference() || isSelectedClass(type.getClassName()))) {
        try {
            mappedSuperclassOpt = createClass(type.getQualifiedName()).map(clazz -> {
                MappedSuperclass mappedSuperclass = new MappedSuperclass();
                mappedSuperclass.setClazz(clazz.getName());
                entityMappings.addMappedSuperclass(mappedSuperclass);
                mappedSuperclass.load(clazz);
                return mappedSuperclass;
            });
        } catch (FileNotFoundException ex) {
            addMissingClass(type.getQualifiedName());
        }
    }
    return mappedSuperclassOpt;
}
 
Example 10
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 5 votes vote down vote up
/**
 * @param targetClass
 * @param targetMethod
 * @return list of resolved classes and interfaces which are ancestors of the
 *         given classes (not including java.lang.Object or external
 *         dependencies) and contain the given target method
 * @throws BotRefactoringException
 */
private static Set<ResolvedReferenceTypeDeclaration> findAllAncestors(ClassOrInterfaceDeclaration targetClass,
		MethodDeclaration targetMethod) throws BotRefactoringException {
	List<ResolvedReferenceType> ancestors = new ArrayList<>();
	Set<ResolvedReferenceTypeDeclaration> result = new HashSet<>();

	try {
		ancestors = targetClass.resolve().getAllAncestors();
	} catch (UnsolvedSymbolException u) {
		ancestors = RefactoringHelper.getAllResolvableAncestors(targetClass.resolve());
		logger.warn("Refactored classes might extend/implement classes or interfaces from external dependency! "
				+ "Please validate the correctness of the refactoring.");
		// TODO propagate warning
	} catch (InvalidPathException i) {
		throw new BotRefactoringException("Javaparser could not parse file: " + i.getMessage());
	} catch (Exception e) {
		throw new BotRefactoringException("Error while resolving superclasses occured!");
	}

	for (ResolvedReferenceType ancestor : ancestors) {
		if (!ancestor.getQualifiedName().equals("java.lang.Object")) {
			for (ResolvedMethodDeclaration method : ancestor.getAllMethods()) {
				if (method.getSignature().equals(targetMethod.resolve().getSignature())) {
					result.add(ancestor.getTypeDeclaration());
				}
			}
		}
	}

	return result;
}
 
Example 11
Source Project: jeddict   Source File: Embedded.java    License: Apache License 2.0 5 votes vote down vote up
public static Embedded load(Embedded embedded, MemberExplorer member) {
    embedded.loadAttribute(member);
    embedded.getAttributeOverride().addAll(AttributeOverride.load(member));
    embedded.getAssociationOverride().addAll(AssociationOverride.load(member));
    embedded.setAccess(AccessType.load(member));

    ResolvedReferenceTypeDeclaration type = member.getTypeDeclaration();
    Optional<Embeddable> embeddableOpt = member.getSource().findEmbeddable(type);
    if (!embeddableOpt.isPresent()) {
        return null;
    }
    embedded.setConnectedClass(embeddableOpt.get());
    embedded.setConverts(Convert.load(member));
    return embedded;
}
 
Example 12
Source Project: jeddict   Source File: Embeddable.java    License: Apache License 2.0 5 votes vote down vote up
public void load(ClassExplorer clazz) {
    Optional<ResolvedReferenceTypeDeclaration> superClassTypeOpt = clazz.getSuperClass();
    if (superClassTypeOpt.isPresent()) {
        ResolvedReferenceTypeDeclaration superClassType = superClassTypeOpt.get();
        if (superClassType.hasDirectlyAnnotation(EMBEDDABLE_FQN)) {
            Optional<Embeddable> superEmbeddableOpt = clazz.getSource().findEmbeddable(superClassType);
            if (superEmbeddableOpt.isPresent()) {
                super.addSuperclass(superEmbeddableOpt.get());
            }
        } else {
            this.setSuperclassRef(new ReferenceClass(superClassType.getQualifiedName()));
        }
    }
    super.load(clazz);
}
 
Example 13
Source Project: jeddict   Source File: OneToManyAssociation.java    License: Apache License 2.0 5 votes vote down vote up
public static OneToManyAssociation load(MemberExplorer member, ResolvedReferenceTypeDeclaration type) {
    OneToManyAssociation attribute = new OneToManyAssociation();
    attribute.loadAttribute(member);
    attribute.setCollectionType(member.getType());

    Optional<BeanClass> beanClassOpt = member.getSource().findBeanClass(type);
    if (!beanClassOpt.isPresent()) {
        return null;
    }
    attribute.setConnectedClass(beanClassOpt.get());
    return attribute;
}
 
Example 14
Source Project: jeddict   Source File: ClassExplorer.java    License: Apache License 2.0 5 votes vote down vote up
public Optional<ResolvedReferenceTypeDeclaration> getSuperClass() {
    ResolvedReferenceTypeDeclaration superClassType = null;
    if (type instanceof ClassOrInterfaceDeclaration) {
        ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) type;
        if (!clazz.getExtendedTypes().isEmpty()) {
            superClassType = clazz.getExtendedTypes().get(0).resolve().asReferenceType().getTypeDeclaration();
        }
    }
    return Optional.ofNullable(superClassType);
}
 
Example 15
Source Project: jeddict   Source File: ClassloaderTypeSolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {
    try {
        // Some implementations could return null when the class was loaded through the bootstrap classloader
            // see https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--
            if (classLoader == null) {
                throw new RuntimeException("The ClassloaderTypeSolver has been probably loaded through the bootstrap class loader. This usage is not supported by the JavaSymbolSolver");
            }

            Class<?> clazz = classLoader.loadClass(name);
            return SymbolReference.solved(ReflectionFactory.typeDeclarationFor(clazz, getRoot()));
        } catch (ClassNotFoundException e) {
            // it could be an inner class
            int lastDot = name.lastIndexOf('.');
            if (lastDot == -1) {
                return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class);
            } else {
                String parentName = name.substring(0, lastDot);
                String childName = name.substring(lastDot + 1);
                SymbolReference<ResolvedReferenceTypeDeclaration> parent = tryToSolveType(parentName);
                if (parent.isSolved()) {
                    Optional<ResolvedReferenceTypeDeclaration> innerClass = parent.getCorrespondingDeclaration().internalTypes()
                            .stream().filter(it -> it.getName().equals(childName)).findFirst();
                    if (innerClass.isPresent()) {
                        return SymbolReference.solved(innerClass.get());
                    } else {
                        return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class);
                    }
                } else {
                    return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class);
                }
            }
        }
}
 
Example 16
Source Project: jeddict   Source File: MultiRelationAttribute.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void loadAttribute(MemberExplorer member, AnnotationExplorer annotation) {
    super.loadAttribute(member, annotation);

    annotation.getString("mappedBy").ifPresent(this::setMappedBy);

    this.orderBy = OrderBy.load(member);
    this.orderColumn = OrderColumn.load(member);
    this.collectionType = member.getType();
    Class collectionTypeClass = null;
    try {
        collectionTypeClass = Class.forName(this.collectionType);
    } catch (ClassNotFoundException ex) {
    }
    boolean mapKeyExist = collectionTypeClass != null && Map.class.isAssignableFrom(collectionTypeClass);

    Optional<ResolvedTypeDeclaration> targetEntityOpt = annotation.getResolvedClass("targetEntity");
    ResolvedTypeDeclaration targetEntityValue;
    if (targetEntityOpt.isPresent()) {
        targetEntityValue = targetEntityOpt.get();
    } else {
        targetEntityOpt = member.getTypeArgumentDeclaration(mapKeyExist ? 1 : 0);
        if (targetEntityOpt.isPresent()) {
            targetEntityValue = targetEntityOpt.get();
            this.setValueConstraints(member.getTypeArgumentBeanValidationConstraints(mapKeyExist ? 1 : 0));
        } else {
            throw new UnsolvedSymbolException("targetEntity or generic type not defined in relation attribute '" + member.getFieldName() + "'");
        }
    }
    this.targetEntityPackage = targetEntityValue.getPackageName();
    this.targetEntity = targetEntityValue.getClassName();

    if (mapKeyExist) {
        this.mapKeyConvert = Convert.load(member, mapKeyExist, true);
        this.mapKey = MapKey.load(member);
        this.mapKeyType = this.mapKey != null ? MapKeyType.EXT : MapKeyType.NEW;

        ResolvedTypeDeclaration keyType = MapKeyClass.getDeclaredType(member);
        if (keyType instanceof ResolvedReferenceTypeDeclaration) {
            ResolvedReferenceTypeDeclaration refKeyType = (ResolvedReferenceTypeDeclaration) keyType;
            if (refKeyType.hasDirectlyAnnotation(EMBEDDABLE_FQN)) {
                Optional<Embeddable> embeddableOpt = member.getSource().findEmbeddable(refKeyType);
                if (!embeddableOpt.isPresent()) {
                    throw new IllegalStateException("Embeddable Not found " + keyType.getQualifiedName());
                }
                this.mapKeyAttributeType = embeddableOpt.get().getClazz(); //TODO set Embeddable
            } else if (refKeyType.hasDirectlyAnnotation(ENTITY_FQN)) {
                Optional<Entity> entityOpt = member.getSource().findEntity(refKeyType);
                if (!entityOpt.isPresent()) {
                    throw new IllegalStateException("Entity Not found " + keyType.getQualifiedName());
                }
                this.mapKeyAttributeType = entityOpt.get().getClazz(); //TODO set Entity
            }
        } else {
            this.mapKeyAttributeType = keyType.getQualifiedName();
        }

        this.mapKeyColumn = Column.loadMapKey(member);
        this.mapKeyTemporal = TemporalType.loadMapKey(member);
        this.mapKeyEnumerated = EnumType.loadMapKey(member);
        this.mapKeyJoinColumn = JoinColumn.loadMapKey(member);

        member.getAnnotation(javax.persistence.ForeignKey.class)
                .map(ForeignKey::load)
                .ifPresent(this::setMapKeyForeignKey);
        this.mapKeyAttributeOverride = AttributeOverride.load(member);
    }
}
 
Example 17
Source Project: jeddict   Source File: MemberExplorer.java    License: Apache License 2.0 4 votes vote down vote up
public ResolvedReferenceTypeDeclaration getTypeDeclaration() {
    return getReferenceType().getTypeDeclaration();
}