Search in sources :

Example 36 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.

the class CompilationUnitContext method fieldsExposedToChild.

@Override
public List<ResolvedFieldDeclaration> fieldsExposedToChild(Node child) {
    List<ResolvedFieldDeclaration> res = new LinkedList<>();
    // Consider the static imports for static fields
    for (ImportDeclaration importDeclaration : wrappedNode.getImports()) {
        if (importDeclaration.isStatic()) {
            Name typeNameAsNode = importDeclaration.isAsterisk() ? importDeclaration.getName() : importDeclaration.getName().getQualifier().get();
            String typeName = typeNameAsNode.asString();
            ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(typeName);
            res.addAll(typeDeclaration.getAllFields().stream().filter(f -> f.isStatic()).filter(f -> importDeclaration.isAsterisk() || importDeclaration.getName().getIdentifier().equals(f.getName())).collect(Collectors.toList()));
        }
    }
    return res;
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) JavaParserAnnotationDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserAnnotationDeclaration) Name(com.github.javaparser.ast.expr.Name) JavaParserInterfaceDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserInterfaceDeclaration) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) AbstractJavaParserContext.isQualifiedName(com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.isQualifiedName) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) ResolvedFieldDeclaration(com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration) JavaParserClassDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserClassDeclaration) CompilationUnit(com.github.javaparser.ast.CompilationUnit) LinkedList(java.util.LinkedList) JavaParserEnumDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserEnumDeclaration) Node(com.github.javaparser.ast.Node) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) Collectors(java.util.stream.Collectors) AssociableToAST(com.github.javaparser.resolution.declarations.AssociableToAST) List(java.util.List) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Optional(java.util.Optional) AnnotationDeclaration(com.github.javaparser.ast.body.AnnotationDeclaration) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedFieldDeclaration(com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) LinkedList(java.util.LinkedList) Name(com.github.javaparser.ast.expr.Name) AbstractJavaParserContext.isQualifiedName(com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.isQualifiedName)

Example 37 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.

the class JavaParserFacade method toMethodUsage.

