Custom Rule for Sonar Java


(Kad) #1

Good morning everybody,

I am trying to implement some custom rules, and I’m having trouble to implement a rule which require me to gather all the invoation of a certain method (doMethod); in certain classes for an example : obj.doMethod() , this case works perferctly, but in the the case of multiple method invocations, lets say : ClassA.getObj.doMethod(), I can’t seem to find a way separate the expression’s components ( ClassA, getObj).

Any help ?

I am using:
Sonar Plugin api 6.7
Sonar Java Plugin 5.1.0.13090

Original Thread : https://groups.google.com/forum/#!topic/sonarqube/gftkifZcCZ8


(Andrei Epure) #2

Hi Kad,
I replied on the original thread:

As general hints, you can play with MEMBER_SELECT and/or METHOD_INVOCATION for what you need.

public class YourRule extends IssuableSubscriptionVisitor {

  @Override
  public List<Tree.Kind> nodesToVisit() {
    // Register to the kind of nodes you want to be called upon visit.
    return ImmutableList.of(
        Tree.Kind.MEMBER_SELECT,
        Tree.Kind.METHOD_INVOCATION);
  }

  @Override
  public void visitNode(Tree tree) {
    if (tree.is(Tree.Kind.MEMBER_SELECT)) {
      MemberSelectExpressionTree mset = (MemberSelectExpressionTree) tree;
      System.out.println(mset);
    } else if (tree.is(Tree.Kind.METHOD_INVOCATION)) {
      MethodInvocationTree mit = (MethodInvocationTree) tree;
      System.out.println(mit);
    }
  }
}

Did you try to do that? What were the results, what are the remaining problems that you face?

Regards,
Andrei