Sonarqube squid:S2095 false positive
Asked Answered
E

2

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?

Ectosarc answered 12/4, 2016 at 12:29 Comment(4)
which version of the java plugin are you using ?Frock
java plugin version is 3.11Ectosarc
There was some improvement around this during 3.12 and release of 3.13 is going to be made public really soon. I recommend you try with version 3.12 at least to benefit from this fix : jira.sonarsource.com/browse/SONARJAVA-1538Frock
Use //NOSONAR commentGender
T
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;
}
Tallie answered 12/4, 2016 at 13:55 Comment(0)
F
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.

Frock answered 12/4, 2016 at 13:29 Comment(3)
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.Frock
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 noiseEctosarc
Try upgrading first, then you would also be better off using try with resource with java 7.Frock

© 2022 - 2024 — McMap. All rights reserved.