protected MethodUsage toMethodUsage(MethodReferenceExpr methodReferenceExpr, List<ResolvedType> paramTypes) {
    Expression scope = methodReferenceExpr.getScope();
    ResolvedType typeOfScope = getType(methodReferenceExpr.getScope());
    if (!typeOfScope.isReferenceType()) {
        throw new UnsupportedOperationException(typeOfScope.getClass().getCanonicalName());
    }
    Optional<MethodUsage> result;
    Set<MethodUsage> allMethods = typeOfScope.asReferenceType().getTypeDeclaration().orElseThrow(() -> new RuntimeException("TypeDeclaration unexpectedly empty.")).getAllMethods();
    if (scope.isTypeExpr()) {
        // static methods should match all params
        List<MethodUsage> staticMethodUsages = allMethods.stream().filter(it -> it.getDeclaration().isStatic()).collect(Collectors.toList());
        result = MethodResolutionLogic.findMostApplicableUsage(staticMethodUsages, methodReferenceExpr.getIdentifier(), paramTypes, typeSolver);
        if (!paramTypes.isEmpty()) {
            // instance methods are called on the first param and should match all other params
            List<MethodUsage> instanceMethodUsages = allMethods.stream().filter(it -> !it.getDeclaration().isStatic()).collect(Collectors.toList());
            List<ResolvedType> instanceMethodParamTypes = new ArrayList<>(paramTypes);
            // remove the first one
            instanceMethodParamTypes.remove(0);
            Optional<MethodUsage> instanceResult = MethodResolutionLogic.findMostApplicableUsage(instanceMethodUsages, methodReferenceExpr.getIdentifier(), instanceMethodParamTypes, typeSolver);
            if (result.isPresent() && instanceResult.isPresent()) {
                throw new MethodAmbiguityException("Ambiguous method call: cannot find a most applicable method for " + methodReferenceExpr.getIdentifier());
            }
            if (instanceResult.isPresent()) {
                result = instanceResult;
            }
        }
    } else {
        result = MethodResolutionLogic.findMostApplicableUsage(new ArrayList<>(allMethods), methodReferenceExpr.getIdentifier(), paramTypes, typeSolver);
        if (result.isPresent() && result.get().getDeclaration().isStatic()) {
            throw new RuntimeException("Invalid static method reference " + methodReferenceExpr.getIdentifier());
        }
    }
    if (!result.isPresent()) {
        throw new UnsupportedOperationException();
    }
    return result.get();
}
Also used : FieldAccessContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.FieldAccessContext) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) SymbolReference.solved(com.github.javaparser.symbolsolver.model.resolution.SymbolReference.solved) ReflectionEnumDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionEnumDeclaration) DataKey(com.github.javaparser.ast.DataKey) UnionType(com.github.javaparser.ast.type.UnionType) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) Type(com.github.javaparser.ast.type.Type) Context(com.github.javaparser.symbolsolver.core.resolution.Context) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaParserEnumDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserEnumDeclaration) Node(com.github.javaparser.ast.Node) NodeList(com.github.javaparser.ast.NodeList) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) ResolvedAnnotationDeclaration(com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) Set(java.util.Set) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) Collectors(java.util.stream.Collectors) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) JavaParserAnonymousClassDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserAnonymousClassDeclaration) List(java.util.List) ResolvedPrimitiveType(com.github.javaparser.resolution.types.ResolvedPrimitiveType) Optional(java.util.Optional) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ResolvedUnionType(com.github.javaparser.resolution.types.ResolvedUnionType) ReflectionAnnotationDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionAnnotationDeclaration) MethodUsage(com.github.javaparser.resolution.MethodUsage) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Log(com.github.javaparser.utils.Log) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) ResolvedArrayType(com.github.javaparser.resolution.types.ResolvedArrayType) MethodAmbiguityException(com.github.javaparser.resolution.MethodAmbiguityException) ConstructorResolutionLogic(com.github.javaparser.symbolsolver.resolution.ConstructorResolutionLogic) Navigator.demandParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.demandParentNode) LinkedList(java.util.LinkedList) WeakHashMap(java.util.WeakHashMap) ArrayType(com.github.javaparser.ast.type.ArrayType) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) ResolvedWildcard(com.github.javaparser.resolution.types.ResolvedWildcard) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ResolvedConstructorDeclaration(com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration) ReferenceTypeImpl(com.github.javaparser.symbolsolver.model.typesystem.ReferenceTypeImpl) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) SymbolReference.unsolved(com.github.javaparser.symbolsolver.model.resolution.SymbolReference.unsolved) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) ResolvedClassDeclaration(com.github.javaparser.resolution.declarations.ResolvedClassDeclaration) ResolvedVoidType(com.github.javaparser.resolution.types.ResolvedVoidType) VarType(com.github.javaparser.ast.type.VarType) WildcardType(com.github.javaparser.ast.type.WildcardType) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) ReflectionInterfaceDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionInterfaceDeclaration) Collections(java.util.Collections) com.github.javaparser.ast.expr(com.github.javaparser.ast.expr) ResolvedTypeVariable(com.github.javaparser.resolution.types.ResolvedTypeVariable) MethodAmbiguityException(com.github.javaparser.resolution.MethodAmbiguityException) ArrayList(java.util.ArrayList) MethodUsage(com.github.javaparser.resolution.MethodUsage) ResolvedType(com.github.javaparser.resolution.types.ResolvedType)

Example 38 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.

the class JavaParserTypeDeclarationAdapter method solveMethod.

public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly) {
    // Begin by locating methods declared "here"
    List<ResolvedMethodDeclaration> candidateMethods = typeDeclaration.getDeclaredMethods().stream().filter(m -> m.getName().equals(name)).filter(m -> !staticOnly || m.isStatic()).collect(Collectors.toList());
    // Note that we only consider ancestors when we are not currently at java.lang.Object (avoiding infinite recursion).
    if (!typeDeclaration.isJavaLangObject()) {
        for (ResolvedReferenceType ancestor : typeDeclaration.getAncestors(true)) {
            Optional<ResolvedReferenceTypeDeclaration> ancestorTypeDeclaration = ancestor.getTypeDeclaration();
            // Avoid recursion on self
            if (ancestor.getTypeDeclaration().isPresent() && typeDeclaration != ancestorTypeDeclaration.get()) {
                // Consider methods declared on self
                candidateMethods.addAll(ancestor.getAllMethodsVisibleToInheritors().stream().filter(m -> m.getName().equals(name)).collect(Collectors.toList()));
                // consider methods from superclasses and only default methods from interfaces :
                // not true, we should keep abstract as a valid candidate
                // abstract are removed in MethodResolutionLogic.isApplicable is necessary
                SymbolReference<ResolvedMethodDeclaration> res = MethodResolutionLogic.solveMethodInType(ancestorTypeDeclaration.get(), name, argumentsTypes, staticOnly);
                if (res.isSolved()) {
                    candidateMethods.add(res.getCorrespondingDeclaration());
                }
            }
        }
    }
    // Note that we want to avoid infinite recursion when a class is using its own method - see issue #75
    if (candidateMethods.isEmpty()) {
        SymbolReference<ResolvedMethodDeclaration> parentSolution = context.getParent().orElseThrow(() -> new RuntimeException("Parent context unexpectedly empty.")).solveMethod(name, argumentsTypes, staticOnly);
        if (parentSolution.isSolved()) {
            candidateMethods.add(parentSolution.getCorrespondingDeclaration());
        }
    }
    // if is interface and candidate method list is empty, we should check the Object Methods
    if (candidateMethods.isEmpty() && typeDeclaration.isInterface()) {
        SymbolReference<ResolvedMethodDeclaration> res = MethodResolutionLogic.solveMethodInType(new ReflectionClassDeclaration(Object.class, typeSolver), name, argumentsTypes, false);
        if (res.isSolved()) {
            candidateMethods.add(res.getCorrespondingDeclaration());
        }
    }
    return MethodResolutionLogic.findMostApplicable(candidateMethods, name, argumentsTypes, typeSolver);
}
Also used : JavaParserFactory(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFactory) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) AccessSpecifier(com.github.javaparser.ast.AccessSpecifier) NodeWithExtends(com.github.javaparser.ast.nodeTypes.NodeWithExtends) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) Context(com.github.javaparser.symbolsolver.core.resolution.Context) NodeWithTypeParameters(com.github.javaparser.ast.nodeTypes.NodeWithTypeParameters) ConstructorResolutionLogic(com.github.javaparser.symbolsolver.resolution.ConstructorResolutionLogic) NodeWithImplements(com.github.javaparser.ast.nodeTypes.NodeWithImplements) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) TypeParameter(com.github.javaparser.ast.type.TypeParameter) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ResolvedConstructorDeclaration(com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) TreeTraversal(com.github.javaparser.ast.Node.TreeTraversal) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) Collectors(java.util.stream.Collectors) ResolvedClassDeclaration(com.github.javaparser.resolution.declarations.ResolvedClassDeclaration) HasAccessSpecifier(com.github.javaparser.resolution.declarations.HasAccessSpecifier) List(java.util.List) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) JavaParserTypeParameter(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserTypeParameter) Optional(java.util.Optional) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)

Example 39 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.

the class MethodVisitorAdapter method visit.

