Search code examples
javasonarqubesonar-runner

How to register custom rules in a plugin for SonarQube 4.5?


SonarQube version: 4.5

I created a Java project based on the sonar-xoo-plugin. Then I added a simple rule which inherits BaseTreeVisitor and always raises an issue in visitMethod(MethodTree). I annotated the class with @Rule(key = "x1") and used the same key in the class MyRulesDefinition when creating a new rule in the repository.

I built the project, put the jar file into the plugins folder and started the sonar server. The plugin was loaded and the rule existed. I activated it for the selected quality profile and ran an analysis but no issues were found by the rule.

What am I doing wrong? How is the rule template in MyRulesDefinition mapped to the logic of the rule?

Do any other examples exist for SonarQube plugins using the latest API?


Solution

  • Do any other examples exist for SonarQube plugins using the latest API?

    No, I faced exactly the same issue today and couldn't find any. But here is the solution :

    1. Create a class implementing RulesDefinition -> it is a ServerExtension whose sole purpose is to make your custom rules appear in SonarQube's UI if you've explicitly provided a definition (programatically, or in a XML file, or through annotations). This extension is loaded at server startup.
    2. Create a class implementing BatchExtension and JavaFileScannersFactory -> its purpose is to make all your custom java rules available during batch analysis by returning instances of your rules. This extension is loaded during analysis.
    3. Create a class extending SonarPlugin which returns Extensions created in points 1 and 2 above.

    Your custom rules will then be both available in UI and during analysis. If you don't do 1. you won't be able to activate / configure them. If you forget 2, they will be activable / configurable, but will never be executed (and no error will be raised neither)

    It's a slight difference with RulesRepository : your CustomRulesRepository extending RulesRepository could directly implement BatchExtension and JavaFilesScanner.