private void setHttpRequestStockPlace(HttpServletRequest request, OutMgr outMgr) {
   outMgr.setCurrentInventoryPlace(request.getParameter("place"));
   outMgr.setLocationPlace(
       (LocationPlace)
           Utility.getObject(
               outMgr.getStockPlaceMeta().getStockPlaceList(), request.getParameter("place")));
 }
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
Example #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();
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing first private_final_five==5 to private_final_five!=5 */
  private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;
    /* INCIDENTAL: CWE 570 Statement is Always False */
    if (private_final_five != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      /* init Data$ */
      data = -1;
      /* read parameter from request */
      String s_data = request.getParameter("name");
      data = Integer.parseInt(s_data.trim());
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded number that won't cause underflow, overflow,
      divide by zero, or loss-of-precision issues */
      data = 2;
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      /* POTENTIAL FLAW: Zero denominator will cause an issue.  An integer division will
      result in an exception. */
      IO.writeLine("bad: 100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* FIX: test for a zero denominator */
      if (data != 0) {
        IO.writeLine("100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
      } else {
        IO.writeLine("This would result in a divide by zero");
      }
    }
  }
  /* goodB2G() - use badsource and goodsink by changing the conditions on
  the second and third for statements */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* POTENTIAL FLAW: data may be set to null */
    data = request.getParameter("CWE690");

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: Set data to a fixed, non-null String */
      data = "CWE690";
    }

    for (int for_index_j = 0; for_index_j < 0; for_index_j++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* POTENTIAL FLAW: data could be null */
      String sOut = data.trim();
      IO.writeLine(sOut);
    }

    for (int for_index_k = 0; for_index_k < 1; for_index_k++) {
      /* FIX: explicit check for null */
      if (data != null) {
        String sOut = data.trim();
        IO.writeLine(sOut);
      }
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
Example #7
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_final_five == 5) {
      /* FIX: Set data to a fixed, non-null String */
      data = "CWE690";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* POTENTIAL FLAW: data may be set to null */
      data = request.getParameter("CWE690");
    }
    if (IO.static_final_five == 5) {
      /* POTENTIAL FLAW: data could be null */
      if (data.equals("CWE690")) {
        IO.writeLine("data is CWE690");
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* FIX: call equals() on string literal (that is not null) */
      if ("CWE690".equals(data)) {
        IO.writeLine("data is CWE690");
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* We need to have one source outside of a for loop in order
    to prevent the Java compiler from generating an error because
    data is uninitialized */

    /* POTENTIAL FLAW: data may be set to null */
    data = request.getParameter("CWE690");

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: Set data to a fixed, non-null String */
      data = "CWE690";
    }

    for (int for_index_j = 0; for_index_j < 1; for_index_j++) {
      /* POTENTIAL FLAW: data could be null */
      String sOut = data.trim();
      IO.writeLine(sOut);
    }

    for (int for_index_k = 0; for_index_k < 0; for_index_k++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      /* FIX: explicit check for null */
      if (data != null) {
        String sOut = data.trim();
        IO.writeLine(sOut);
      }
    }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
      res.setContentType("text/html");
      pw = res.getWriter();
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:com", "o7it58", "yajiv32737");
      st = con.createStatement();
      pw.println("<html>");
      pw.println("<head><title>Welcome</title></head>");
      pw.println("<body>");

      s = req.getParameter("login");
      if (s.equals("Submit")) {
        uname = req.getParameter("firstname");
        pass = req.getParameter("pwd");
        PrintWriter out = new PrintWriter(new FileWriter("log.txt"), true);
        out.println(uname);
        rs =
            st.executeQuery(
                "select type from login where username='******' and password='******'");
        if (rs.next()) {
          type = rs.getString("type");
        } else {
          pw.println("<center>");
          pw.println("User does not exists");
          pw.println("</center>");
        }
        if (type.equals("admin")) {

          pw.println(
              "<a href=\"http://localhost:8080/servlet/AdminLogin\">Hello Admin.Please Click Here</a>");
        } else if (type.equals("staff")) {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StaffLogin\">Hello Staff.Please Click Here</a>");
        } else {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StudentLogin\">Hello Student.Please Click Here</a>");
        }
      }
      pw.println("</body></html>");
    } catch (Exception e) {
    }
  }
