Skip to content
Advertisement

Using SonarQube how would one implement a java import blacklist?

Using SonarQube (version 3.0) I am trying to implement a blacklist of java libraries. For example I’d like for SonarQube to generate a code smell for any java file that contains an import for org.apache.lang.StringUtils

I did find this rule: “Track uses of disallowed dependencies” however as previously stated I want to focus on the java file import statements themselves. e.g.

import org.apache.lang.StringUtils; // SonarQube should generate smell for this line
import java.awt.Component;

Ideally I’d like to maintain a centralized list of deprecated/bug causing imports that would cover the following use cases:

  • Alert developer their code changes include prohibited imports
  • Scan legacy code base for prohibited, potentially bug causing imports

Advertisement

Answer

Following David M. Karr’s advice I looked through the custom rules documentation and found this template; Track uses of disallowed classes

Opening this template for configuration, there appears a note explaining that the rule parameters (in this case the class name) allows for regex – and explicitly advises to use regex when targeting packages.

enter image description here

The custom rule with org.apache.commons.lang.StringUtils passed to the ClassName parameter achieved the desired results stated in the question. Additionally the entire package can be targeted with org.apache.commons.lang.*

TL;DR

In SonarQube Dashboard

  1. Click “Rules” in main nav bar
  2. Search for “Track uses of disallowed classes”
  3. Select rule marked as “Template”
  4. At the bottom of the screen click “Create”
  5. Fill out Custom Rule configuration form, most importantly the ClassName field with either the fully qualified class e.g. org.apache.commons.lang.StringUtils or use regex to target an entire package e.g. org.apache.commons.lang.*
  6. Create/Save
  7. Add and then Activate this new custom rule to a profile associated with the target project. (I’m sure there are other ways to do this part, this is what worked for my small project, by extending the Java SonarWay profile)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement