javasonarqubesonarqube-web

Sonarqube Custom Rule- String Literal should not be duplicated, ignored in context of logger


Trying to extend the below linked Sonarqube rule to ignore the occurrence of a string literal in a logger method.

I am having issues trying to extract method names for methods (which in the context of the Base Visitor Tree may not be scoped as methods from my analysis. But have had some luck looking at methodInvocation type to extract a few method names).

So my question is does any one have a definition list of the Base Visitor Tree elements and how it would see different statements?

e.g. weeLogger.Log(exception, "exception occurred");

or

e.g. logger(exception1, "exception occured);

And as well has anyone done anything similar and share how they extracted out method names from the Base Visitor Tree class for analysis with Sonarqube?

https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/StringLiteralDuplicatedCheck.java


Solution

  • get method name

        public class SomeClass extends IssuableSubscriptionVisitor {
          @Override
          public List<Tree.Kind> nodesToVisit() {
            return ImmutableList.of(Tree.Kind.METHOD);
          }
    
          @Override
          public void visitNode(Tree tree) {
            MethodTree methodTree = (MethodTree) tree;
            IdentifierTree methodName = methodTree.simpleName();
           // getName from methodName. 
    
          }
    
    **get invocation method name**
    public class SomeClass extends IssuableSubscriptionVisitor {
    
        public static IdentifierTree methodName(MethodInvocationTree mit) {
            IdentifierTree id;
            if (mit.methodSelect().is(Tree.Kind.IDENTIFIER)) {
                id = (IdentifierTree) mit.methodSelect();
            } else {
                id = ((MemberSelectExpressionTree) mit.methodSelect()).identifier();
            }
            return id;
        }