Saturday, 4 January 2014

Findbugs as eclipse plugin in a bndtools project

This post is just a little write-up about how to use findbugs in a bndtools project. Specifically it is about how to suppress findbugs warnings you don't think to be accurate in some context.

Prerequisites:

I assume you have installed bndtools and findbugs (e.g. via the eclipse marketplace). Further you should have created a bndtools project, and, preferably for this little tutorial, you should get a findbugs warning in your code when running findbugs on your bndtools project.

An Example:

    private static volatile ConfigurationProvider configurationProvider;

    @Reference
    public void setConfigurationProvider(ConfigurationProvider provider) {
        configurationProvider = provider;
    }

This kind of code will give me a findbugs warning like "Write to static field" in the assignment. I do not want to discuss if this is appropriate here, just now I want to get rid of this warning.

The library to the rescue:

Fortunately for us, when searching maven.org for "com.google.code.findbugs", you will find an "annotations" jar (currently in version 2.0.3); this little library provides a couple of annotations to give findbugs some hints about your needs.

The code change needed:

Checking some examples, I conclude that what I need is this:

    @Reference
    @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
    public void setConfigurationProvider(ConfigurationProvider provider) {
        configurationProvider = provider;
    }


Dependencies management:

But I have to add the annotations jar to the build path of my project (I will not need the dependency when running the bundle though!). In the context of a bndtools workspace there is a convenient way to add the library in in non-obstructive way:


  • Drag the downloaded annotations-2.0.3.jar onto the "Build" repository in the bndtools Repositories view
  • you might have to check the ext/repositories.bnd file (see below)
  • Refresh the bndtools repositories (in the Bndtools menu)
  • Your code should compile now, and the findbugs warning should be gone.
Troubleshooting:

There is one thing which might prevent you from succeeding: If you check your cnf/ext/repositories.bnd file, the definition of the Build repository might look like

aQute.lib.deployer.FileRepo;name=Build;location=${workspace}/cnf/buildrepo

I think this is the default when installing bndtools. What you need to do to make the above work is to change that line to 

aQute.bnd.deployer.repository.LocalIndexedRepo;name=Build;local=${workspace}/cnf/buildrepo;pretty=true

This will make the Build repo a LocalOBR which should not change its behaviour otherwise (see that google groups entry).

Hope that this is useful for somebody ;)