简体   繁体   中英

SonarQube: Create custom rules to get custom annotations in a class

I'm trying to create a custom SonarQube rule which will detect the usage of a specific custom Java Annotation. Here is the code I found which prints a list of all annotations used in a class.

public class SampleAnnotationCheck extends IssuableSubscriptionVisitor {
    @Override
    public List<Tree.Kind> nodesToVisit() {
        return ImmutableList.of(Tree.Kind.METHOD);
    }

    @Override
    public void visitNode(Tree tree) {
        MethodTree methodTree = (MethodTree) tree;
        for (AnnotationInstance ai : ((JavaSymbol.MethodJavaSymbol) methodTree.symbol()).metadata().annotations()) {
            System.out.println(ai.symbol().name());
        }
    }
}

Sample Java File:

@GET
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method1(...) {...}

@CustomAnnotation(values)
@POST
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method2(...) {...}

@PATCH
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method3(...) {...}

Expected Output:

GET
Path
Consumes
Produces
CustomAnnotation
POST
Path
Consumes
Produces
PATCH
Path
Consumes
Produces

Actual Output:

GET
Path
Consumes
Produces
!unknownSymbol!
POST
Path
Consumes
Produces
!unknownSymbol!
Path
Consumes
Produces

I'm getting !unknownSymbol! instead of the Custom Annotations' actual names. One of the custom annotations is io.swagger.jaxrs.PATCH.

The other annotation is defined inside a separate package and imported by the sample class.

Do we have to register these custom annotations somewhere for the API to detect?

Please suggest what changes should be made so that we can detect and print the actual Custom Annotation's name.

Thanks in advance!

I assume you are following this guide and running check within your tests https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101 . To provide dependencies to your tests you can either

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM