简体   繁体   English

Sonarqube鱿鱼:S2095假阳性

[英]Sonarqube squid:S2095 false positive

In our code base we get Sonar reports violation for rule squid:S2095 on code like the following: 在我们的代码库中,我们得到Sonar报告规则squid的违规行为:S2095代码如下:

    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 将Utilities.close实现为

    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? 有没有办法避免这些误报?

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. 如果您使用Java 7+,有一种非常简单的方法可以使用try-with-resources来关闭资源本身,您不必再关注它了。 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)) ,教程: 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;
}

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. 您应该精确使用您正在使用的声纳java插件版本。

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. 但请注意,声纳java团队正努力使此限制消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM