5

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?

Marco Storto
  • 51
  • 1
  • 2

2 Answers2

4

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;
}
Martin Strejc
  • 4,307
  • 2
  • 23
  • 38
3

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.

benzonico
  • 10,635
  • 5
  • 42
  • 50
  • This is not something available for users, values are open/closed during analysis.You can mark the issue as false positive in SonarQube interface though. – benzonico Apr 13 '16 at 08:03
  • I know, but I have 200+ reported violations of rule squid:S2095 in our code base as this pattern is used in may places. My concern is that we may have some real issues hidden in the noise – Marco Storto Apr 13 '16 at 10:55
  • Try upgrading first, then you would also be better off using try with resource with java 7. – benzonico Apr 13 '16 at 15:28