0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
johny sinh
  • 43
  • 5
  • 2
    Does this answer your question? ['Optional.get()' without 'isPresent()' check](https://stackoverflow.com/questions/38725445/optional-get-without-ispresent-check) – HariHaravelan Apr 15 '22 at 14:38

1 Answers1

2

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
samabcde
  • 6,988
  • 2
  • 25
  • 41