@Override
public void visit(final MethodCallExpr methodCall, final Object arg) {
    final Map<String, Object> params = (HashMap) arg;
    final String clsName = (String) params.get("clsName");
    final JavaParserFacade facade = (JavaParserFacade) params.get("facade");
    final App app = (App) params.get("app");
    logger.info("###### " + clsName + ": " + methodCall.getName());
    try {
        // //// !!!!!!!!!!! Methoden-Aufruf kann in den meisten Fällen nicht aufgelöst werden!!
        final SymbolReference<ResolvedMethodDeclaration> ref = facade.solve(methodCall);
        if (ref.isSolved()) {
            final String qualifiedSignature = ref.getCorrespondingDeclaration().getQualifiedSignature();
            // final String scopeString = scope.toString();
            final String parentNodeAsString = methodCall.getParentNode().toString();
            // logger.info("Resolved to " + qualifiedSignature + ", scope: " + scopeString + ", parent node: " + parentNodeAsString);
            logger.info("Resolved to " + qualifiedSignature + ", parent node: " + parentNodeAsString);
            final String calledMethodQualifiedName = StringUtils.replacePattern(qualifiedSignature, "\\(.*\\)", "");
            final String calledMethodQualifiedClassName = StringUtils.substringBeforeLast(calledMethodQualifiedName, ".");
            final String calledMethodName = StringUtils.substringAfterLast(calledMethodQualifiedName, ".");
            Method calledMethod = null;
            final JavaClass calledMethodClass = (JavaClass) app.nodeQuery(JavaClass.class).and(JavaClass.name, calledMethodQualifiedClassName).getFirst();
            if (calledMethodClass != null) {
                logger.info("└ Found called class in graph: " + calledMethodClass.getName());
                calledMethod = (Method) app.nodeQuery(Method.class).and(Method.name, calledMethodName).and(Method.classOrInterface, calledMethodClass).getFirst();
                if (calledMethod != null) {
                    logger.info("└ Found called method in graph: " + calledMethod.getProperty(Method.declaration));
                    final Optional<MethodDeclaration> callingMethod = methodCall.getAncestorOfType(MethodDeclaration.class);
                    if (callingMethod.isPresent()) {
                        final String callingMethodDeclaration = callingMethod.get().getDeclarationAsString();
                        logger.info("└ Calling method: " + callingMethodDeclaration);
                        final String callingMethodName = callingMethod.get().getNameAsString();
                        final Optional<TypeDeclaration> typeDecl = callingMethod.get().getAncestorOfType(TypeDeclaration.class);
                        if (typeDecl.isPresent()) {
                            final String callingMethodClassName = typeDecl.get().getNameAsString();
                            // Find compilation unit
                            final Optional<CompilationUnit> localCU = typeDecl.get().getAncestorOfType(CompilationUnit.class);
                            if (localCU.isPresent()) {
                                // Does it have a package declaration?
                                final Optional<PackageDeclaration> packageDecl = localCU.get().getPackageDeclaration();
                                if (packageDecl.isPresent()) {
                                    // Assemble qualified class name
                                    final String packageName = packageDecl.get().getNameAsString();
                                    final String fqcn = packageName + "." + callingMethodClassName;
                                    // Find class in graph
                                    final JavaClass callingClass = (JavaClass) app.nodeQuery(JavaClass.class).and(JavaClass.name, fqcn).getFirst();
                                    if (callingClass != null) {
                                        final Method method = (Method) app.nodeQuery(Method.class).and(Method.name, callingMethodName).and(Method.classOrInterface, callingClass).getFirst();
                                        if (method != null) {
                                            logger.info("Found calling method in graph: " + method.getName());
                                            final List<Method> methodsCalled = Iterables.toList(method.getProperty(Method.methodsCalled));
                                            methodsCalled.add(calledMethod);
                                            method.setProperty(Method.methodsCalled, methodsCalled);
                                            logger.info("Added " + calledMethod.getName() + " to list of methods called in " + method.getName());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (final Throwable t) {
        logger.info("Unable to resolve " + clsName, t);
    }
}
Also used : App(org.structr.core.app.App) CompilationUnit(com.github.javaparser.ast.CompilationUnit) HashMap(java.util.HashMap) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Method(org.structr.javaparser.entity.Method) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) JavaClass(org.structr.javaparser.entity.JavaClass) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration)

Example 40 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project Hidoc by yuzhengyang.

the class JavaDocCreateService method parseJavaDoc.

// @Transactional
// public ResponseData upload(String projectId, MultipartFile[] files) {
// 
// // 参数判断检查
// if (!ListTool.ok(files)) return ResponseData.error("请选择文件");
// 
// JavaDocProject javaDocProject = javaDocProjectMapper.selectById(projectId);
// if (javaDocProject == null) return ResponseData.error("JavaDoc项目不存在");
// 
// SysUser curUser = CurrentUserManager.getUser();
// 
// // 更新项目信息
// javaDocProject.setUpdateUserId(curUser.getId());
// javaDocProject.setUpdateTime(LocalDateTime.now());
// javaDocProject.setVersion(String.valueOf(System.currentTimeMillis()));
// List<JavaDocClass> javaDocClassList = new ArrayList<>();
// List<JavaDocMethod> javaDocMethodList = new ArrayList<>();
// 
// // 准备数据开始分解存储
// for (MultipartFile file : files) {
// try {
// parseJavaDoc(cu, javaDocProject, javaDocClassList, javaDocMethodList);
// } catch (IOException ex) {
// }
// }
// 
// // 最终汇总数据
// if (javaDocProject != null && javaDocClassList != null && javaDocMethodList != null) {
// javaDocProjectMapper.updateById(javaDocProject);
// 
// if (ListTool.ok(javaDocClassList)) {
// for (JavaDocClass item : javaDocClassList) {
// javaDocClassMapper.insert(item);
// }
// }
// 
// if (ListTool.ok(javaDocMethodList)) {
// for (JavaDocMethod item : javaDocMethodList) {
// javaDocMethodMapper.insert(item);
// }
// }
// return ResponseData.ok("JavaDoc创建完成");
// }
// return ResponseData.error("没有发现要创建的内容");
// }
private void parseJavaDoc(String filepath, JavaDocProject javaDocProject, List<JavaDocClass> javaDocClassList, List<JavaDocMethod> javaDocMethodList) throws FileNotFoundException {
    SysUser curUser = CurrentUserManager.getUser();
    List<String> oriDocTextList = TxtTool.readLine(filepath);
    String oriDocText = String.join(StringConst.NEWLINE, oriDocTextList);
    // parse() 参数可以是 String, File, InputStream等
    CompilationUnit cu = StaticJavaParser.parse(new File(filepath));
    List<TypeDeclaration> typeList = cu.findAll(TypeDeclaration.class);
    // 遍历类信息
    if (ListTool.ok(typeList)) {
        for (TypeDeclaration typeItem : typeList) {
            // 创建类信息
            JavaDocClass javaDocClass = new JavaDocClass();
            javaDocClass.setId(R.SnowFlake.nexts());
            javaDocClass.setProjectId(javaDocProject.getId());
            javaDocClass.setProjectName(javaDocProject.getName());
            javaDocClass.setVersion(javaDocProject.getVersion());
            javaDocClass.setCreateUserId(curUser.getId());
            javaDocClass.setCreateTime(LocalDateTime.now());
            javaDocClass.setName(typeItem.getNameAsString());
            javaDocClass.setOriginalDocument(cu.toString());
            javaDocClass.setIsStruct(false);
            if (typeItem.hasParentNode() && typeItem.getParentNode().isPresent() && typeItem.getParentNode().get().findCompilationUnit().isPresent()) {
                CompilationUnit parentNode = typeItem.getParentNode().get().findCompilationUnit().get();
                // 填充包信息
                if (parentNode.getPackageDeclaration().isPresent()) {
                    javaDocClass.setPackageInfo(parentNode.getPackageDeclaration().get().getNameAsString());
                }
                // 填充引用信息
                if (ListTool.ok(parentNode.getImports())) {
                    List<Object> importsJson = new ArrayList<>(parentNode.getImports().size());
                    StringBuilder stringBuilder = new StringBuilder();
                    for (ImportDeclaration nodeItem : parentNode.getImports()) {
                        stringBuilder.append(nodeItem.getNameAsString());
                        stringBuilder.append(" ");
                        importsJson.add(nodeItem.getNameAsString());
                    }
                    javaDocClass.setImports(stringBuilder.toString());
                    javaDocClass.setImportsJson(new JSONArray(importsJson));
                }
                // 填充修饰词
                if (ListTool.ok(typeItem.getModifiers())) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (Object modObject : typeItem.getModifiers()) {
                        if (modObject.getClass().equals(Modifier.class)) {
                            Modifier modItem = (Modifier) modObject;
                            stringBuilder.append(modItem.getKeyword().asString());
                            stringBuilder.append(" ");
                        }
                    }
                    javaDocClass.setQualifier(stringBuilder.toString());
                }
                // 填充注释内容
                StringBuilder stringBuilder = new StringBuilder();
                if (typeItem.getComment().isPresent()) {
                    String content = typeItem.getComment().get().getContent();
                    stringBuilder.append(content);
                }
                if (ListTool.ok(parentNode.getOrphanComments())) {
                    for (Comment commentItem : parentNode.getOrphanComments()) {
                        stringBuilder.append(commentItem.getContent());
                        stringBuilder.append(StringConst.NEWLINE);
                    }
                }
                if (stringBuilder.length() > 0) {
                    String[] commentArrays = parseComment(stringBuilder.toString());
                    javaDocClass.setCommentInfo(commentArrays[0]);
                    javaDocClass.setCommentScene(commentArrays[1]);
                    javaDocClass.setCommentLimit(commentArrays[2]);
                    javaDocClass.setCommentExample(commentArrays[3]);
                    javaDocClass.setCommentLog(commentArrays[4]);
                    javaDocClass.setCommentKeywords(commentArrays[5]);
                    javaDocClass.setCommentMenu(commentArrays[6]);
                    javaDocClass.setCommentLogJson(parseCommentLog(commentArrays[4]));
                    if (StringTool.ok(javaDocClass.getCommentScene()) || StringTool.ok(javaDocClass.getCommentLimit()) || StringTool.ok(javaDocClass.getCommentMenu()) || StringTool.ok(javaDocClass.getCommentKeywords())) {
                        javaDocClass.setIsStruct(true);
                    }
                }
            }
            javaDocClassList.add(javaDocClass);
            // 创建方法信息
            if (ListTool.ok(typeItem.getChildNodes())) {
                for (Node nodeItem : typeItem.getChildNodes()) {
                    if (nodeItem.getClass().equals(MethodDeclaration.class)) {
                        MethodDeclaration methodItem = (MethodDeclaration) nodeItem;
                        JavaDocMethod javaDocMethod = new JavaDocMethod();
                        javaDocMethod.setId(R.SnowFlake.nexts());
                        javaDocMethod.setClassId(javaDocClass.getId());
                        javaDocMethod.setClassName(javaDocClass.getName());
                        javaDocMethod.setProjectId(javaDocProject.getId());
                        javaDocMethod.setProjectName(javaDocProject.getName());
                        javaDocMethod.setVersion(javaDocProject.getVersion());
                        javaDocMethod.setCreateUserId(curUser.getId());
                        javaDocMethod.setCreateTime(LocalDateTime.now());
                        javaDocMethod.setName(methodItem.getNameAsString());
                        javaDocMethod.setSourceCode(methodItem.toString());
                        javaDocMethod.setIsStruct(false);
                        // 填充修饰词
                        if (ListTool.ok(methodItem.getModifiers())) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (Modifier modItem : methodItem.getModifiers()) {
                                stringBuilder.append(modItem.getKeyword().asString());
                            }
                            javaDocMethod.setQualifier(stringBuilder.toString());
                        }
                        // 填充传入参数
                        javaDocMethod.setReturnType(methodItem.getTypeAsString());
                        if (ListTool.ok(methodItem.getParameters())) {
                            StringBuilder stringBuilder = new StringBuilder();
                            JSONArray jsonArray = new JSONArray();
                            for (Parameter parameterItem : methodItem.getParameters()) {
                                stringBuilder.append(parameterItem.getTypeAsString());
                                stringBuilder.append(parameterItem.getNameAsString());
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("type", parameterItem.getTypeAsString());
                                jsonObject.put("name", parameterItem.getNameAsString());
                                jsonArray.add(jsonObject);
                            }
                            javaDocMethod.setParams(stringBuilder.toString());
                            javaDocMethod.setParamsJson(jsonArray);
                        }
                        // 填充注释内容
                        if (methodItem.getComment().isPresent()) {
                            String content = methodItem.getComment().get().getContent();
                            String[] commentArrays = parseComment(content);
                            javaDocMethod.setCommentInfo(commentArrays[0]);
                            javaDocMethod.setCommentScene(commentArrays[1]);
                            javaDocMethod.setCommentLimit(commentArrays[2]);
                            javaDocMethod.setCommentExample(commentArrays[3]);
                            javaDocMethod.setCommentLog(commentArrays[4]);
                            javaDocMethod.setCommentKeywords(commentArrays[5] + " , " + javaDocClass.getCommentKeywords());
                            javaDocMethod.setCommentMenu(commentArrays[6]);
                            javaDocMethod.setCommentLogJson(parseCommentLog(commentArrays[4]));
                            if (StringTool.ok(javaDocMethod.getCommentScene()) || StringTool.ok(javaDocMethod.getCommentLimit()) || StringTool.ok(javaDocMethod.getCommentMenu()) || StringTool.ok(javaDocMethod.getCommentKeywords())) {
                                javaDocMethod.setIsStruct(true);
                            }
                        }
                        if (!javaDocClass.getIsStruct())
                            javaDocMethod.setIsStruct(false);
                        javaDocMethodList.add(javaDocMethod);
                    }
                }
            }
        }
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Comment(com.github.javaparser.ast.comments.Comment) SysUser(com.yuzhyn.hidoc.app.application.entity.sys.SysUser) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) JavaDocMethod(com.yuzhyn.hidoc.app.application.entity.javadoc.JavaDocMethod) Node(com.github.javaparser.ast.Node) ArrayList(java.util.ArrayList) JSONArray(com.alibaba.fastjson.JSONArray) JSONObject(com.alibaba.fastjson.JSONObject) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) Parameter(com.github.javaparser.ast.body.Parameter) JSONObject(com.alibaba.fastjson.JSONObject) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) JavaDocClass(com.yuzhyn.hidoc.app.application.entity.javadoc.JavaDocClass) Modifier(com.github.javaparser.ast.Modifier)

Aggregations

TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)44 CompilationUnit (com.github.javaparser.ast.CompilationUnit)22 Node (com.github.javaparser.ast.Node)14 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)13 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)12 BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)10 ResolvedReferenceTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration)8 List (java.util.List)8 Optional (java.util.Optional)8 ResolvedTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration)6 SymbolReference (com.github.javaparser.symbolsolver.model.resolution.SymbolReference)6 Collectors (java.util.stream.Collectors)6 ImportDeclaration (com.github.javaparser.ast.ImportDeclaration)5 NodeList (com.github.javaparser.ast.NodeList)5 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)5 EnumDeclaration (com.github.javaparser.ast.body.EnumDeclaration)5 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)5 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)5 ResolvedValueDeclaration (com.github.javaparser.resolution.declarations.ResolvedValueDeclaration)5 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)5