Search in sources :

Example 1 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project checker-framework by typetools.

the class StubParser method getAllStubAnnotations.

/**
 * Returns all annotations found in the stub file, as a value for {@link #allStubAnnotations}.
 * Note that this also modifies {@link #importedConstants} and {@link #importedTypes}.
 *
 * @see #allStubAnnotations
 */
private Map<String, AnnotationMirror> getAllStubAnnotations() {
    Map<String, AnnotationMirror> result = new HashMap<>();
    assert !stubUnit.getCompilationUnits().isEmpty();
    CompilationUnit cu = stubUnit.getCompilationUnits().get(0);
    if (cu.getImports() == null) {
        return result;
    }
    for (ImportDeclaration importDecl : cu.getImports()) {
        String imported = importDecl.getNameAsString();
        try {
            if (importDecl.isAsterisk()) {
                if (importDecl.isStatic()) {
                    // Wildcard import of members of a type (class or interface)
                    TypeElement element = getTypeElement(imported, "Imported type not found");
                    if (element != null) {
                        // Find nested annotations
                        // Find compile time constant fields, or values of an enum
                        putAllNew(result, annosInType(element));
                        importedConstants.addAll(getImportableMembers(element));
                        addEnclosingTypesToImportedTypes(element);
                    }
                } else {
                    // Wildcard import of members of a package
                    PackageElement element = findPackage(imported);
                    if (element != null) {
                        putAllNew(result, annosInPackage(element));
                        addEnclosingTypesToImportedTypes(element);
                    }
                }
            } else {
                // A single (non-wildcard) import
                final TypeElement importType = elements.getTypeElement(imported);
                if (importType == null && !importDecl.isStatic()) {
                    // Class or nested class (according to JSL), but we can't resolve
                    stubWarnNotFound("Imported type not found: " + imported);
                } else if (importType == null) {
                    // Nested Field
                    Pair<String, String> typeParts = StubUtil.partitionQualifiedName(imported);
                    String type = typeParts.first;
                    String fieldName = typeParts.second;
                    TypeElement enclType = getTypeElement(type, String.format("Enclosing type of static field %s not found", fieldName));
                    if (enclType != null) {
                        if (findFieldElement(enclType, fieldName) != null) {
                            importedConstants.add(imported);
                        }
                    }
                } else if (importType.getKind() == ElementKind.ANNOTATION_TYPE) {
                    // Single annotation or nested annotation
                    AnnotationMirror anno = AnnotationBuilder.fromName(elements, imported);
                    if (anno != null) {
                        Element annoElt = anno.getAnnotationType().asElement();
                        putNoOverride(result, annoElt.getSimpleName().toString(), anno);
                        importedTypes.put(annoElt.getSimpleName().toString(), (TypeElement) annoElt);
                    } else {
                        stubWarnNotFound("Could not load import: " + imported);
                    }
                } else {
                    // Class or nested class
                    // TODO: Is this needed?
                    importedConstants.add(imported);
                    TypeElement element = getTypeElement(imported, "Imported type not found");
                    importedTypes.put(element.getSimpleName().toString(), element);
                }
            }
        } catch (AssertionError error) {
            stubWarnNotFound("" + error);
        }
    }
    return result;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) AnnotationMirror(javax.lang.model.element.AnnotationMirror) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) PackageElement(javax.lang.model.element.PackageElement) Pair(org.checkerframework.javacutil.Pair) MemberValuePair(com.github.javaparser.ast.expr.MemberValuePair)

Example 2 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project javaparser by javaparser.

the class CloneVisitor method visit.

@Override
public Node visit(ImportDeclaration _n, Object _arg) {
    NameExpr name = cloneNodes(_n.getName(), _arg);
    Comment comment = cloneNodes(_n.getComment(), _arg);
    ImportDeclaration r = new ImportDeclaration(_n.getBeginLine(), _n.getBeginColumn(), _n.getEndLine(), _n.getEndColumn(), name, _n.isStatic(), _n.isAsterisk());
    r.setComment(comment);
    return r;
}
Also used : JavadocComment(com.github.javaparser.ast.comments.JavadocComment) BlockComment(com.github.javaparser.ast.comments.BlockComment) LineComment(com.github.javaparser.ast.comments.LineComment) Comment(com.github.javaparser.ast.comments.Comment) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration)

Example 3 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project javaparser by javaparser.

the class CompilationUnitContext method solveMethod.

@Override
public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly, TypeSolver typeSolver) {
    for (ImportDeclaration importDecl : wrappedNode.getImports()) {
        if (importDecl.isStatic()) {
            if (importDecl.isAsterisk()) {
                String importString = importDecl.getNameAsString();
                if (this.wrappedNode.getPackageDeclaration().isPresent() && this.wrappedNode.getPackageDeclaration().get().getName().getIdentifier().equals(packageName(importString)) && this.wrappedNode.getTypes().stream().anyMatch(it -> it.getName().getIdentifier().equals(toSimpleName(importString)))) {
                    // a lower level so this will fail
                    return SymbolReference.unsolved(ResolvedMethodDeclaration.class);
                }
                ResolvedTypeDeclaration ref = typeSolver.solveType(importString);
                SymbolReference<ResolvedMethodDeclaration> method = MethodResolutionLogic.solveMethodInType(ref, name, argumentsTypes, true, typeSolver);
                if (method.isSolved()) {
                    return method;
                }
            } else {
                String qName = importDecl.getNameAsString();
                if (qName.equals(name) || qName.endsWith("." + name)) {
                    String typeName = getType(qName);
                    ResolvedTypeDeclaration ref = typeSolver.solveType(typeName);
                    SymbolReference<ResolvedMethodDeclaration> method = MethodResolutionLogic.solveMethodInType(ref, name, argumentsTypes, true, typeSolver);
                    if (method.isSolved()) {
                        return method;
                    }
                }
            }
        }
    }
    return SymbolReference.unsolved(ResolvedMethodDeclaration.class);
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) JavaParserAnnotationDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserAnnotationDeclaration) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Name(com.github.javaparser.ast.expr.Name) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) List(java.util.List) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) CompilationUnit(com.github.javaparser.ast.CompilationUnit) AnnotationDeclaration(com.github.javaparser.ast.body.AnnotationDeclaration) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) JavaParserEnumDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserEnumDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)

