Search in sources :

Example 26 with ImportDeclaration

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

the class AnnotationFileParser method getImportedAnnotations.

/**
 * Returns all annotations imported by the annotation file, as a value for {@link
 * #allAnnotations}. Note that this also modifies {@link #importedConstants} and {@link
 * #importedTypes}.
 *
 * <p>This method misses annotations that are not imported. The {@link #getAnnotation} method
 * compensates for this deficiency by adding any fully-qualified annotation that it encounters.
 *
 * @return a map from names to TypeElement, for all annotations imported by the annotation file.
 *     Two entries for each annotation: one for the simple name and another for the
 *     fully-qualified name, with the same value.
 * @see #allAnnotations
 */
private Map<String, TypeElement> getImportedAnnotations() {
    Map<String, TypeElement> result = new HashMap<>();
    // TODO: The size can be greater than 1, but this ignores all but the first element.
    assert !stubUnit.getCompilationUnits().isEmpty();
    CompilationUnit cu = stubUnit.getCompilationUnits().get(0);
    if (cu.getImports() == null) {
        return result;
    }
    for (ImportDeclaration importDecl : cu.getImports()) {
        try {
            if (importDecl.isAsterisk()) {
                @// https://tinyurl.com/cfissue/3094:
                SuppressWarnings(// https://tinyurl.com/cfissue/3094:
                "signature") @DotSeparatedIdentifiers String imported = importDecl.getName().toString();
                if (importDecl.isStatic()) {
                    // Wildcard import of members of a type (class or interface)
                    TypeElement element = getTypeElement(imported, "Imported type not found", importDecl);
                    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, importDecl);
                    if (element != null) {
                        putAllNew(result, annosInPackage(element));
                        addEnclosingTypesToImportedTypes(element);
                    }
                }
            } else {
                // A single (non-wildcard) import.
                @// importDecl is non-wildcard, so its name is
                SuppressWarnings(// importDecl is non-wildcard, so its name is
                "signature") @FullyQualifiedName String imported = importDecl.getNameAsString();
                final TypeElement importType = elements.getTypeElement(imported);
                if (importType == null && !importDecl.isStatic()) {
                    // Class or nested class (according to JSL), but we can't resolve
                    stubWarnNotFound(importDecl, "Imported type not found: " + imported);
                } else if (importType == null) {
                    // static import of field or method.
                    Pair<@FullyQualifiedName String, String> typeParts = AnnotationFileUtil.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), importDecl);
                    if (enclType != null) {
                        // want a warning, imported might be a method.
                        for (VariableElement field : ElementUtils.getAllFieldsIn(enclType, elements)) {
                            // field.getSimpleName() is a CharSequence, not a String
                            if (fieldName.equals(field.getSimpleName().toString())) {
                                importedConstants.add(imported);
                            }
                        }
                    }
                } else if (importType.getKind() == ElementKind.ANNOTATION_TYPE) {
                    // Single annotation or nested annotation
                    TypeElement annoElt = elements.getTypeElement(imported);
                    if (annoElt != null) {
                        putIfAbsent(result, annoElt.getSimpleName().toString(), annoElt);
                        importedTypes.put(annoElt.getSimpleName().toString(), annoElt);
                    } else {
                        stubWarnNotFound(importDecl, "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", importDecl);
                    importedTypes.put(element.getSimpleName().toString(), element);
                }
            }
        } catch (AssertionError error) {
            stubWarnNotFound(importDecl, error.toString());
        }
    }
    return result;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) FullyQualifiedName(org.checkerframework.checker.signature.qual.FullyQualifiedName) VariableElement(javax.lang.model.element.VariableElement) DotSeparatedIdentifiers(org.checkerframework.checker.signature.qual.DotSeparatedIdentifiers) 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 27 with ImportDeclaration

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

the class InsertAjavaAnnotations method getImportedAnnotations.

/**
 * Returns all annotations imported by the annotation file as a mapping from simple and qualified
 * names to TypeElements.
 *
 * @param cu compilation unit to extract imports from
 * @return a map from names to TypeElement, for all annotations imported by the annotation file.
 *     Two entries for each annotation: one for the simple name and another for the
 *     fully-qualified name, with the same value.
 */
