The following plugin demonstrates how to create a new rule in SonarQube that checks for the use of the System.out.println()
method in Java code, which is considered bad practice.
First, create a new SonarQube plugin project using the SonarQube Plugin Generator, and then follow these steps:
- Add the necessary dependencies to your plugin’s
pom.xml
file:
<dependencies>
<dependency>
<groupId>org.sonarsource.java</groupId>
<artifactId>sonar-java-plugin</artifactId>
<version>5.14.0.18788</version>
</dependency>
<dependency>
<groupId>org.sonarsource.sonar-plugin-api</groupId>
<artifactId>sonar-plugin-api</artifactId>
<version>7.9.1</version>
</dependency>
</dependencies>
- Create a new Java class that extends
org.sonar.api.server.rule.RulesDefinition
to define the new rule:
public class MyRulesDefinition implements RulesDefinition {
public static final String REPOSITORY_KEY = "my_repository";
public static final String RULE_KEY = "no-system-out";
@Override
public void define(Context context) {
NewRepository repository = context.createRepository(REPOSITORY_KEY, "java");
NewRule rule = repository.createRule(RULE_KEY)
.setName("Avoid using System.out.println()")
.setSeverity(Severity.MAJOR)
.setTags("performance");
repository.done();
}
}
- Create another Java class that extends
org.sonar.plugins.java.api.JavaCheck
to implement the new rule:
@Rule(key = MyRulesDefinition.RULE_KEY)
public class NoSystemOutCheck extends AbstractJavaCheck {
@Override
public void visitMethodInvocation(MethodInvocationTree tree) {
if (tree.symbol().owner().type().is("java.io.PrintStream") &&
tree.symbol().name().equals("println") &&
tree.arguments().size() == 1 &&
tree.arguments().get(0).is(Tree.Kind.STRING_LITERAL)) {
reportIssue(tree, "Do not use System.out.println() in production code.");
}
super.visitMethodInvocation(tree);
}
}
- Finally, create a
sonar-plugin.properties
file in the root of your project and specify the plugin metadata:
sonar.plugin.name=My Plugin
sonar.plugin.version=1.0.0
sonar.plugin.description=This is my custom SonarQube plugin
sonar.plugin.developer=My Company
sonar.java.version=8
sonar.updatecenter.url=https://update.sonarsource.org/update-center.properties
- Build your plugin using
mvn clean package
, and then install it by copying the generated JAR file to theextensions/plugins
directory of your SonarQube instance.
That’s it! Now you have a custom SonarQube plugin that adds a new rule to check for the use of System.out.println()
in Java code. You can customize this plugin to add more rules or features according to your needs.