Configuring rules to use NonNull and CheckForNull Annotations

Relevant information:

  • Version: SonarQube 7.9.1
  • What are you trying to achieve: Rule violations when @NonNull or @CheckForNull are violated/
  • What have you done: Ensured relevant rules are activated, wrote a test file with violations, scanned test file. No issues were identified.

Question:
Which annotations are supported? E.g. squid:S4449 specifically identifies:
javax.annotation.CheckForNull

So the problem might be that I’m trying to use the annotations currently in spotbugs?
edu.umd.cs.findbugs.annotations.CheckForNull

However, from looking at this, it seems like I’m using one of the approved annotations:
https://github.com/SonarSource/sonar-java/blob/master/java-frontend/src/test/files/se/annotations/NullableAnnotationUtils.java

AnnotationDemo.txt (1.0 KB)

More information: I switched to IntelliJ annotations and implemented the example from the SonarQube rule.

Both the IntelliJ and Sonar Linters find the examples that don’t comply with the annotation. SonarQube does not.

i mport org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class AnnotationDemo {

    @NotNull
    private String primary;
    @Nullable
    private String secondary;

    public AnnotationDemo(String color) {
        if (color != null) {
            secondary = null;
        }
        primary = color;  // Noncompliant; "primary" is Nonnull but could be set to null here
    }

    public AnnotationDemo() { // Noncompliant; "primary" Nonnull" but is not initialized
    }

    public static void main(String [] args){
        AnnotationDemo ad = new AnnotationDemo();
        System.out.println(ad.primary + " " + ad.secondary); //Noncompliant; secondary can be null
    }
}

Resolution: Move the file from the test directory to a source directory. Annotations are then found as expected.

Remember Next Time: Only a subset of rules are applied to tests.