I have a Spring boot project and I want to parse it and file the dependencies between classes I am using the JavaSymbolSolver to find out the Class Name
public static void main(String[] args) throws Exception {
Set<Map<String, Set<String>>> entries = new HashSet<>();
String jdkPath = "/usr/lib/jvm/java-11-openjdk-amd64/";
List<File> projectFiles = FileHandler.readJavaFiles(new File("/home/dell/MySpace/Tekit/soon-back/src/main"));
CombinedTypeSolver combinedSolver = new CombinedTypeSolver
(
new JavaParserTypeSolver(new File("/home/dell/MySpace/Tekit/soon-back/src/main/java/")),
new JavaParserTypeSolver(new File(jdkPath)),
new ReflectionTypeSolver()
);
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(combinedSolver);
StaticJavaParser.getConfiguration().setSymbolResolver(symbolSolver);
CompilationUnit cu = null;
try {
cu = StaticJavaParser.parse(projectFiles.get(7));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<ClassOrInterfaceDeclaration> classes = new ArrayList<>();
TypeDeclarationImp typeDeclarationImp = new TypeDeclarationImp();
typeDeclarationImp.visit(cu, classes);
Set<String> collect = classes.stream()
.map(classOrInterfaceDeclaration -> {
List<MethodCallExpr> collection = new ArrayList<>();
MethodInvocationImp methodInvocationImp = new MethodInvocationImp();
classOrInterfaceDeclaration.accept(methodInvocationImp, collection);
return collection;
})
.flatMap(Collection::stream)
.map(methodCallExpr -> {
return methodCallExpr
.getScope()
.stream()
.filter(Expression::isNameExpr)
.map(Expression::calculateResolvedType)
.map(ResolvedType::asReferenceType)
.map(ResolvedReferenceType::getQualifiedName)
.map(s -> s.split("\\."))
.map(strings -> strings[strings.length - 1])
.collect(Collectors.toSet());
})
.filter(expressions -> expressions.size() != 0)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
collect.forEach(System.out::println);
}
I am facing this issue
Exception in thread "main" UnsolvedSymbolException{context='SecurityContextHolder', name='Solving SecurityContextHolder', cause='null'}
It's not entirely correct. If you only want to traverse the AST you don't need to provide project dependencies but if you want for example to know the type of a variable you must use the symbol solver and declare all the dependencies of the project to it. Furthermore Javaparser can recover from parsing error (see https://matozoid.github.io/2017/06/11/parse-error-recovery.html)