S2637 javax.validation.constraints.NotNull False Positives

SonarQube 7.7 / SonarJava 5.12.1 give a warning when something annotated with javax.validation.constraints.NotNull is set to null. This is apparently because Sonar finds that javax.validation.constraints.NotNull indicates a variable is never null, as it is included in the not-null list here: https://github.com/SonarSource/sonar-java/blob/35e70591626e1b27bb059f795dda0327c02a09d3/java-frontend/src/main/java/org/sonar/java/se/NullableAnnotationUtils.java#L59

This is an incorrect assumption. The javax.validation.constraints package is meant for bean validation, validating user input. There is no reason these fields can be assumed to be not-null. The whole idea is that the field is null in the beginning, filled by the user, and then validated by the validator. Sonar should not consider the javax.validation.constraints.NotNull annotation as an indication of a non-nullable field.

A minimum sample is something like this, which gives an error because name is not initialised in the constructor:

public class ApiTokenForm {

    @NotNull(message = "{Admin_Core_Validation_ApiTokenForm_Name_NotNull}")
    @Size(min = 1, max = 64, message = "{Admin_Core_Validation_ApiTokenForm_Name_Size}")
    private String name;

    public ApiTokenForm() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Hi Mike,

Thank you for reporting this problem.
This is indeed a false positive. I created the corresponding ticket SONARJAVA-3157.
Let me know if you see any issue with it.

Cheers,

Nicolas

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.