Example #11
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
Example #12
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
  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);

      int user_id = Integer.parseInt(request.getParameter("user_id"));
      int question_id = Integer.parseInt(request.getParameter("question_id"));
      int option = Integer.parseInt(request.getParameter("option"));

      System.out.println("uid: " + user_id + "\nquestion: " + question_id + "\noption: " + option);
      String str1 = "INSERT INTO VOTES(USER_ID, QUESTION_ID,OPTION_VOTED) VALUES (?,?,?)";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setInt(1, user_id);
      prep1.setInt(3, option);
      prep1.setInt(2, question_id);
      prep1.execute();

      String str2 = "SELECT OPTION_" + option + " FROM ARCHIVE_VOTES WHERE QUESTION_ID=?";
      PreparedStatement prep2 = con.prepareStatement(str2);
      prep2.setInt(1, question_id);
      int count = 0;
      ResultSet rs2 = prep2.executeQuery();
      if (rs2.next()) {
        count = rs2.getInt("OPTION_" + option);
      }
      count++;
      String str3 = "UPDATE ARCHIVE_VOTES SET OPTION_" + option + "=? WHERE QUESTION_ID=?";
      PreparedStatement prep3 = con.prepareStatement(str3);
      prep3.setInt(1, count);
      prep3.setInt(2, question_id);
      prep3.executeUpdate();

      out.print("You Vote has been recorded! Thank you!");
      System.out.println(
          "Voted for question " + question_id + ", by user " + user_id + ", for option " + option);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();
    PR.deleteProduct(req.getParameter("prid"));
    pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>");
    pw.println("<table align='center' border=0>");
    pw.println("<tr col span=2><th>Web-Enabled Automated Manufacturing Process</th></tr>");
    pw.println("<tr><td>Product ID:</td><td>" + req.getParameter("prid") + "</td></tr>");

    pw.println("<tr><td>Product data is deleted Click on OK to Continue</td></tr>");
    pw.println(
        "<tr><td align=center><a href='http://peers:8080/servlet/deleteProduct' target='main'>OK</a></td>");
    pw.println("<td></td></tr>");
    pw.println("</table></form></body></html>");
    pw.flush();
    pw.close();
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String nombreChofer = request.getParameter("nombreChofer");
    String telefonoChofer = request.getParameter("telefonoChofer");
    float salarioChofer = Float.parseFloat(request.getParameter("salarioChofer"));
    String choferID = request.getParameter("usernameChofer");

    Chofer c = new Chofer(nombreChofer, telefonoChofer, salarioChofer);
    new ListaChoferes().updateChofer(choferID, c);

    request.setAttribute("mensaje", "Chofer modificado de manera exitosa");
    String color = "10E214";
    request.setAttribute("coloreado", color);
    request.setAttribute("ListaDeChoferes", new ListaChoferes().obtenerChoferes());
    request.getRequestDispatcher("VerChoferes.jsp").forward(request, response);
  }
  /* goodB2G() - use badsource and goodsink */
  private String goodB2G_source(HttpServletRequest request, HttpServletResponse response)
      throws Throwable {
    String data;

    /* POTENTIAL FLAW: data may be set to null */
    data = request.getParameter("CWE690");

    return data;
  }
  /* goodB2G() - use badsource and goodsink by changing the second "if" so that
  both branches use the GoodSink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* init Data$ */
      data = -1;
      /* read parameter from request */
      String s_data = request.getParameter("name");
      data = Integer.parseInt(s_data.trim());
    } else {

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

      /* init Data$ */
      data = -1;

      /* read parameter from request */
      String s_data = request.getParameter("name");
      data = Integer.parseInt(s_data.trim());
    }
    if (IO.static_returns_t_or_f()) {
      int valueToSub = (new SecureRandom()).nextInt(99) + 1; /* subtracting at least 1 */
      int result = 0;
      /* FIX: Add a check to prevent an underflow from occurring */
      if (data >= (Integer.MIN_VALUE + valueToSub)) {
        result = (data - valueToSub);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("Input value is too small to perform subtraction.");
      }
    } else {

      int valueToSub = (new SecureRandom()).nextInt(99) + 1; /* subtracting at least 1 */
      int result = 0;

      /* FIX: Add a check to prevent an underflow from occurring */
      if (data >= (Integer.MIN_VALUE + valueToSub)) {
        result = (data - valueToSub);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("Input value is too small to perform subtraction.");
      }
    }
  }
  /* 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);
        }
      }
    }
  }
Example #19
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   try {
     Driver driver = new com.mysql.jdbc.Driver();
     DriverManager.registerDriver(driver);
     Connection connection =
         DriverManager.getConnection("jdbc:mysql://127.0.0.1/school", "root", "password");
     PreparedStatement preparedStatement =
         connection.prepareStatement("update student set name=?, per=? where roll=?");
     preparedStatement.setString(1, request.getParameter("name"));
     preparedStatement.setFloat(2, Float.parseFloat(request.getParameter("per")));
     preparedStatement.setInt(3, Integer.parseInt(request.getParameter("roll")));
     preparedStatement.execute();
     preparedStatement.close();
     connection.close();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Display");
   requestDispatcher.forward(request, response);
 }
Example #20
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 service(
     HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
     throws ServletException, IOException {
   System.out.println("This is my service");
   String s = "";
   String s2 = "";
   String s4 = "";
   String s6 = "";
   String s7 = "";
   String s8 = "";
   java.io.PrintWriter printwriter = httpservletresponse.getWriter();
   httpservletresponse.setContentType("text/html");
   HttpSession httpsession = httpservletrequest.getSession(true);
   s6 = (String) httpsession.getValue("co");
   s7 = (String) httpsession.getValue("na");
   s8 = (String) httpsession.getValue("ss");
   try {
     String s1 = httpservletrequest.getParameter("text1");
     String s3 = httpservletrequest.getParameter("text2");
     String s5 = httpservletrequest.getParameter("text3");
     System.out.println("code iiiiis" + s1);
     System.out.println("cname iss" + s3);
     System.out.println("status iss" + s5);
     int i =
         st.executeUpdate(
             "update categoryies set categoryname='"
                 + s3
                 + "',status='"
                 + s5
                 + "' where categoryid='"
                 + s1
                 + "'");
     System.out.println(
         "update categoryies set categoryname='" + s3 + "' where categorycode='" + s1 + "'");
     System.out.println(i + " is updated");
     httpservletresponse.sendRedirect("./categories");
   } catch (Exception exception) {
     System.out.println(exception);
   }
 }
 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) {
   }
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   Integer etat = (Integer) request.getSession().getAttribute("etat");
   if (etat == null) {
     RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
     dispatcher.forward(request, response);
   } else {
     try {
       String titre = request.getParameter("titre");
       String dateSortie = request.getParameter("dateSortie");
       String nom = request.getParameter("nom");
       String role = request.getParameter("role");
       // conversion du parametre dateSortie en SQLDate
       Date date;
       try {
         date = new Date(FormatDate.convertirDate(dateSortie).getTime());
       } catch (ParseException e) {
         throw new Tp6Exception(
             "Format de la date " + dateSortie + " incorrect. AAAA-MM-JJ attendue.");
       }
       // executer la transaction
       GestionTp6 tp6Update = (GestionTp6) request.getSession().getAttribute("tp6Update");
       synchronized (tp6Update) {
         tp6Update.gestionFilm.ajoutActeurFilm(titre, date, nom, role);
       }
       RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/menu.jsp");
       dispatcher.forward(request, response);
     } catch (Tp6Exception e) {
       List<String> listeMessageErreur = new LinkedList<String>();
       listeMessageErreur.add(e.toString());
       request.setAttribute("listeMessageErreur", listeMessageErreur);
       RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/menu.jsp");
       dispatcher.forward(request, response);
     } catch (Exception e) {
       e.printStackTrace();
       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
     }
   }
 }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

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

    /* init Data$ */
    data = -1;

    /* read parameter from request */
    String s_data = request.getParameter("name");
    data = Integer.parseInt(s_data.trim());

    (new CWE369_Divide_By_Zero__getParameterServlet_divide_53b()).bad_sink(data, request, response);
  }
  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();
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

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

    /* init Data$ */
    data = -1;

    /* read parameter from request */
    String s_data = request.getParameter("name");
    data = Integer.parseInt(s_data.trim());

    (new CWE190_Integer_Overflow__getParameterServlet_add_51b())
        .goodB2G_sink(data, request, response);
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* We need to have one source outside of a for loop in order
    to prevent the Java compiler from generating an error because
    data is uninitialized */

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

    /* read parameter from request */
    data = request.getParameter("name");

    for (int for_index_i = 0; for_index_i < 0; for_index_i++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      data = "5";
    }

    for (int for_index_j = 0; for_index_j < 1; for_index_j++) {
      int loopNum;
      try {
        loopNum = Integer.parseInt(data);
      } catch (NumberFormatException nfe) {
        IO.writeLine("Invalid response. Numeric input expected. Assuming 1.");
        loopNum = 1;
      }
      for (int i = 0; i < loopNum; i++) {
        /* POTENTIAL FLAW: user supplied input used for loop counter test */
        IO.writeLine("hello world");
      }
    }

    for (int for_index_k = 0; for_index_k < 0; for_index_k++) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      int loopNum;
      try {
        loopNum = Integer.parseInt(data);
      } catch (NumberFormatException nfe) {
        IO.writeLine("Invalid response. Numeric input expected. Assuming 1.");
        loopNum = 1;
      }
      /* FIX: loop number thresholds validated */
      if (loopNum >= 0 && loopNum <= 5) {
        for (int i = 0; i < loopNum; i++) {
          IO.writeLine("hello world");
        }
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.staticTrue) {
      /* 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 (IO.staticTrue) {
      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
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // get a connection
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();

    String sqlStatement = request.getParameter("sqlStatement");
    String sqlResult = "";
    try {
      // create a statement
      Statement statement = connection.createStatement();

      // parse the SQL string
      sqlStatement = sqlStatement.trim();
      if (sqlStatement.length() >= 6) {
        String sqlType = sqlStatement.substring(0, 6);
        if (sqlType.equalsIgnoreCase("select")) {
          // create the HTML for the result set
          ResultSet resultSet = statement.executeQuery(sqlStatement);
          sqlResult = SQLUtil.getHtmlTable(resultSet);
          resultSet.close();
        } else {
          int i = statement.executeUpdate(sqlStatement);
          if (i == 0) {
            sqlResult = "<p>The statement executed successfully.</p>";
          } else { // an INSERT, UPDATE, or DELETE statement
            sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>";
          }
        }
      }
      statement.close();
      connection.close();
    } catch (SQLException e) {
      sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>";
    } finally {
      pool.freeConnection(connection);
    }

    HttpSession session = request.getSession();
    session.setAttribute("sqlResult", sqlResult);
    session.setAttribute("sqlStatement", sqlStatement);

    String url = "/index.jsp";
    getServletContext().getRequestDispatcher(url).forward(request, response);
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_five == 5) {
      data = "5";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      /* read parameter from request */
      data = request.getParameter("name");
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_five == 5) {
      int loopNum;
      try {
        loopNum = Integer.parseInt(data);
      } catch (NumberFormatException nfe) {
        IO.writeLine("Invalid response. Numeric input expected. Assuming 1.");
        loopNum = 1;
      }
      for (int i = 0; i < loopNum; i++) {
        /* POTENTIAL FLAW: user supplied input used for loop counter test */
        IO.writeLine("hello world");
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      int loopNum;
      try {
        loopNum = Integer.parseInt(data);
      } catch (NumberFormatException nfe) {
        IO.writeLine("Invalid response. Numeric input expected. Assuming 1.");
        loopNum = 1;
      }

      /* FIX: loop number thresholds validated */
      if (loopNum >= 0 && loopNum <= 5) {
        for (int i = 0; i < loopNum; i++) {
          IO.writeLine("hello world");
        }
      }
    }
  }