Skip to content

[java] CloseResource: false positive violation with closeNotInFinally=true property #3586

@dykov

Description

@dykov

PMD version: 6.39.0
Rule: CloseResource
Rule in ruleset:

  <rule ref="rulesets/java/design.xml/CloseResource">
    <properties>
      <property name="closeNotInFinally" value="true" />
    </properties>
  </rule>

Code to reproduce:

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SomeClass {
    private void method() throws SQLException {
        Connection connection = DriverManager.getConnection("/*...*/");   //violation
        connection.close();
    }
}

Please check if these functions work correctly?
net.sourceforge.pmd.lang.java.rule.errorprone.CloseResourceRule#visit:

    @Override
    public Object visit(ASTPrimaryPrefix prefix, Object data) {
        //...
        ASTName methodCall = prefix.getFirstChildOfType(ASTName.class);
        if (methodCall != null && isNodeInstanceOfResourceType(methodCall)) {
       //...

net.sourceforge.pmd.lang.java.rule.errorprone.CloseResourceRule#isNodeInstanceOfResourceType:

private boolean isNodeInstanceOfResourceType(TypeNode refType) {
        for (String resType : types) {
            if (TypeTestUtil.isA(resType, refType)) {
                return true;
            }
        }
        return false;
    }

So, we provide ASTName object with a name of invocation (e.g. connection.close()) to the TypeTestUtil#isA.
Is it allowed? As I understand, TypeTestUtil#isA should receive ASTClassOrInterfaceType object and the canonical name of the class to compare?

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions