Java Optional isPresent Using Helpers

Language: Java
Flag: squid:S3655
Using sonarcloud

At my company, we’ve got our own variant of Preconditions.checkArgument for certain arguments (primarily around checking arguments coming from Http and throwing a special exception)

We use this often to check the presence of Optionals, and thrown an exception if it’s not present. Unfortunately sonar doesn’t pick that up as calling Optional isPresent, even though it will always fail if it’s not present. Code:

That ResourceVerifier code looks like the following:

    public static void verifyExternal(boolean condition, String errorMessageTemplate, Object... errorMessageArgs) {
        if (!condition) {
            throw new WebApplicationException(format(errorMessageTemplate, errorMessageArgs), Response.Status.BAD_REQUEST);

Which is the same as the preconditions code. Is there any way we can get this picked up so it doesn’t warn for this case?


Thanks for reporting this FP.
Looks like this is a current limitation of the analyzer: we don’t do cross-file analysis and I guess verifyExternal is in another file. Indeed when using standard precondition FP disappears as we “whitelist” some known APIs.
Unfortunately I don’t know when we will tackle this limitation, so for now I can see 3 ways for you:

  • marking those issues with FP/wont’t fix
  • disable rule for the project or only for some files if it makes sense
  • consider using guava :slight_smile:

Is it possible for me to write a custom check for my codebase and just extend the existing one to add to the whitelist? And followup to that, is it possible to use such a custom check if I’m using sonarcloud?

hello @hkothari,

no, unfortunately this is not yet possible, and so far we don’t have concrete plans to make it possible. However we will consider it in the longer term.