【问题标题】:Detecting Connection not closed in java code using PMD maven使用PMD maven检测Java代码中未关闭的连接
【发布时间】:2017-04-24 21:03:27
【问题描述】:

我正在尝试使用 maven pmd 插件来检测整个项目的所有连接泄漏。我们使用 BaseSqlUtl.close 关闭连接,所以如果我们可以使用 PMD 找到打开连接的人已经使用此方法关闭,我们可以检测到连接泄漏。 由于我们使用自定义类来关闭连接,因此我在以下 ruleset.xml 中创建了一个以 ** 突出显示的规则集更改。

 <?xml version="1.0"?>

   <ruleset name="Design"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

  <description>
The Design ruleset contains rules that flag suboptimal code implementations. Alternate approaches
are suggested.
  </description>

  <rule name="CloseResource"
          since="1.2.2"
        message="Ensure that resources like this {0} object are closed after use"
        class="net.sourceforge.pmd.lang.java.rule.design.CloseResourceRule"
          externalInfoUrl="http://pmd.sourceforge.net/pmd-5.0.5/rules/java/design.html#CloseResource">
    <description>
Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
    </description>
    <priority>3</priority>
    <properties>
    <property name="types" value="Connection,Statement,ResultSet"/>
    **<property name="closeTargets" value="closeStatementQuietly,closeResultSetQuietly,commitAndCloseQuietly,rollbackAndCloseQuietly,closeQuietly,sqlUtil.closeQuietly,resetAndCloseQuietly"/>**
    </properties>
    <example>
<![CDATA[
public class Bar {
  public void foo() {
    Connection c = pool.getConnection();
    try {
      // do stuff
    } catch (SQLException ex) {
     // handle exception
    } finally {
      // oops, should close the connection using 'close'!
      // c.close();
    }
  }
}
]]>
    </example>
  </rule>

</ruleset>

现在这对于像 commitAndCloseQuietly() 这样的未参数化方法来说工作得很好,但不幸的是对于像 "sqlUtil.closeQuietly(connection)" 这样接受连接作为参数的其他方法,它会发出错误警报。

我尝试参考提出的类似问题,但在这种特定情况下无法提供帮助: Identifying Connection not closed in java code using PMD

【问题讨论】:

    标签: java maven connection code-analysis pmd


    【解决方案1】:

    PMD 目前不支持使用辅助方法关闭资源。即使可以配置 close 方法,它们都被假定为在资源本身上调用。

    如果 PMD 执行多类 DFA 可能会解决这个问题,它目前没有并且可能在一段时间内不会(它对缓存结果的能力有很大影响)。

    更好的解决方法是添加支持以指定将资源作为参数的关闭辅助方法。随意在 Github (https://github.com/pmd/pmd) 上创建功能请求;或者更好的是,提交 PR。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多