private void saveToDb() {
    Connection con = null;
    PreparedStatement pstmt = null;
    try {

      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(UPDATE_WARE);
      System.out.println(UPDATE_WARE);
      pstmt.setString(1, StringUtils.toChinese(this.Pname));
      pstmt.setString(2, StringUtils.toChinese(this.Pmodel));
      pstmt.setString(3, StringUtils.toChinese(this.Pcost));
      pstmt.setString(4, StringUtils.toChinese(this.Pheft));
      pstmt.setString(5, StringUtils.toChinese(this.Pfacturer));
      pstmt.setString(6, StringUtils.toChinese(this.Pnote));
      pstmt.setInt(7, this.Status);
      pstmt.setInt(8, this.Id);
      pstmt.executeUpdate();
    } catch (SQLException sqle) {
      System.err.println("错误位置: DbWare.java:saveToDb(): " + sqle);
      sqle.printStackTrace();
    } finally {
      try {
        pstmt.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        con.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
  private void goodB2G1() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_FIVE == 5) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      if (data != null) {
        String names[] = data.split("-");
        int successCount = 0;
        Connection dbConnection = null;
        PreparedStatement sqlStatement = null;
        try {
          /* FIX: Use prepared statement and executeBatch (properly) */
          dbConnection = IO.getDBConnection();
          sqlStatement =
              dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?");
          for (int i = 0; i < names.length; i++) {
            sqlStatement.setString(1, names[i]);
            sqlStatement.addBatch();
          }
          int resultsArray[] = sqlStatement.executeBatch();
          for (int i = 0; i < names.length; i++) {
            if (resultsArray[i] > 0) {
              successCount++;
            }
          }
          IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
        } finally {
          try {
            if (sqlStatement != null) {
              sqlStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
          }

          try {
            if (dbConnection != null) {
              dbConnection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    }
  }
Beispiel #3
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private void DELToDb() {
   Connection con = null;
   PreparedStatement pstmt = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(Del_ware);
     System.out.println(Del_ware);
     pstmt.setInt(1, this.Status);
     pstmt.setInt(2, this.Id);
     pstmt.executeUpdate();
   } catch (SQLException sqle) {
     System.err.println("错误位置: DbShop.java:DELToDb(): " + sqle);
     sqle.printStackTrace();
   } finally {
     try {
       pstmt.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
     try {
       con.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  /* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */
  private void goodB2G1() throws Throwable {
    String data;
    if (IO.staticTrue) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.staticFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
Beispiel #6
0
  /**
   * Determine whether or a not a User with the supplied researcherID exists
   *
   * @param username The researcherID to test
   * @return true if the user exists, false if not
   * @throws SQLException if a database error was encountered
   */
  public static boolean userExists(int researcherID) throws SQLException {
    boolean returnVal = false;

    // Get our connection to the database.
    Connection conn = DBConnectionManager.getConnection("yrc");
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
      stmt = conn.prepareStatement("SELECT researcherID FROM tblUsers WHERE researcherID = ?");
      stmt.setInt(1, researcherID);

      rs = stmt.executeQuery();

      // No rows returned.
      if (!rs.next()) {
        returnVal = false;
      } else {
        returnVal = true;
      }

      rs.close();
      rs = null;

      stmt.close();
      stmt = null;

      conn.close();
      conn = null;
    } finally {

      // Always make sure result sets and statements are closed,
      // and the connection is returned to the pool
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {;
        }
        rs = null;
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (SQLException e) {;
        }
        stmt = null;
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {;
        }
        conn = null;
      }
    }

    return returnVal;
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (privateFive == 5) {
      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      try {
        /* FIX: Use prepared statement and execute (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name=?");
        sqlStatement.setString(1, data);
        Boolean result = sqlStatement.execute();
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
 private void insertLog(HttpServletRequest req, Connection connection) throws SQLException {
   try (PreparedStatement stmt =
       connection.prepareStatement("INSERT INTO LOGGING (date,ip,url) VALUES (?,?,?)")) {
     stmt.setTimestamp(1, new Timestamp((new java.util.Date()).getTime()));
     stmt.setString(2, req.getRemoteAddr());
     stmt.setString(3, req.getRequestURI());
     stmt.executeUpdate();
   }
 }
  /* goodB2G1() - use badsource and goodsink by changing second privateTrue to privateFalse */
  private void goodB2G1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    if (privateTrue) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (privateFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;

      try {
        /* FIX: Use prepared statement and execute (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name=?");
        sqlStatement.setString(1, data);

        Boolean result = sqlStatement.execute();

        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      System.out.println("Enrollno: 130050131049");
      // STEP 2: Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      // STEP 2: Executing query
      String sql = "SELECT * FROM logindetails WHERE name = ?";
      pstmt = conn.prepareStatement(sql);
      pstmt.setString(1, "Krut");

      ResultSet rs = pstmt.executeQuery();
      out.print("| <b>Name</b>| ");
      out.print("<b>Password</b>| ");
      out.println("</br>\n-------------------------------</br>");
      while (rs.next()) {
        out.println();
        out.print("| " + rs.getString(1));
        out.print("| " + rs.getString(2) + "|");
        out.println("</br>");
      }

    } catch (SQLException se) {
      // Handle errors for JDBC
      se.printStackTrace();
    } catch (Exception e) {
      // Handle errors for Class.forName
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (pstmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(String data_array[]) throws Throwable {
    String data = data_array[2];

    String names[] = data.split("-");
    int iSuccess = 0;

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    PreparedStatement sqlstatement = null;

    try {
      /* FIX: use prepared sqlstatement */
      conn_tmp2 = IO.getDBConnection();
      sqlstatement =
          conn_tmp2.prepareStatement("update users set hitcount=hitcount+1 where name=?");

      for (int i = 0; i < names.length; ++i) {
        sqlstatement.setString(1, names[i]);
        sqlstatement.addBatch();
      }

      int dbResults[] = sqlstatement.executeBatch();

      for (int i = 0; i < names.length; ++i) {
        if (dbResults[i] > 0) {
          iSuccess++;
        }
      }

      IO.writeString("Succeeded in " + iSuccess + " out of " + names.length + " queries.");
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlstatement != null) {
          sqlstatement.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlstatement");
      } finally {
        try {
          if (conn_tmp2 != null) {
            conn_tmp2.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing conn_tmp2");
        }
      }
    }
  }
  /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
  public void goodB2G1Sink(String data) throws Throwable {
    if (CWE89_SQL_Injection__Environment_executeBatch_22a.goodB2G1PublicStatic) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      if (data != null) {
        String names[] = data.split("-");
        int successCount = 0;
        Connection dbConnection = null;
        PreparedStatement sqlStatement = null;
        try {
          /* FIX: Use prepared statement and executeBatch (properly) */
          dbConnection = IO.getDBConnection();
          sqlStatement =
              dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?");
          for (int i = 0; i < names.length; i++) {
            sqlStatement.setString(1, names[i]);
            sqlStatement.addBatch();
          }
          int resultsArray[] = sqlStatement.executeBatch();
          for (int i = 0; i < names.length; i++) {
            if (resultsArray[i] > 0) {
              successCount++;
            }
          }
          IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
        } finally {
          try {
            if (sqlStatement != null) {
              sqlStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
          }

          try {
            if (dbConnection != null) {
              dbConnection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    }
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (PRIVATE_STATIC_FINAL_TRUE) {
      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      try {
        /* FIX: Use prepared statement and execute (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name=?");
        sqlStatement.setString(1, data);
        Boolean result = sqlStatement.execute();
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      String email = request.getParameter("email_id");

      String number = "";
      boolean exists = false;
      String user_name = "";
      int user_id = -1;
      String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setString(1, email);
      ResultSet rs1 = prep1.executeQuery();
      if (rs1.next()) {
        exists = true;
        user_id = rs1.getInt("USER_ID");
        user_name = rs1.getString("NAME");
        number = rs1.getString("PHONE_NUMBER");
      }
      int verification = 0;
      JSONObject data = new JSONObject();
      if (exists) {
        verification = (int) (Math.random() * 9535641 % 999999);
        System.out.println("Number " + number + "\nVerification: " + verification);
        SMSProvider.sendSMS(
            number, "Your One Time Verification Code for PeopleConnect Is " + verification);
      }

      data.put("user_name", user_name);
      data.put("user_id", user_id);
      data.put("verification_code", "" + verification);
      data.put("phone_number", number);

      String toSend = data.toJSONString();
      out.print(toSend);
      System.out.println(toSend);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
  /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
  public void goodB2G1Sink(String data) throws Throwable {
    if (CWE89_SQL_Injection__connect_tcp_executeQuery_22a.goodB2G1PublicStatic) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  private void goodB2G1Sink(String data) throws Throwable {
    if (goodB2G1Private) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing first privateTrue to privateFalse */
  private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (privateTrue) {
      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      try {
        /* POTENTIAL FLAW: data concatenated into SQL statement used in prepareStatement() call, which could result in SQL Injection */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name='" + data + "'");
        Boolean result = sqlStatement.execute();
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    System.out.println("Clearing changes");
    Connection c = null;
    try {

      DriverManager.registerDriver(new AppEngineDriver());
      c = DriverManager.getConnection("jdbc:google:rdbms://trmrphdn:veebirakendused/andmebaas");
      String statement = "delete from kandidaat where nimi = 'Tandi Kaat'";
      PreparedStatement stmt = c.prepareStatement(statement);
      stmt.executeUpdate();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    PreparedStatement sqlstatement = null;
    ResultSet sqlrs = null;

    try {
      /* FIX: use prepared sqlstatement */
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.prepareStatement("select * from users where name=?");
      sqlstatement.setString(1, data);

      sqlrs = sqlstatement.executeQuery();

      IO.writeString(sqlrs.toString());
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlrs != null) {
          sqlrs.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlrs");
      } finally {
        try {
          if (sqlstatement != null) {
            sqlstatement.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlstatement");
        } finally {
          try {
            if (conn_tmp2 != null) {
              conn_tmp2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn_tmp2");
          }
        }
      }
    }
  }
  private void goodB2G1Sink(String data) throws Throwable {
    if (goodB2G1Private) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;

      try {
        /* FIX: Use prepared statement and execute (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement(
                "insert into users (status) values ('updated') where name=?");
        sqlStatement.setString(1, data);

        Boolean result = sqlStatement.execute();

        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  public void action(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    if (data != null) {
      String names[] = data.split("-");
      int successCount = 0;
      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      try {
        /* FIX: Use prepared statement and executeBatch (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement =
            dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?");
        for (int i = 0; i < names.length; i++) {
          sqlStatement.setString(1, names[i]);
          sqlStatement.addBatch();
        }
        int resultsArray[] = sqlStatement.executeBatch();
        for (int i = 0; i < names.length; i++) {
          if (resultsArray[i] > 0) {
            successCount++;
          }
        }
        IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
Beispiel #22
0
 public void destroy() {
   try {
     // session.close();
     ps.close();
     con.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(HashMap<Integer, String> dataHashMap) throws Throwable {
    String data = dataHashMap.get(2);

    Connection dbConnection = null;
    PreparedStatement sqlStatement = null;
    ResultSet resultSet = null;

    try {
      /* FIX: Use prepared statement and executeQuery (properly) */
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
      sqlStatement.setString(1, data);

      resultSet = sqlStatement.executeQuery();

      IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (resultSet != null) {
          resultSet.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
      }

      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
  private void goodB2G() throws Throwable {
    String data = goodB2G_source();

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    PreparedStatement sqlstatement = null;

    try {
      /* FIX: use prepared sqlstatements */
      conn_tmp2 = IO.getDBConnection();
      sqlstatement =
          conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
      sqlstatement.setString(1, data);

      Boolean bResult = sqlstatement.execute();

      if (bResult) {
        IO.writeString("Name, " + data + ", updated successfully");
      } else {
        IO.writeString("Unable to update records for user: "******"Error getting database connection");
    } finally {
      try {
        if (sqlstatement != null) {
          sqlstatement.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlstatement");
      } finally {
        try {
          if (conn_tmp2 != null) {
            conn_tmp2.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing conn_tmp2");
        }
      }
    }
  }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(LinkedList<String> dataLinkedList) throws Throwable {
    String data = dataLinkedList.remove(2);

    Connection dbConnection = null;
    PreparedStatement sqlStatement = null;

    try {
      /* FIX: Use prepared statement and execute (properly) */
      dbConnection = IO.getDBConnection();
      sqlStatement =
          dbConnection.prepareStatement(
              "insert into users (status) values ('updated') where name=?");
      sqlStatement.setString(1, data);

      Boolean result = sqlStatement.execute();

      if (result) {
        IO.writeLine("Name, " + data + ", updated successfully");
      } else {
        IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
  /* goodG2B() - use GoodSource and BadSink */
  public void goodG2BSink(LinkedList<String> dataLinkedList) throws Throwable {
    String data = dataLinkedList.remove(2);

    Connection dbConnection = null;
    PreparedStatement sqlStatement = null;

    try {
      /* POTENTIAL FLAW: data concatenated into SQL statement used in prepareStatement() call, which could result in SQL Injection */
      dbConnection = IO.getDBConnection();
      sqlStatement =
          dbConnection.prepareStatement(
              "insert into users (status) values ('updated') where name='" + data + "'");

      Boolean result = sqlStatement.execute();

      if (result) {
        IO.writeLine("Name, " + data + ", updated successfully");
      } else {
        IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
Beispiel #27
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String fName = req.getParameter("fName");
    String lName = req.getParameter("lName");
    String party = req.getParameter("party");
    String area = req.getParameter("area");

    Connection c = null;
    try {
      DriverManager.registerDriver(new AppEngineDriver());
      c =
          DriverManager.getConnection(
              "jdbc:google:rdbms://netivalimised2013:netivalimised/evalimised");
      String statement;
      if ((fName.equals("") || fName == null)
          && (lName.equals("") || lName == null)
          && (party.equals("") || party == null)
          && (area.equals("") || area == null)) {
        System.out.println("Getting all candidates");
        statement =
            "SELECT Person.FirstName, Person.LastName, Party.PartyName, Area.AreaName "
                + "FROM Person JOIN Party ON Person.PartyID = Party.Party_Id JOIN Area ON Person.AreaID = Area.Area_Id";
      } else statement = createQuery(fName, lName, party, area);
      PreparedStatement stmt = c.prepareStatement(statement);
      ResultSet rs = stmt.executeQuery();
      String jsonData = createJSON(rs, party, area);
      resp.setContentType("application/json");
      resp.setCharacterEncoding("UTF-8");
      resp.getWriter().write(jsonData);
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException ignore) {
        }
      }
    }
    // resp.setHeader("Refresh","3; url=/evalimised.jsp");
  }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // I use "session" in order to throws the object named user bean.
   HttpSession session = request.getSession(true);
   response.setContentType("text/html");
   request.setCharacterEncoding("UTF-8");
   UserBean ub = (UserBean) session.getAttribute("user");
   if (ub == null) {
     String haveLogin = "******";
     session.setAttribute("haveLogin", haveLogin);
     response.sendRedirect("cart");
   } else {
     String mID = ub.getmID();
     String iID = (String) request.getParameter("iID");
     // String idx = (String)request.getParameter("idx");
     Connection conn = null;
     try {
       // Getting the connection from database.
       Class.forName("com.mysql.jdbc.Driver");
       /*conn = DriverManager
       .getConnection("jdbc:mysql://localhost/se?"
       		+ "user=root");*/
       conn =
           DriverManager.getConnection(
               "jdbc:mysql://localhost/user_register?"
                   + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8");
       String sql = "delete from cart_item_mapping where mID=? and iID = ?";
       PreparedStatement pst = conn.prepareStatement(sql);
       // Using preparedstatement by set the parameter related to "?" symbol.
       pst.setString(1, mID);
       pst.setString(2, iID);
       pst.executeUpdate();
       pst.close();
       response.sendRedirect("ShowCartController");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE89_SQL_Injection__getQueryString_Servlet_executeUpdate_61b())
            .goodB2GSource(request, response);

    Connection dbConnection = null;
    PreparedStatement sqlStatement = null;

    try {
      /* FIX: Use prepared statement and executeUpdate (properly) */
      dbConnection = IO.getDBConnection();
      sqlStatement =
          dbConnection.prepareStatement(
              "insert into users (status) values ('updated') where name=?");
      sqlStatement.setString(1, data);

      int rowCount = sqlStatement.executeUpdate();

      IO.writeLine("Updated " + rowCount + " rows successfully.");
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   try {
     String comment = request.getParameter("comment");
     int answerId = Integer.parseInt(request.getParameter("answer_id"));
     Connection connection = GlobalResources.getConnection();
     Statement s;
     s = connection.createStatement();
     PreparedStatement preparedStatement;
     PreparedStatement preparedStatement1;
     preparedStatement =
         connection.prepareStatement("insert into comment(comment,answer_id) values(?,?)");
     preparedStatement.setString(1, comment);
     preparedStatement.setInt(2, answerId);
     preparedStatement.executeUpdate();
     preparedStatement.close();
     connection.close();
     RequestDispatcher requestDispatcher;
     requestDispatcher = request.getRequestDispatcher("/studenthome.jsp");
     requestDispatcher.forward(request, response);
   } catch (Exception e) {
   }
 }