Reputation: 53
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!
Upvotes: 3
Views: 1444
Reputation: 4430
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
put jars in target/test-jars
directory (see how to do it with maven dependency plugin here https://github.com/SonarSource/sonar-custom-rules-examples/blob/master/java-custom-rules/pom.xml#L147)
in your test provide custom classpath using JavaCheckVerifier.verify(filename, check, classpath)
Upvotes: 1