Import Related Custom Rule - Java

Must-share information (formatted with Markdown):

  • which versions are you using (SonarQube Server / Community Build, Scanner, Plugin, and any relevant extension) - 10.7
  • how is SonarQube deployed: zip, Docker, Helm - Zip
  • what are you trying to achieve

The requirement is to create a custom rule which detects the usage of Slf4j import statement in the java code / project.

  • what have you tried so far to achieve this

Have created the below code and its relevant html/json files. This works while testing with junit case while building but after deployed to sonarqube 10.7 (created quality profile → added this rule to the profile → project is attached to quality profile) this rule violation is not detected and not seeing any error in the logs.

Please help.

private JavaFileScannerContext context;

 protected String name;

@Override
  public void scanFile(JavaFileScannerContext context) {
    this.context = context;
    scan(context.getTree());
  }

 @Override
 public void visitImport(ImportTree node) {
	 String importedClass = node.symbol().name();
	
     
     if (importedClass.startsWith("org.slf4j.Logger") || importedClass.contains("slf4j")) {
       
         context.reportIssue(this, node, StringUtils.Slf4jLoggerRule);
     }

// else if (importedClass.startsWith(“org.slf4j.LoggerFactory”) || importedClass.contains(“slf4j”)) {
//
// context.reportIssue(this, node, StringUtils.Slf4jLoggerRule);
// }

      super.visitImport(node);
  
 }

}

Hey there.

If you need help developing a custom rule, your best bet is to share the complete project (or a minimal version, just containing the rule) so that somebody else can build the project and reproduce the same issue.

Sure,I can do that. I do have a question about custom rule creation in sonarqube. So far, we are manually creating all the rule class, json and html files for custom rules. we were asked to work on almost 30 custom rules which we are manually doing the coding, deployment and then testing it with sample codes. It there any alternate way to automate or simply the whole process of creating files for the custom rules.