Example 4 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project cloud-sea-towerman by huadahuang1983.

the class JavaFileMergerJaxp method mergerFile.

public String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {
    StringBuilder sb = new StringBuilder(newCompilationUnit.getPackageDeclaration().get().toString());
    newCompilationUnit.removePackageDeclaration();
    // 合并imports
    NodeList<ImportDeclaration> imports = newCompilationUnit.getImports();
    imports.addAll(existingCompilationUnit.getImports());
    Set<ImportDeclaration> importSet = new HashSet<ImportDeclaration>();
    importSet.addAll(imports);
    NodeList<ImportDeclaration> newImports = new NodeList<>();
    newImports.addAll(importSet);
    newCompilationUnit.setImports(newImports);
    for (ImportDeclaration i : newCompilationUnit.getImports()) {
        sb.append(i.toString());
    }
    newLine(sb);
    NodeList<TypeDeclaration<?>> types = newCompilationUnit.getTypes();
    NodeList<TypeDeclaration<?>> oldTypes = existingCompilationUnit.getTypes();
    for (int i = 0; i < types.size(); i++) {
        // 截取Class
        String classNameInfo = types.get(i).toString().substring(0, types.get(i).toString().indexOf("{") + 1);
        sb.append(classNameInfo);
        newLine(sb);
        newLine(sb);
        // 合并fields
        List<FieldDeclaration> fields = types.get(i).getFields();
        List<FieldDeclaration> oldFields = oldTypes.get(i).getFields();
        List<FieldDeclaration> newFields = new ArrayList<>();
        Set<FieldDeclaration> fieldDeclarations = new LinkedHashSet<>();
        fieldDeclarations.addAll(fields);
        fieldDeclarations.addAll(oldFields);
        newFields.addAll(fieldDeclarations);
        for (FieldDeclaration f : newFields) {
            sb.append("\t" + f.toString());
            newLine(sb);
            newLine(sb);
        }
        // 合并methods
        List<MethodDeclaration> methods = types.get(i).getMethods();
        List<MethodDeclaration> existingMethods = oldTypes.get(i).getMethods();
        Set<MethodDeclaration> methodDeclarations = new LinkedHashSet<>();
        methodDeclarations.addAll(methods);
        methodDeclarations.addAll(existingMethods);
        for (MethodDeclaration f : methodDeclarations) {
            String res = f.toString().replaceAll("\r\n", "\r\n\t");
            sb.append("\t" + res);
            newLine(sb);
            newLine(sb);
        }
        // 判断是否有内部类
        types.get(i).getChildNodes();
        for (Node n : types.get(i).getChildNodes()) {
            if (n.toString().contains("static class")) {
                sb.append(n.toString());
            }
        }
    }
    return sb.append(System.getProperty("line.separator") + "}").toString();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) NodeList(com.github.javaparser.ast.NodeList) Node(com.github.javaparser.ast.Node) ArrayList(java.util.ArrayList) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project drools by kiegroup.

the class PackageModel method createClass.

private ClassOrInterfaceDeclaration createClass(String className, RuleSourceResult results) {
    CompilationUnit cuRulesMethod = new CompilationUnit();
    results.withClass(cuRulesMethod);
    cuRulesMethod.setPackageDeclaration(name);
    manageImportForCompilationUnit(cuRulesMethod);
    cuRulesMethod.getImports().add(new ImportDeclaration(new Name(name + "." + rulesFileName), true, true));
    return cuRulesMethod.addClass(className);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) ClassUtil.asJavaSourceName(org.drools.modelcompiler.util.ClassUtil.asJavaSourceName) SimpleName(com.github.javaparser.ast.expr.SimpleName) Name(com.github.javaparser.ast.expr.Name)

Aggregations

ImportDeclaration (com.github.javaparser.ast.ImportDeclaration)29 CompilationUnit (com.github.javaparser.ast.CompilationUnit)11 Name (com.github.javaparser.ast.expr.Name)6 Test (org.junit.Test)6 NodeList (com.github.javaparser.ast.NodeList)5 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)5 PackageDeclaration (com.github.javaparser.ast.PackageDeclaration)4 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)4 SimpleName (com.github.javaparser.ast.expr.SimpleName)3 HashMap (java.util.HashMap)3 ClassUtil.asJavaSourceName (org.drools.modelcompiler.util.ClassUtil.asJavaSourceName)3 AnnotationDeclaration (com.github.javaparser.ast.body.AnnotationDeclaration)2 EmptyTypeDeclaration (com.github.javaparser.ast.body.EmptyTypeDeclaration)2 EnumDeclaration (com.github.javaparser.ast.body.EnumDeclaration)2 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)2 AnnotationExpr (com.github.javaparser.ast.expr.AnnotationExpr)2 MemberValuePair (com.github.javaparser.ast.expr.MemberValuePair)2 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)2 ResolvedReferenceTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration)2 ResolvedTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration)2