private Map<String, TypeElement> getImportedAnnotations(CompilationUnit cu) {
    if (cu.getImports() == null) {
        return Collections.emptyMap();
    }
    Map<String, TypeElement> result = new HashMap<>();
    for (ImportDeclaration importDecl : cu.getImports()) {
        if (importDecl.isAsterisk()) {
            @// https://tinyurl.com/cfissue/3094:
            SuppressWarnings(// https://tinyurl.com/cfissue/3094:
            "signature") @DotSeparatedIdentifiers String imported = importDecl.getName().toString();
            if (importDecl.isStatic()) {
                // Wildcard import of members of a type (class or interface)
                TypeElement element = elements.getTypeElement(imported);
                if (element != null) {
                    // Find nested annotations
                    result.putAll(AnnotationFileParser.annosInType(element));
                }
            } else {
                // Wildcard import of members of a package
                PackageElement element = elements.getPackageElement(imported);
                if (element != null) {
                    result.putAll(AnnotationFileParser.annosInPackage(element));
                }
            }
        } else {
            @// importDecl is non-wildcard, so its name is
            SuppressWarnings(// importDecl is non-wildcard, so its name is
            "signature") @FullyQualifiedName String imported = importDecl.getNameAsString();
            TypeElement importType = elements.getTypeElement(imported);
            if (importType != null && importType.getKind() == ElementKind.ANNOTATION_TYPE) {
                TypeElement annoElt = elements.getTypeElement(imported);
                if (annoElt != null) {
                    result.put(annoElt.getSimpleName().toString(), annoElt);
                }
            }
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) FullyQualifiedName(org.checkerframework.checker.signature.qual.FullyQualifiedName) PackageElement(javax.lang.model.element.PackageElement) DotSeparatedIdentifiers(org.checkerframework.checker.signature.qual.DotSeparatedIdentifiers)

Example 28 with ImportDeclaration

use of com.github.javaparser.ast.ImportDeclaration in project mybatis-generator-gui-extension by spawpaw.

the class MyShellCallback method mergeCompilationUnit.

/**
 * 合并可编译单元(即合并两个Java文件)
 */
private CompilationUnit mergeCompilationUnit(CompilationUnit oldCompilationUnit, CompilationUnit newCompilationUnit) {
    CompilationUnit finalCompilationUnit = new CompilationUnit();
    // 修改包名为新类的包名
    if (newCompilationUnit.getPackageDeclaration().isPresent())
        finalCompilationUnit.setPackageDeclaration(newCompilationUnit.getPackageDeclaration().get());
    // 合并import
    Set<ImportDeclaration> importSet = new HashSet<>();
    importSet.addAll(oldCompilationUnit.getImports());
    importSet.addAll(newCompilationUnit.getImports());
    NodeList<ImportDeclaration> imports = new NodeList<>();
    imports.addAll(importSet);
    finalCompilationUnit.setImports(imports);
    // 合并topLevelClass
    finalCompilationUnit.setTypes(mergeTypes(oldCompilationUnit.getTypes(), newCompilationUnit.getTypes()));
    return finalCompilationUnit;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) NodeList(com.github.javaparser.ast.NodeList) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration)

Example 29 with ImportDeclaration

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

the class GeneratorUtilsTest method should_Not_BeConsideredAsHavingAnAnnotation_When_GivenClassHavsAnnotationDeclarationButWithDifferentImport.

@Test
public void should_Not_BeConsideredAsHavingAnAnnotation_When_GivenClassHavsAnnotationDeclarationButWithDifferentImport() {
    NodeWithAnnotations<?> declarationWithEndpointAnnotation = Mockito.mock(NodeWithAnnotations.class);
    CompilationUnit compilationUnitWithNonVaadinEndpointImport = Mockito.mock(CompilationUnit.class);
    AnnotationExpr endpointAnnotation = Mockito.mock(AnnotationExpr.class);
    Mockito.doReturn(Optional.of(endpointAnnotation)).when(declarationWithEndpointAnnotation).getAnnotationByClass(Endpoint.class);
    NodeList<ImportDeclaration> imports = new NodeList<>();
    ImportDeclaration importDeclaration = Mockito.mock(ImportDeclaration.class);
    Mockito.doReturn("some.non.vaadin.Endpoint").when(importDeclaration).getNameAsString();
    imports.add(importDeclaration);
    Mockito.doReturn(imports).when(compilationUnitWithNonVaadinEndpointImport).getImports();
    Assert.assertFalse("A class with a non Vaadin Endpoint should not be considered as an Endpoint", GeneratorUtils.hasAnnotation(declarationWithEndpointAnnotation, compilationUnitWithNonVaadinEndpointImport, Endpoint.class));
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) AnnotationExpr(com.github.javaparser.ast.expr.AnnotationExpr) Endpoint(dev.hilla.Endpoint) NodeList(com.github.javaparser.ast.NodeList) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) Test(org.junit.Test)

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