简体   繁体   中英

How do I fix squid:S2259 `NullPointerException might be thrown as 'getString' is nullable here`?

I have the following code block

/**
 * Checks if the server name is equal to localhost in the servlet request.
 *
 * @param request
 *            servlet request
 * @return true if the server name is equal to localhost.
 */
public boolean isLocalHost(@Nonnull final ServletRequest request) {

    return settings != null && settings.getString(LOCALHOST) != null && settings.getString(LOCALHOST).equals(request.getServerName());
}

But Sonarqube keeps on complaing that getString may be nullable, even though from what I can tell it can't happen due to boolean short circuiting

SonarQube cannot recognize the fact that successive calls of settings.getString will return the same value.

Might be it is right because it possible if other thread modify settings between calls.

So assigning value to variable as @Andreas mentioned in comment should resolve this issue.

UPD :

 public boolean isLocalHost(@Nonnull final ServletRequest request) {
     if(settings == null) {
         return false;
     }

     String localhost = settings.getString(LOCALHOST);

     return localhost != null && localhost.equals(request.getServerName());
 }

Or check variable from another side:

 public boolean isLocalHost(@Nonnull final ServletRequest request) {
    String requestServerName = request.getServerName();

    return settings != null && requestServerName != null && requestServerName.equals(settings.getString(LOCALHOST));
 }

UPD2 : Removed one of snippets because HttpServletRequest.getServerName() occasionally returning null in concurrent use?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM