Search code examples
javanullpointerexceptionsonarqubenullablesonarlint

Sonarlint false positive NullPointer warning (S2259) when using ResponseEntity


For general restTemplate operation,as :

ResponseEntity<ResponseVO> response = restTemplate.postForEntity(url, entity, ResponseVO.class);
if (response.getBody() != null) {
    String url = response.getBody().getUrl();

I'm getting wrong sonar warning when reusing the ResponseEntity:

A "NullPointerException" could be thrown; "getBody()" can return null. sonarlint(java:S2259)

Also if I refactor and introduce a variable no warning appears:

ResponseVO body = response.getBody();
if (body != null) {
    String url = body.getUrl();

I don't need to add response != null, if added there's a different (ok) warning:

Remove this expression which always evaluates to "true" [+3 locations]sonarlint(java:S2589)

Is it SonarLint bug? why it warns about NullPointerException?

I suspect it's related to HttpEntity @Nullable definition

@Nullable
public T getBody() {

I didn't find similar issue in jira.sonarsource


Solution

  • Raised a false-positive in Sonar community and answered by @DamienUrruty

    indeed it looks like a false-positive. That said it might make the rule more complex to support this case