Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2655

JEE applications should delegate connection management to the container

    XMLWordPrintable

    Details

    • Message:
      Use a JNDI-supplied DataSource instead.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • Implementation details:
    • CWE:
      CWE-245

      Description

      The JEE standard forbids the direct management of connections in JEE applications. But if that's not reason enough to delegate connection management to the servlet container, consider that the container is both better positioned and better equipped to manage resources not just for a single class, but across classes in an application. Further, mis-managing connections in a JEE class can lead to connection leaks which could compound into a denial of service.

      This rule raises an issue for each use of a DriverManager in a servlet class.

      Noncompliant Code Example

      private static final String CONNECT_STRING = "jdbc:mysql://localhost:3306/mysqldb";
      
      public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException  {
        
        Connection conn = null;
        try {
          conn = DriverManager.getConnection(CONNECT_STRING);  // Noncompliant
          // ...
        } catch (SQLException ex) {...}
          //...
        }
      }
      

      Compliant Solution

      private static final String DB_LOOKUP = "jdbc/mainDb";
      
      public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException  {
        
        Connection conn = null;
        try {
          InitialContext ctx = new InitialContext();
          DataSource datasource = (DataSource) ctx.lookup(DB_LOOKUP);
          conn = datasource.getConnection();
          // ...
        } catch (SQLException ex) {...}
          //...
        }
      }
      

      See

      • MITRE, CWE-245 - J2EE Bad Practices: Direct Management of Connections

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            ann.campbell.2 Ann Campbell
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Dates

              Created:
              Updated: