Search code examples
javasonarqubefindbugsspotbugs

Findbugs Unchecked/unconfirmed cast from builder style chained function calls


FindBugs is reporting an Unchecked/Unconfirmed cast issue with the and() line in the following builder pattern code for configuring Spring security.

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
            .withUser("admin").password("secret").roles("ADMIN")
                .and()
            .withUser("user").password("secret").roles("USER");
}

The code works fine, how do I appease FindBugs?


Solution

  • Edit:

    As suggested by @h3xStream (in the comments below), if you run into a false positive with any code analysis tool, the best solution is to configure the tool to ignore the false positive and to take action to correct the code analysis tool. This of course assumes that it is indeed a false positive and that your code, in its current form, is correct and better left unaltered.

    In a pinch, you may be able to rewrite your code to keep the false positive from being triggered. That's what I ended up doing in this particular case, though it is really just a work around:


    I was able to stop the false positive from being triggered by updating the code to the following:

    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> conf 
                = auth.inMemoryAuthentication();
        conf.withUser("admin").password("secret").roles("ADMIN");
        conf.withUser("user").password("secret").roles("USER");
    }
    

    As I was no longer chaining the functions together, the return values became irrelevant and the false positive was no longer triggered.