/* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String data) throws Throwable {

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
      int rowCount =
          sqlStatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      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 Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
Ejemplo n.º 2
0
  @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);
  }
  /* goodG2B1() - use goodsource and badsink by changing first privateFive==5 to privateFive!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (privateFive != 5) {
      /* 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 (privateFive == 5) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
        int rowCount =
            sqlStatement.executeUpdate(
                "insert into users (status) values ('updated') where name='" + data + "'");
        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 Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE89_SQL_Injection__getQueryString_Servlet_executeUpdate_61b())
            .goodG2BSource(request, response);

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
      int rowCount =
          sqlStatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      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 Statement", 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 goodG2B_sink(Object data_obj) throws Throwable {
    String data = (String) data_obj;

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

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      /* POTENTIAL FLAW: place user input into dynamic sql query */
      int iResult =
          sqlstatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      IO.writeString("Updated " + iResult + " rows successfully.");
    } 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");
        }
      }
    }
  }
Ejemplo n.º 6
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector =
          (org.glassfish.jsp.api.ResourceInjector)
              application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\n");
      out.write("    \n");
      out.write("    \n");
      out.write("    \n");
      Class.forName("com.mysql.jdbc.Driver");
      out.write("\n");
      out.write("    \n");
      out.write("    \n");
      out.write(
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write(" <link href=\"css/bootstrap.min.css\" rel=\"stylesheet\">\n");
      out.write("        <!-- Bootstrap css online -->\n");
      out.write(
          "        <link rel=\"stylesheet\" href=\"http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css\">\n");
      out.write("        <link  href=\"css/customcss.css\" rel=\"stylesheet\">\n");
      out.write(
          "        <script type=\"text/javascript\" src=\"js/jquery-1.10.2.min.js\"></script>\n");
      out.write("        <script src=\"js/bootstrap.min.js\"></script>\n");
      out.write("\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n");
      out.write("<title>Analysis of Algorithms : D.B.Phatak</title>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      out.write("\n");
      out.write("<!--Header-->\n");
      out.write("\n");
      out.write("  ");

      String name = (String) session.getAttribute("pass");

      out.write("\n");
      out.write("    <div class=\"container\">\n");
      out.write("             <br>\n");
      out.write("            <!--HEADER -->\n");
      out.write("            <div class=\"header\">\n");
      out.write(
          "                <a href=\"index.jsp\" style=\"color: #000;\"> <ul class=\"nav nav-pills pull-left\" >\n");
      out.write(
          "                    <li id=\"brand_icon\">       <img src=\"Images/mic_logo.png\" alt=\"\" width=\"80px\" height=\"80px\"/></li>\n");
      out.write(
          "                    <li id=\"brand_name\"> <p class=\"title\"><span style=\"font-size: 70px;\">|</span> iClass <strong>Forum</strong></p></li>\n");
      out.write("\n");
      out.write("                </ul></a>\n");
      out.write(
          "                <!--   <p class=\"title1\">iClass</p>&nbsp;&nbsp;<p class=\"title2\">Forum</p> \n");
      out.write("                -->\n");
      out.write("                <form action=\"Login\" method=\"post\">\n");
      out.write("\n");
      out.write(
          "                    <ul class=\"nav nav-pills pull-right\" style=\"margin-top: 35px\">\n");
      out.write("                        <li><a href=\"index.jsp\">Home</a></li>\n");
      out.write("                        <li><a href=\"contactus.jsp\">Contact Us</a></li>\n");
      out.write("\n");
      out.write("                        ");
      if (name != null) {
        try {
          out.write("\n");
          out.write("\n");
          out.write("                        <li><a href=\"logout.jsp\">Logout</a></li>\n");
          out.write("                        <li style=\"margin-top: 10px\">Welcome ");
          out.print(name);
          out.write("</li>\n");
          out.write("\n");
          out.write("                        ");
        } catch (Exception e) {

          System.out.println("Problem :" + e);
        }

      } else {

        out.write("\n");
        out.write("\n");
        out.write("                        <li><a href=\"signup.jsp\">Login</a></li>\n");
        out.write("\n");
        out.write("                        ");
      }
      out.write("\n");
      out.write("\n");
      out.write("                    </ul>\n");
      out.write("                </form>\n");
      out.write("\n");
      out.write("\n");
      out.write("            </div>\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("            <br>\n");
      out.write("         \n");
      out.write("      \n");
      out.write("\n");
      out.write("        <!-- MODAL -->\n");
      out.write("        <form action=\"\" name=\"batti\" method=\"post\">\n");
      out.write("\n");
      out.write(
          "        <div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\n");
      out.write("          <div class=\"modal-dialog\">\n");
      out.write("            <div class=\"modal-content\">\n");
      out.write("              <div class=\"modal-header\">\n");
      out.write(
          "                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\n");
      out.write("                <h4 class=\"modal-title\" id=\"myModalLabel\">Answer here</h4>\n");
      out.write("              </div>\n");
      out.write("              <div class=\"modal-body\">\n");
      out.write("                                <div class=\"input-group input-group-lg\">\n");
      out.write("                                <span class=\"input-group-addon\">\n");
      out.write(
          "                                <span class=\"glyphicon glyphicon-pencil\"></span>\n");
      out.write("                                </span>\n");
      out.write(
          "                                <textarea class=\"form-control\" id=\"currentans\" name=\"mainanswer\" rows=\"10\" style=\"resize: vertical;\">\n");
      out.write("                                </textarea>\n");
      out.write("                                </div>\n");
      out.write("              </div>\n");
      out.write("              <div class=\"modal-footer\">\n");
      out.write(
          "              <input type=\"text\" id=\"hidden\" name=\"maindata\" value=\"JAI HO\"/>\n");
      out.write(
          "                <button type=\"button\" class=\"btn btn-primary\" onClick=\"saveAns()\">Save Answer</button>\n");
      out.write("              </div>\n");
      out.write("            </div>\n");
      out.write("          </div>\n");
      out.write("        </div>\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("    </form>\n");
      out.write("    <!-- MODAL ENDS HERE -->\n");
      out.write("\n");
      out.write("<div class=\"page1\" >          \n");
      out.write("                <center>\n");
      out.write("\n");
      out.write(
          "                    <font face=\"myFontThin\" size=\"6\" class=\"title\">Department of  </font><font face=\"myFontThick\" size=\"8\"><b>Computer Science</b></font>\n");
      out.write("                <br>\n");
      out.write("                   <font face=\"myFontThick\" size=\"5\">Prof. sunil</font>\n");
      out.write("                \n");
      out.write("                </center>\n");
      out.write(
          "                <br> <br>  <font face=\"myFontThick\" size=\"6\"><b> bbbbbb </b></font>\n");
      out.write("<br><br><br>\n");
      out.write("                        \n");
      out.write("\n");
      out.write("\n");
      out.write("            ");

      Connection connection =
          DriverManager.getConnection("jdbc:mysql://localhost/aakash", "root", "lavikothari");
      Statement statement = connection.createStatement();
      ResultSet resultset = statement.executeQuery("select * from qa27;");

      int i = 0, no, ct = 0;
      String qid, bid, ansdivid, buttonid, delbuttonid, userid, answerid;

      while (resultset.next()) {
        ct++;
        no = resultset.getInt(1);
        if (i < no) {
          i = no;
        }
        qid = "q" + no;
        ansdivid = "ans" + no;
        bid = "b" + no;
        buttonid = "button" + no;
        delbuttonid = "delbutton" + no;
        userid = "user" + no;
        answerid = "answer" + no;

        out.write("\n");
        out.write("        <!--  <form action=\"\" method=\"get\" name=\"batti\" > -->\n");
        out.write("\t    \n");
        out.write("\t<div class=\"panel panel-default\">\n");
        out.write("            <div class=\"panel-heading\">\n");
        out.write("                <h3 class=\"panel-title\">\n");
        out.write("                <div id=");
        out.print(userid);
        out.write(
            " style=\"font-style:bold ;font-size:15px; padding-left:0.5px ;text-shadow: 2px 2px 8px #6E6E6E\">\n");
        out.write("\t    \t");
        out.print(resultset.getString(4));
        out.write("\n");
        out.write("                </div>\n");
        out.write("                </h3>\n");
        out.write("            </div>\n");
        out.write("            <div class=\"panel-body\">\n");
        out.write("                <div id=");
        out.print(qid);
        out.write(" style=\"text-align:left ;font-size:20px;font-style:italic\">\n");
        out.write("\t\t\t");
        out.print(resultset.getString(2));
        out.write("<br><br>\n");
        out.write("\t\t</div>\n");
        out.write("\t    \t<div class=\"panel panel-default\" id=");
        out.print(ansdivid);
        out.write(" >\n");
        out.write("  \t\t\t\t<div class=\"panel-body\" >\n");
        out.write("   \t\t\t \t\t<p id=");
        out.print(answerid);
        out.write('>');
        out.print(resultset.getString(3));
        out.write("</p>\n");
        out.write(" \t\t \t\t</div>\n");
        out.write("\t\t</div>\n");
        out.write("\t\t<div id=");
        out.print(bid);
        out.write(" >\n");
        out.write("\t\t\t ");
        String condition = (String) session.getAttribute("pass");
        String prof1 = (String) session.getAttribute("Prof");
        String prof2 = (String) session.getAttribute("Prof2");

        // out.println("Lec="+condition);

        // out.println("prof1="+prof1);
        // out.println("prof2="+prof2);
        // System.out.println("Lec="+condition);
        if (condition != null && prof1.equals(prof2)) {

          out.write("       \n");
          out.write("\n");
          out.write(
              "                                <input type=\"button\" class=\"btn btn-primary btn-sm\" style=\"float:right;display:inline\" value=\"Delete\" onClick=\"delQues(this.id)\" id=");
          out.print(delbuttonid);
          out.write(" />\n");
          out.write(
              "                                <input type=\"button\" class=\"btn btn-primary btn-sm\" style=\"float:left;display:inline\" data-toggle=\"modal\" value=\"Answer\" data-target=\"#myModal\" onClick=\"myfunc(this.id)\" id=");
          out.print(buttonid);
          out.write(" />\n");
          out.write("                                ");
        }

        out.write("\n");
        out.write("         \n");
        out.write("\t\t</div>\n");
        out.write("            </div>\n");
        out.write("        </div>\n");
        out.write("\t\n");
        out.write("\t   \n");
        out.write("\t\t\n");
        out.write("        ");
      }
      out.write("\n");
      out.write("\n");
      out.write(
          "               <form action=\"\" name=\"delform\" method=\"post\" style=\"visibility:hidden\">\n");
      out.write("\n");
      out.write(
          "               <input type=\"text\" id= \"delfieldid\" name=\"delfield\" value=\"Namastey\" />\n");
      out.write(
          "               <input type=\"text\" id= \"futureid\" name=\"futurefield\" value=\"London\" />\n");
      out.write("               </form>\n");
      out.write("\n");
      out.write("\n");
      out.write("        <span id =\"debug\" style=\"visibility:hidden\">Hello </span>\n");
      out.write("\n");
      out.write("    </div>\n");
      out.write("</div>    \n");
      out.write("\t    \n");
      out.write(" \n");
      out.write("</div>\n");
      out.write(" \n");
      out.write(" </div>\n");
      out.write("        \n");
      out.write(" \n");
      out.write(" <script type=\"text/javascript\">\n");
      out.write("\t count=");
      out.print(ct);
      out.write(";\n");
      out.write("\t debugging=document.getElementById(\"debug\");\n");
      out.write("\t debugging.innerHTML=\"Count is\"+count;\n");
      out.write("\t hid=document.getElementById(\"hidden\");\n");
      out.write("\t hid.style.display='none';\n");
      out.write("\t \n");
      out.write("\t for (x=1;x<=count;x++)\n");
      out.write("\t {\t\n");
      out.write("\t\t y=document.getElementById(\"answer\"+x);\n");
      out.write("\t\t debug.innerHTML+=y.innerHTML;\n");
      out.write("\t\t z=document.getElementById(\"button\"+x);\n");
      out.write("\t\t if(y!=null && y.innerHTML==\"\")\n");
      out.write("\t\t {\n");
      out.write("\t\t document.getElementById(\"ans\"+x).style.display='none';\n");
      out.write("\t\t }\n");
      out.write("\t\t \n");
      out.write("\t\t else\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t if(z!=null){\n");
      out.write("\t\t\t z.value=\"Edit Answer\";\n");
      out.write("\t\t\t }\n");
      out.write("\t\t\t }\n");
      out.write("\t }\n");
      out.write("\n");
      out.write("\t function myfunc(clicked_id){\n");
      out.write("\t\t \n");
      out.write("\t\t hid.value=clicked_id;\n");
      out.write("\t\t quesid=clicked_id.replace(\"button\",\"q\");\n");
      out.write("\t\t ansid=clicked_id.replace(\"button\",\"answer\");\n");
      out.write("\t\t \n");
      out.write("\t\t question=document.getElementById(quesid).innerHTML;\n");
      out.write("\t\t answer=document.getElementById(ansid).innerHTML;\n");
      out.write("\t\t \n");
      out.write("\t\t answer.replace(\"  \",\"\");\n");
      out.write("\t\t question.replace(\"  \",\"\");\n");
      out.write("\t\t \n");
      out.write("\t\t document.getElementById(\"myModalLabel\").innerHTML=question;\n");
      out.write("\t\t document.getElementById(\"currentans\").value=answer;\n");
      out.write("\t\t \n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t\n");
      out.write("\t function saveAns()\n");
      out.write("\t {\n");
      out.write("\t\t document.batti.submit();\n");
      out.write("\t\t \n");
      out.write("\t\t ");

      String clid = request.getParameter("maindata");
      if (clid != null) {
        String tobeanswered = clid.replace("button", "");
        System.out.println(tobeanswered);
        String answer = request.getParameter("mainanswer");

        Statement stmt = connection.createStatement();
        String query = "update qa27 set ans ='" + answer + "' where id='" + tobeanswered + "';";

        stmt.executeUpdate(query);

        response.sendRedirect("lec.jsp#user" + tobeanswered);
      }

      out.write("\n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t \n");
      out.write("\n");
      out.write("\t function delQues(clicked_id)\n");
      out.write("\t {\n");
      out.write("\t\t \n");
      out.write("\t\t document.getElementById(\"delfieldid\").value=clicked_id;\n");
      out.write("\t\t \n");
      out.write("\t\t \n");
      out.write("\t\t\t document.getElementById(\"futureid\").value=\"yesssssssss\";\n");
      out.write("\t\t  v=parseInt(clicked_id.replace(\"delbutton\",\"\"))+1;\n");
      out.write("\t\t while(document.getElementById(\"user\"+v)==null && v<count)\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t v++;\n");
      out.write("\t\t\t document.getElementById(\"futureid\").value=\"user\"+v;\n");
      out.write("\t\t\t }\n");
      out.write("\t\t if(clicked_id==\"delbutton\"+count)\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t v=parseInt(clicked_id.replace(\"delbutton\",\"\"))-1;\n");
      out.write("\t\t\t }\n");
      out.write("\t\tdocument.getElementById(\"futureid\").value=\"user\"+v;\n");
      out.write("\t\t\t \n");
      out.write("\t\t document.delform.submit();\n");
      out.write("\t\t \n");
      out.write("\t\t ");

      String delid = request.getParameter("delfield");
      if (delid != null) {
        String tobedel = delid.replace("delbutton", "");
        System.out.println("Deleting " + tobedel);

        Statement stmt1 = connection.createStatement();
        String query1 = "delete from qa27 where id='" + tobedel + "';";

        stmt1.executeUpdate(query1);
        String futid = request.getParameter("futurefield");
        response.sendRedirect("lec.jsp#" + futid);
      }

      out.write("\n");
      out.write("\t\t \n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t \n");
      out.write("\t </script>\n");
      out.write("\t\n");
      out.write("\n");
      out.write("</body>\n");
      out.write("</html> \n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    HttpSession session = request.getSession(false);
    if (session == null) {
      session = request.getSession();
    }

    PrintWriter out = response.getWriter();
    Connection conn = null;
    Statement stmt = null;
    try {
      System.out.println("Enrollno: 130050131067");
      // 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...");

      stmt = conn.createStatement();

      // STEP 2: Executing query
      String name = "asdf";
      String rollno = "34";
      String branch = "CSE";
      String sql =
          "INSERT INTO student(rollno, name, branch) VALUES ('"
              + rollno
              + "', '"
              + name
              + "', '"
              + branch
              + "')";

      if (stmt.executeUpdate(sql) != 0) {
        out.println("Record has been inserted</br>");
      } else {
        out.println("Sorry! Failure</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 (stmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
  }
Ejemplo n.º 8
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Variable initializations.
    HttpSession session = request.getSession();
    FileItem image_file = null;
    int record_id = 0;
    int image_id;

    // Check if a record ID has been entered.
    if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) {
      // If no ID has been entered, send message to jsp.
      response_message =
          "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>";
      session.setAttribute("msg", response_message);
      response.sendRedirect("UploadImage.jsp");
    }

    try {
      // Parse the HTTP request to get the image stream.
      DiskFileUpload fu = new DiskFileUpload();
      // Will get multiple image files if that happens and can be accessed through FileItems.
      List<FileItem> FileItems = fu.parseRequest(request);

      // Connect to the database and create a statement.
      conn = getConnected(drivername, dbstring, username, password);
      stmt = conn.createStatement();

      // Process the uploaded items, assuming only 1 image file uploaded.
      Iterator<FileItem> i = FileItems.iterator();

      while (i.hasNext()) {
        FileItem item = (FileItem) i.next();

        // Test if item is a form field and matches recordID.
        if (item.isFormField()) {
          if (item.getFieldName().equals("recordID")) {
            // Covert record id from string to integer.
            record_id = Integer.parseInt(item.getString());

            String sql = "select count(*) from radiology_record where record_id = " + record_id;
            int count = 0;

            try {
              rset = stmt.executeQuery(sql);

              while (rset != null && rset.next()) {
                count = (rset.getInt(1));
              }
            } catch (SQLException e) {
              response_message = e.getMessage();
            }

            // Check if recordID is in the database.
            if (count == 0) {
              // Invalid recordID, send message to jsp.
              response_message =
                  "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>";
              session.setAttribute("msg", response_message);
              // Close connection.
              conn.close();
              response.sendRedirect("UploadImage.jsp");
            }
          }
        } else {
          image_file = item;

          if (image_file.getName().equals("")) {
            // No file, send message to jsp.
            response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>";
            session.setAttribute("msg", response_message);
            // Close connection.
            conn.close();
            response.sendRedirect("UploadImage.jsp");
          }
        }
      }

      // Get the image stream.
      InputStream instream = image_file.getInputStream();

      BufferedImage full_image = ImageIO.read(instream);
      BufferedImage thumbnail = shrink(full_image, 10);
      BufferedImage regular_image = shrink(full_image, 5);

      // First, to generate a unique img_id using an SQL sequence.
      rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual");
      rset1.next();
      image_id = rset1.getInt(1);

      // Insert an empty blob into the table first. Note that you have to
      // use the Oracle specific function empty_blob() to create an empty blob.
      stmt.execute(
          "INSERT INTO pacs_images VALUES("
              + record_id
              + ","
              + image_id
              + ", empty_blob(), empty_blob(), empty_blob())");

      // to retrieve the lob_locator
      // Note that you must use "FOR UPDATE" in the select statement
      String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE";
      rset = stmt.executeQuery(cmd);
      rset.next();
      BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5);
      BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3);
      BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4);

      // Write the full size image to the blob object.
      OutputStream fullOutstream = myblobFull.getBinaryOutputStream();
      ImageIO.write(full_image, "jpg", fullOutstream);
      // Write the thumbnail size image to the blob object.
      OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream();
      ImageIO.write(thumbnail, "jpg", thumbOutstream);
      // Write the regular size image to the blob object.
      OutputStream regularOutstream = myblobRegular.getBinaryOutputStream();
      ImageIO.write(regular_image, "jpg", regularOutstream);

      // Commit the changes to database.
      stmt.executeUpdate("commit");
      response_message = "<p><font color=00CC00>Upload Successful.</font></p>";
      session.setAttribute("msg", response_message);

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
      response.sendRedirect("UploadImage.jsp");

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
    } catch (Exception ex) {
      response_message = ex.getMessage();
    }
  }
Ejemplo n.º 9
0
Archivo: Set1.java Proyecto: wangz/MYOA
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("gb2312");
    response.setContentType("text/html; charset=gb2312");
    out = response.getWriter();
    session = request.getSession();
    time = new Time();
    str = new Str();
    db = new Db();

    // 取得
    try {
      id = Integer.parseInt((String) request.getParameter("id"));
    } catch (Exception e) {
      id = 0;
    }
    password = request.getParameter("password");
    password = str.inStr(password);
    sqlsp = "SELECT * FROM password WHERE employeeid=" + id;
    sqlse = "SELECT employeeid FROM eminfo WHERE employeeid=" + id;
    sqlu =
        "UPDATE password SET time='"
            + time.getYMDHMS()
            + "',password='******' WHERE employeeid="
            + id;
    sqli =
        "INSERT INTO password(employeeid,password,time) VALUES("
            + id
            + ",'"
            + password
            + "','"
            + time.getYMDHMS()
            + "')";
    try {
      stmt = db.getStmtread();
      rs = stmt.executeQuery(sqlsp);
      // 不是第一次设置更新数据库
      if (rs.next()) {
        db.close();
        stmt = db.getStmt();
        temp = 0;
        temp = stmt.executeUpdate(sqlu);
        if (temp > 0) {
          request.setAttribute("msg", "设置成功");
        } else {
          request.setAttribute("msg", "设置失败");
        }
        db.close();
      } else {
        // 第一次设置
        db.close();
        temp = 0;
        stmt = db.getStmtread();
        rs = stmt.executeQuery(sqlse);
        if (rs.next()) {
          // id存在
          rs.close();
          stmt.close();
          temp = 0;
          stmt = db.getStmt();
          temp = stmt.executeUpdate(sqli);
          if (temp > 0) {
            request.setAttribute("msg", "设置成功");
          } else {
            request.setAttribute("msg", "设置失败");
          }
          db.close();
        } else {
          // id不存在
          db.close();
          request.setAttribute("msg", "员工序号不存在");
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      RequestDispatcher dispatcher = request.getRequestDispatcher("set1.jsp");
      dispatcher.forward(request, response);
    }
  }
Ejemplo n.º 10
0
	public void doPost (HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
	{
		Connection con=null;
		pw=res.getWriter();
		Statement stmt=null;
		ResultSet rr=null;
		ResultSetMetaData rsmd;
		res.setContentType("text/html");
		
		try
		{
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		con=DriverManager.getConnection("jdbc:odbc:sri","scott","tiger");
		stmt=con.createStatement();
		String inm="'"+req.getParameter("txtinm")+"'";
		String q="'"+req.getParameter("txtq")+"'";
		String t=req.getParameter("txtr");
		char type=t.charAt(0);
                                System.out.println((char)type);
		pw.println("Item name "+inm);
                                pw.println("Quantity "+q);
		pw.println("Item Type "+t);
		pw.println((char)type);
		String qry1=null;
		switch(type)
		{
			case 'H':
			case 'h':
				qry1="select rate,iname from hware where iname="+inm;
				pw.println(qry1);
				// rr=stmt.executeQuery("select rate from hware where iname="+inm);
				rr=stmt.executeQuery(qry1);
				pw.println("Query is Executed...");
				break;
			case 'S':
			case 's':      qry1="select rate,iname from sware where iname="+inm;
				pw.println(qry1);
				break;
			
			case 'M':
			case 'm':   rr=stmt.executeQuery("select rate,title from music where title="+inm);
				break;
			
			case 'B':
			case 'b': rr=stmt.executeQuery("select rate,title from books where title="+inm);
				break;
			default:
				{
				pw.println("Invalid choice");
				 myflag='n';
				}
                                                           
		}
		        pw.println("Concerned Statement Prepared and Executed...");
						
                                pw.println((char)type+" Valid item type "+myflag);
		
		/*rsmd=rr.getMetaData();
                                int col=rsmd.getColumnCount();
                                pw.println("The Above Query has fetched "+col+ " Columns");*/
		String name="";
		while(rr.next())	
                                {
		String rate=rr.getString(1);
		int amount=Integer.parseInt(rate);
                                name=rr.getString(2);
                                  System.out.println(" "+rate+" "+name);
		pw.println(" "+amount+" "+name);
		pw.println("\n"+myflag);
		System.out.println("Valid item name "+rr.getString(2)+"     "+myflag);
		}
		pw.println(" "+myflag);
                                 if(myflag=='y')
                                  {
			pw.println("\nOK");
		pw.println("Valid item name "+name+"     "+myflag);
		if(rr==null)
		{
			pw.println("Not a valid item");
			myflag='n';
		}
		pw.println("Valid item name "+name+"     "+myflag);
                                  if(myflag=='y')
                                  {
                                        pw.println(" "+inm+" "+q);
                                       rr=stmt.executeQuery("select * from reges where flag='y'");
		if(rr==null)
		{
			pw.println("\nSign in first");
			//System.exit(0);
                                                 myflag='n';
		}
		pw.println("Signed in "+rr.getString(1)+"     "+myflag);
                                    if(myflag=='y')
                                   {
		String data="'"+rr.getString(1)+"'";	
		String qry="insert into cart values("+inm+","+q+","+data+")";
		pw.println("Query is "+qry);
		int rs=stmt.executeUpdate(qry);
		pw.println("1 row inserted");
                          } 
                           }  
                            }
	           	}		

		catch(ClassNotFoundException e){}
		catch(SQLException e){}
	}
  public void bad() throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* Initialize data */
      /* Read data from a database */
      {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
          /* setup the connection */
          connection = IO.getDBConnection();
          /* prepare and execute a (hardcoded) query */
          preparedStatement = connection.prepareStatement("select name from users where id=0");
          resultSet = preparedStatement.executeQuery();
          /* POTENTIAL FLAW: Read data from a database query resultset */
          data = resultSet.getString(1);
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql);
        } finally {
          /* Close database objects */
          try {
            if (resultSet != null) {
              resultSet.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
          }

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

          try {
            if (connection != null) {
              connection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    } 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;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
        int rowCount =
            sqlStatement.executeUpdate(
                "insert into users (status) values ('updated') where name='" + data + "'");
        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 Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
Ejemplo n.º 12
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    server svr = new server();
    response.setContentType("text/html");
    HttpSession session = request.getSession(true);
    PrintWriter out = response.getWriter();
    String email = request.getParameter("email");
    String pw1 = request.getParameter("pw1");
    String pw2 = request.getParameter("pw2");
    String error = null;
    String username = session.getAttribute("username").toString();
    if (pw1.compareTo(pw2) != 0) {
      error = "Passwords do not match";
      session.setAttribute("ErrorMessage", error);
      response.sendRedirect("home.jsp");
    }
    try {
      Statement st = null;
      String strQuery = null;
      if ((pw1.length() == 0) && (email.length() == 0)) {
        session.setAttribute("ErrorMessage", "Nothing to change!");
        response.sendRedirect("home.jsp");
      } else if ((pw1.length() != 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "', `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() == 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() != 0) && (email.length() == 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "' WHERE `username`='"
                + username
                + "'";
      }
      Connection dbcon = null;
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      dbcon = DriverManager.getConnection(svr.getURL(), svr.getUN(), svr.getPW());
      st = dbcon.createStatement();
      st.executeUpdate(strQuery);
      session.setAttribute("ErrorMessage", "Details Changed");
      dbcon.close();
      session.setAttribute("ErrorMessage", "Details Changed");
      response.sendRedirect("home.jsp");
    } catch (Exception ex) {
      out.println(ex);
    }
  }
  public void bad() throws Throwable {
    String data;
    if (5 == 5) {
      data = ""; /* Initialize data */
      {
        File file = new File("C:\\data.txt");
        FileInputStream streamFileInput = null;
        InputStreamReader readerInputStream = null;
        BufferedReader readerBuffered = null;
        try {
          /* read string from file into data */
          streamFileInput = new FileInputStream(file);
          readerInputStream = new InputStreamReader(streamFileInput, "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data from a file */
          /* This will be reading the first "line" of the file, which
           * could be very long if there are little or no newlines in the file */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInput != null) {
              streamFileInput.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    } 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 (5 == 5) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
        int rowCount =
            sqlStatement.executeUpdate(
                "insert into users (status) values ('updated') where name='" + data + "'");
        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 Statement", exceptSql);
        }

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