Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonarqube squid:S2095 false positive

In our code base we get Sonar reports violation for rule squid:S2095 on code like the following:

    PreparedStatement ps = null;
    try {
        ps = connection.prepareStatement(DML); 
        ps.setString(1, externalDeviceId);
        ps.setInt(2, internalDeviceId);
        ps.execute();
        return ps.getUpdateCount() > 0;
    } finally {
        Utilities.close(ps);
    }

with Utilities.close implemented as

    public static final void close(final AutoCloseable ac) {
        if(ac != null) {
            try {
                ac.close(); 
                } catch(Exception e) {
            }
        }
    }

Is there a way to avoid these false positives?

like image 529
Marco Storto Avatar asked Apr 12 '16 12:04

Marco Storto


People also ask

How to handle false positive in SonarQube?

How do I get rid of issues that are False-Positives? You can mark individual issues False Positive or Won't Fix through the issues interface. If you're using PR analysis provided by the Developer Edition, issues marked False Positive or Won't Fix will retain that status after merge.


2 Answers

If you use Java 7+, there is a much simple way to use try-with-resources that is able to close resource itself and you needn't take care about that anymore. See try (PreparedStatement ps = connection.prepareStatement(DML)), a tutorial: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

try (PreparedStatement ps = connection.prepareStatement(DML)) {
    ps.setString(1, externalDeviceId);
    ps.setInt(2, internalDeviceId);
    ps.execute();
    return ps.getUpdateCount() > 0;
}
like image 123
Martin Strejc Avatar answered Oct 19 '22 19:10

Martin Strejc


Short answer, there is no way to avoid those for the moment.

Longer answer : Normally, passing an opened value to a method should mark it as closed to avoid false positive. You should precise the sonar java plugin version you are using.

This rule is relying on symbolic execution engine and is limited to the boundaries of a method and as such, there is no way to determine for the moment that a call to this utility method will for sure close the open resource.

Note however that the sonar java team is working to make this limit go away.

like image 33
benzonico Avatar answered Oct 19 '22 20:10

benzonico