elamas
elamas

Reputation: 221

How does the rule "Resources should be closed" check that a connection is closed?

this is a question, not a problem.

I have a class called DSConnectionUtilExternal with one method to retrieve a database connection and one method to close it. This class is in a jar file.

In the other hand I have a project which includes the jar file as a dependency. In this project I have this code

Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
    con = DSConnectionUtilExternal.openConnection();

    psGet = con.prepareStatement("SELECT * FROM TEST");
    rsGet = psGet.executeQuery();
    int counter = 0;
    while (rsGet.next()) {
        counter++;
        System.err.println(counter);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (rsGet != null) {
            rsGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    rsGet = null;
    try {
        if (psGet != null) {
            psGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    psGet = null;
    DSConnectionUtilExternal.closeConnection(con);
}

If I delete the content of the method closeConnection at the jar file, sonar doesn't detect that the connection is not closed. I think it's normal, sonar doesn't decompile the jar file to access the jar file code.

So the question is? What is the criterion used by the "Resources should be closed" rule to determine if the connection is closed in the finally clause?

Thanks

Upvotes: 2

Views: 975

Answers (1)

benzonico
benzonico

Reputation: 10833

Correct assumption from your question : At the moment SonarJava (4.11 just released) does not do cross file analysis and have no clue about what's going on in your closeConnection method.

However, the rule about unclosed resource has a simple heuristic to avoid false positives to consider resources closed if they are passed to a method named close.

SonarJava is on its way to be able to read your jar file and understand the resource is closed there but that is a complicated feature and we hope to deliver it in the near future.

Upvotes: 4

Related Questions