Why sonarqube doesn't generate an issue for no

2019-08-02 04:34发布

问题:

I'm testing sonar in order to ensure the closing database connections.

I'm executing the maven goal "sonar:sonar" from eclipse with the embeded maven version 3.3.9. with sonarqube 6.2 with sonar-java-plugin-4.10.0.10260.jar.

With this code

package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class STestClosingResources extends HttpServlet{

    private static final long serialVersionUID = 1L;

    public final void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {
        Connection con = null;
        ResultSet rsGet = null;
        PreparedStatement psGet = null;
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/testci");
            con = ds.getConnection();

            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;
        }
    }
}

I don't get this issue I expected:

Close this "Connection" in a "finally" clause.

Why?

Thank you very much

回答1:

SonarJava analyzer responsible to analyze Java code and detect this issue doesn't recognize that DataSource.getConnection returns Connection which needs to be closed. I created ticket to fix it https://jira.sonarsource.com/browse/SONARJAVA-2355