Home > Blockchain >  Optional value should only be accessed after calling isPresent()
Optional value should only be accessed after calling isPresent()

Time:04-16

How can I change my code according to Sonar lint rules?

My code is below:

public interface TokenParser {
    public Optional<String> getUserName();
}

public class JWTTokenParser implements TokenParser {

    private Optional<Jwt> getJwt() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) {
            return Optional.empty();
        }
        return Optional.ofNullable((Jwt) authentication.getPrincipal());
    }

    @Override
    public Optional<String> getUserName() {
        return Optional.ofNullable(getJwt().get().getClaimAsString("preferred_username"));
    }
}

I could not pass the Sonar rules. How can I change my code?

CodePudding user response:

The problem is warning about the get is called without checking isPresent. Which will throw NoSuchElementException if no value is present, it violates the idea of using Optional.

    @Override
    public Optional<String> getUserName() {
        return Optional.ofNullable(getJwt().get().getClaimAsString("preferred_username"));
    }

Since getUserName() is also returning an Optional, we may use Optional#map to convert Optional<Jwt> to Optional<String>

 return getJwt().map(jwt -> jwt.getClaimAsString("preferred_username")));

map method will take care different case for us, as below:

getJwt() jwt.getClaimAsString("preferred_username") return
empty will not call Optioal.empty()
empty will not call Optioal.empty()
not empty return null Optioal.empty()
not empty return non null value Optional with non null value
  • Related