1

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

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Well, at least, two subsequent calls to `getBody()` *could* return different results if the resulting `ResponseVO` is mutable and some other thread changes its value. That's not possible if you store it in a local variable first. However, I do not know whether this is the reason why SonarLint issues a warning here. – MC Emperor Dec 21 '21 at 14:02
  • @MCEmperor I don't think it's related for HttpEntity's `private final T body` – Ori Marko Dec 21 '21 at 14:09
  • Another way this can trigger: `MyClass debug = null; if (debug?.Buffer?.Length > 0) return debug.Buffer[0];` -- assuming MyClass has a byte[] Buffer property. – Peet Brits Sep 30 '22 at 08:43
  • 1
    I also logged an issue: https://github.com/SonarSource/sonar-dotnet/issues/6149 – Peet Brits Sep 30 '22 at 09:30

1 Answers1

1

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

Ori Marko
  • 56,308
  • 23
  • 131
  • 233