Reputation: 25
if(request.getHeaders().get(HttpHeaders.CUSTOMER_ID.getName()) ==nul || request.getHeaders().get(HttpHeaders.CUSTOMER_ID.getName()).isEmpty()){ String customer_id = LogContext.getCustomerId(); if(customer_id != null){ request.getHeaders().add(HttpHeaders.CUSTOMER_ID.getName(), customer_id); } }`
Upvotes: 1
Views: 1846
Reputation: 1267
Sonar is probably talking about this rule: https://rules.sonarsource.com/java/RSPEC-2259
A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.
With this rule Sonar will check every method call that you do for the possibility of null
as the return value.
Using the return value of such method calls without a null check
will result in this warning.
In this case you know that request.getHeaders().get(HttpHeaders.CUSTOMER_ID.getName())
is not null because you've just checked that, but in theory if you execute this call again the result might be different.
For example what if you shared the request
object with another Thread
that is writing a null
value as the header with this same key?
It would be nearly impossible for Sonar to know for sure that this is not happening in the static analysis context, and that is why you are getting this error message.
You could consider it as a false positive and handle it that way, but i would suggest to take a more defensive approach and rewrite your code as follows:
String currentCustomerIdHeader = request.getHeaders().get(HttpHeaders.CUSTOMER_ID.getName());
if (currentCustomerIdHeader == null || currentCustomerIdHeader.isEmpty()) {
String customer_id = LogContext.getCustomerId();
if (customer_id != null) {
request.getHeaders().add(HttpHeaders.CUSTOMER_ID.getName(), customer_id);
}
}
This is also reduces some duplication, and makes your code cleaner and easier to read.
If you're using Java 8 you can also rewrite this null check using Optional.
And please check the common Java coding conventions, we normally don't use the underscore in variable naming (customerId
over customer_id
).
Upvotes: 2