Squid Well: S2095 False Positive

In our code base, we get a sonar violation message for the squid: S2095 rule using a 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 any way to avoid these false positives?

+5
source share
2 answers

If you use Java 7+, there is a very simple way to use try-in-resources that can close the resource itself, and you no longer need to worry about that. See Try (PreparedStatement ps = connection.prepareStatement (DML)) , 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; } 
+4
source

Short answer, there is currently no way to avoid this.

Longer answer: Usually, passing an open value to a method should be marked as closed to avoid false positives. You should clarify the version of the java sonar plugin you are using.

This rule is based on the mechanism of symbolic execution and is limited by the boundaries of the method and as such, at that time there is no way to determine that calling this method of the utility will probably close the open resource.

Note that the java sonar command is working to get this limit gone.

+3
source

Source: https://habr.com/ru/post/1246949/


All Articles