Exemplo n.º 1
0
  /*
  	Show context number lines of string before and after target line.
  	Add HTML formatting to bold the target line.
  */
  String showScriptContextHTML(String s, int lineNo, int context) {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new StringReader(s));

    int beginLine = Math.max(1, lineNo - context);
    int endLine = lineNo + context;
    for (int i = 1; i <= lineNo + context + 1; i++) {
      if (i < beginLine) {
        try {
          br.readLine();
        } catch (IOException e) {
          throw new RuntimeException(e.toString());
        }
        continue;
      }
      if (i > endLine) break;

      String line;
      try {
        line = br.readLine();
      } catch (IOException e) {
        throw new RuntimeException(e.toString());
      }

      if (line == null) break;
      if (i == lineNo) sb.append("<font color=\"red\">" + i + ": " + line + "</font><br/>");
      else sb.append(i + ": " + line + "<br/>");
    }

    return sb.toString();
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;

    /* get environment variable ADD */
    /* POTENTIAL FLAW: Read data from an environment variable */
    data = System.getenv("ADD");

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing 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";
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Exemplo n.º 4
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
  /* good1() changes IO.staticReturnsTrue() to IO.staticReturnsFalse() */
  private void good1() throws Throwable {
    if (IO.staticReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      BufferedReader readerBuffered = null;
      InputStreamReader readerInputStream = null;

      try {
        readerInputStream = new InputStreamReader(System.in, "UTF-8");
        readerBuffered = new BufferedReader(readerInputStream);
        double num = 0;

        IO.writeString("Enter double number (1e-50): ");

        try {
          num = Double.parseDouble(readerBuffered.readLine());
        } catch (NumberFormatException exceptionNumberFormat) {
          IO.writeLine("Error parsing number");
        }

        /* FIX: check for conversion error */
        if (num > Float.MAX_VALUE || num < Float.MIN_VALUE) {
          IO.writeLine("Error, cannot safely cast this number to a float!");
          return;
        }

        IO.writeLine("" + (float) num);
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
      } finally {
        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);
        }
      }
    }
  }
 /**
  * Permet de repondre a une requete web En affichant la liste des Spectacles et representations :
  * Utiliste JQuery javascript pour la mise en forme
  *
  * @param HttpServletRequest request requete
  * @param HttpServletResponse response reponse
  * @throw IOException, ServletException
  * @return void
  */
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   // Get the session object
   HttpSession session = req.getSession(true);
   // Get the output stream
   ServletOutputStream out = res.getOutputStream();
   res.setContentType("text/html");
   out.println("<HEAD><TITLE>Reservation de tickets </TITLE></HEAD><BODY>");
   out.println("<h1> Reservations de tickets </h1>");
   out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">");
   out.println("<p align=\"Right\"><font face=\"Monotype Corsiva\"style=\"font-size: 16pt\">");
   try {
     // Open the file that is the first
     // command line parameter
     String relativeWebPath = "/WEB-INF/files/JAVASCRIPTPROG.txt";
     String absoluteDiskPath = this.getServletContext().getRealPath(relativeWebPath);
     File file = new File(absoluteDiskPath);
     FileInputStream fstream = new FileInputStream(file);
     // Get the object of DataInputStream
     DataInputStream in = new DataInputStream(fstream);
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String strLine;
     // Read File Line By Line
     while ((strLine = br.readLine()) != null) {
       // Print the content on the console
       out.println(strLine);
     }
     // Close the input stream
     in.close();
   } catch (Exception e) { // Catch exception if any
     out.println("Error: " + e.getMessage());
   }
   if (session.isNew() || session.getAttribute("session.PanierListe") == null)
     out.println("<a href=\"admin/admin.html\">Caddie (vide)</a></font><br></p>");
   else if (session.getAttribute("session.PanierListe") != null)
     if (((PanierListe) session.getAttribute("session.PanierListe")).getSize() > 0)
       out.println(
           "<a href=\"admin/admin.html\">afficher caddie("
               + ((PanierListe) session.getAttribute("session.PanierListe")).Liste.size()
               + "Representations dans le panier)"
               + "</a></font><br></p>");
   try {
     Utilisateur user = Utilitaires.Identification(this);
     out.println(Utilitaires.AffichageAchat(user));
   } catch (Exception e) {
     out.println(e.getMessage());
   }
   out.println("</BODY>");
   out.close();
 }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String dataArray[]) throws Throwable {
    String data = dataArray[2];

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Exemplo n.º 8
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 9
0
  public static void main(String args[]) throws IOException {

    // Function References
    String path =
        "http://motherlode.ucar.edu:8081/thredds/radarServer/nexrad/level3/IDD/dataset.xml";

    try {
      catURI = new URI(StringUtil2.escape(path, "/:-_."));
    } catch (URISyntaxException e) {
      System.out.println("radarServer main: URISyntaxException=" + e.getMessage());
      return;
    }

    // read the catalog
    System.out.println("radarServer main: full path=" + path);
    InputStream ios = null;
    try {

      URL url = new URL(path);
      ios = url.openStream();
      // ios = new FileInputStream(path);
      // acat = factory.readXML(ios, catURI );
      BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios));

      while (true) {
        String line = dataIS.readLine();
        if (line == null) break;
        System.out.println(line);
      }

    } catch (Throwable t) {
      System.out.println("radarServer main: Exception on catalog=" + path + " " + t.getMessage());
      return;
    } finally {
      if (ios != null) {
        try {
          ios.close();
        } catch (IOException e) {
          System.out.println("radarServer main: error closing" + path);
        }
      }
    }
    return;
  }
  public void bad() throws Throwable {
    for (int j = 0; j < 1; j++) {
      BufferedReader readerBuffered = null;
      InputStreamReader readerInputStream = null;
      try {
        /* Enter: 1e-50, result should be 0.0 (for bad case)
         *
         * Note: alternate input
         * 999999999999999999999999999999999999999999999999999999999999999
         */
        readerInputStream = new InputStreamReader(System.in, "UTF-8");
        readerBuffered = new BufferedReader(readerInputStream);
        double doubleNumber = 0;
        IO.writeString("Enter double number (1e-50): ");
        try {
          doubleNumber = Double.parseDouble(readerBuffered.readLine());
        } catch (NumberFormatException exceptionNumberFormat) {
          IO.writeLine("Error parsing number");
        }
        /* FLAW: should not cast without checking if conversion is safe */
        IO.writeLine("" + (float) doubleNumber);
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
      } finally {
        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);
        }
      }
    }
  }
  /* good1() use the GoodSinkBody in the for statement */
  private void good1() throws Throwable {
    for (int k = 0; k < 1; k++) {
      BufferedReader readerBuffered = null;
      InputStreamReader readerInputStream = null;
      try {
        readerInputStream = new InputStreamReader(System.in, "UTF-8");
        readerBuffered = new BufferedReader(readerInputStream);
        double num = 0;
        IO.writeString("Enter double number (1e-50): ");
        try {
          num = Double.parseDouble(readerBuffered.readLine());
        } catch (NumberFormatException exceptionNumberFormat) {
          IO.writeLine("Error parsing number");
        }
        /* FIX: check for conversion error */
        if (num > Float.MAX_VALUE || num < Float.MIN_VALUE) {
          IO.writeLine("Error, cannot safely cast this number to a float!");
          return;
        }
        IO.writeLine("" + (float) num);
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
      } finally {
        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);
        }
      }
    }
  }
Exemplo n.º 12
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int i, j;
    String amount = req.getParameter("amount");
    String from = req.getParameter("from");
    String to = req.getParameter("to");
    String ch = req.getParameter("choice");
    String answer, answer1, answer2, answer3;

    if ("INFO".equals(ch)) {
      Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect");
      res.sendRedirect(newurl.getUrl());
    } else {
      out.println("<html>");
      out.println("<title>Currency Converter</title>");
      String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to;
      URL convert = new URL(addr);
      BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream()));
      answer = in.readLine();
      answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7");
      from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7");
      to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7");
      amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7");

      in.close();
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(0, i);
      out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>");
      out.println("</body>");
      out.println("</html>");
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String data;

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

    BufferedReader bufread2 = null;
    InputStreamReader inread2 = null;

    data = ""; /* init data */

    try {
      inread2 = new InputStreamReader(System.in);
      bufread2 = new BufferedReader(inread2);

      /* FIX: read key from console */
      data = bufread2.readLine();
    } catch (IOException e) {
      log_gsrc.warning("Error reading from console");
    } finally {
      try {
        if (bufread2 != null) {
          bufread2.close();
        }
      } catch (IOException e) {
        log_gsrc.warning("Error closing bufread2");
      } finally {
        try {
          if (inread2 != null) {
            inread2.close();
          }
        } catch (IOException e) {
          log_gsrc.warning("Error closing inread2");
        }
      }
    }

    (new CWE321_Hard_Coded_Cryptographic_Key__basic_51b()).goodG2B_sink(data);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    /*
     * // Create path components to save the file final String path =
     * request.getParameter("destination"); final Part filePart =
     * request.getPart("file"); final String fileName =
     * getFileName(filePart);
     */

    String path = request.getContextPath();
    String csvFileToRead = request.getRealPath("/") + "mail.csv";
    BufferedReader br = null;
    String line = "";
    String splitBy = ",";

    JSONArray jArrayMails = new JSONArray();
    try {
      br = new BufferedReader(new FileReader(csvFileToRead));
      while ((line = br.readLine()) != null) {
        jArrayMails.add(line);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();
    jobj.put("studentEmailsArray", jArrayMails);
    out.print(jobj);
  }
Exemplo n.º 15
0
  // *****************************************************
  // Process the initial request from Proshop_main
  // *****************************************************
  //
  @SuppressWarnings("deprecation")
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    //
    //  Prevent caching so sessions are not mangled
    //
    resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1
    resp.setDateHeader("Expires", 0); // prevents caching at the proxy server

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

    HttpSession session = SystemUtils.verifyPro(req, out); // check for intruder

    if (session == null) {

      return;
    }

    String club = (String) session.getAttribute("club"); // get club name
    String templott = (String) session.getAttribute("lottery"); // get lottery support indicator
    int lottery = Integer.parseInt(templott);

    //
    //  Call is to display the new features page.
    //
    //  Display a page to provide a link to the new feature page
    //
    out.println("<html><head>");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");
    out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">");
    out.println("<title> \"ForeTees Proshop Announcement Page\"</title>");
    //   out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/web utilities/foretees.css\"
    // type=\"text/css\"></link>");
    out.println(
        "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>");
    out.println("</head>");
    out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\">");

    SystemUtils.getProshopSubMenu(req, out, lottery);

    File f;
    FileReader fr;
    BufferedReader br;
    String tmp = "";
    String path = "";

    try {
      path = req.getRealPath("");
      tmp = "/proshop_features.htm"; // "/" +rev+
      f = new File(path + tmp);
      fr = new FileReader(f);
      br = new BufferedReader(fr);
      if (!f.isFile()) {
        // do nothing
      }
    } catch (FileNotFoundException e) {
      out.println("<br><br><p align=center>Missing New Features Page.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    } catch (SecurityException se) {
      out.println("<br><br><p align=center>Access Denied.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    }

    while ((tmp = br.readLine()) != null) out.println(tmp);

    br.close();

    out.println("</BODY></HTML>");
    out.close();
  } // end of doGet
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    switch (6) {
      case 6:
        {
          data = "pass";
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        {
          java.util.logging.Logger log_good_source =
              java.util.logging.Logger.getLogger("local-logger");
          BufferedReader bufread2 = null;
          InputStreamReader inread2 = null;
          Properties prop = new Properties();
          IO.writeLine("Enter the password: "******"";
          try {
            inread2 = new InputStreamReader(System.in);
            bufread2 = new BufferedReader(inread2);
            /* FIX: password is read from stdin */
            data = bufread2.readLine();
          } catch (Exception e) {
            log_good_source.warning("Exception in try");
          } finally {
            try {
              if (bufread2 != null) {
                bufread2.close();
              }
            } catch (IOException e) {
              log_good_source.warning("Error closing bufread2");
            } finally {
              try {
                if (inread2 != null) {
                  inread2.close();
                }
              } catch (IOException e) {
                log_good_source.warning("Error closing inread2");
              }
            }
          }
        }
        break;
    }

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

    Connection conn2 = null;
    PreparedStatement st = null;
    ResultSet rs2 = null;
    String pw = data;
    try {
      /* POTENTIAL FLAW: use of hard-coded password */
      conn2 = DriverManager.getConnection("data-url", "root", pw);
      st = conn2.prepareStatement("select * from test_table");
      rs2 = st.executeQuery();
    } catch (SQLException e) {
      log2.warning("Error with database connection");
    } finally {
      try {
        if (rs2 != null) {
          rs2.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing rs2");
      } finally {
        try {
          if (st != null) {
            st.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing st");
        } finally {
          try {
            if (conn2 != null) {
              conn2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn2");
          }
        }
      }
    }
  }
  /*
   * Procesamiento de peticiones GET y POST
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  public final void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Comprobar si es un GET
    if (request.getMethod().equalsIgnoreCase("GET")) {
      return;
    }

    // Se trata de un POST

    // La respuesta es JSON
    response.setContentType("application/json; charset=UTF-8");

    // Crear los filtros definidos para todos los servicios
    es.tid.frawa.service.servlet.Filter[] filters = new es.tid.frawa.service.servlet.Filter[0];

    PrintWriter output = null;

    StringBuffer input = null;

    String action = "";

    try {
      // Crea una sesión si no existe (esta opción está marcada en el modelo de servicios)
      request.getSession(true);

      // Invocar el método startService() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].startService(request, response);
      }

      // Invocar el método frawaService() de la clase derivada (si está implementado)
      if (!frawaService(request, response)) {
        // Ha retornado false, por tanto abortamos el procesamiento del servicio
        return;
      }

      // Mensaje por defecto para los filtros que no necesitan el texto JSON
      StringBuffer soapStr = new StringBuffer("");

      // Leer el mensaje JSON

      if (request.getParameter("JSONAction") != null
          && request.getParameter("JSONAction").length() > 0) {
        action = request.getParameter("JSONAction");
        String tmp = request.getParameter("JSON");
        if (tmp == null || tmp.length() == 0) {
          throw new Exception(
              getClass().getName()
                  + ".service() JSONAction viene en la URL pero no viene el parámetro JSON con los datos");
        }
        input = new StringBuffer(tmp);
      } else {
        action = request.getHeader("JSONAction");
        if (action == null || action.length() == 0) {
          throw new Exception(
              getClass().getName() + ".service() La cabecera HTTP JSONAction no esta definida");
        }
        // new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName()+".service()
        // Leyendo mensaje JSON");
        BufferedReader input_r = new BufferedReader(request.getReader());
        input = new StringBuffer();
        String line = input_r.readLine();
        while (line != null) {
          input.append(line);
          line = input_r.readLine();
        }
      }

      // Invocar el método beforeParse() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].beforeParse(request, response, input.toString());
      }

      //
      // Invocar al servicio adecuado en función del header JSONAction
      //

      if (action.equals("http://www.qualipso.org/advdoc/ws/storage/CreateFolder")) {

        // SERVICIO: CreateFolder

        // Parámetro de entrada al servicio
        CreateFolder_req inbean = new CreateFolder_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        CreateFolder_resp outbean = new CreateFolder_resp();

        // Crear un objeto que implementa la operación
        CreateFolderService serviceImplementation = new CreateFolderService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: CreateFolder]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetFiles")) {

        // SERVICIO: GetFiles

        // Parámetro de entrada al servicio
        GetFiles_req inbean = new GetFiles_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        GetFiles_resp outbean = new GetFiles_resp();

        // Crear un objeto que implementa la operación
        GetFilesService serviceImplementation = new GetFilesService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: GetFiles]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetSubFolders")) {

        // SERVICIO: GetSubFolders

        // Parámetro de entrada al servicio
        GetSubFolders_req inbean = new GetSubFolders_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        GetSubFolders_resp outbean = new GetSubFolders_resp();

        // Crear un objeto que implementa la operación
        GetSubFoldersService serviceImplementation = new GetSubFoldersService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: GetSubFolders]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadBinaryFile")) {

        // SERVICIO: LoadBinaryFile

        // Parámetro de entrada al servicio
        LoadBinaryFile_req inbean = new LoadBinaryFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        LoadBinaryFile_resp outbean = new LoadBinaryFile_resp();

        // Crear un objeto que implementa la operación
        LoadBinaryFileService serviceImplementation = new LoadBinaryFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: LoadBinaryFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadFile")) {

        // SERVICIO: LoadFile

        // Parámetro de entrada al servicio
        LoadFile_req inbean = new LoadFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        LoadFile_resp outbean = new LoadFile_resp();

        // Crear un objeto que implementa la operación
        LoadFileService serviceImplementation = new LoadFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: LoadFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFile")) {

        // SERVICIO: RemoveFile

        // Parámetro de entrada al servicio
        RemoveFile_req inbean = new RemoveFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        RemoveFile_resp outbean = new RemoveFile_resp();

        // Crear un objeto que implementa la operación
        RemoveFileService serviceImplementation = new RemoveFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: RemoveFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFolder")) {

        // SERVICIO: RemoveFolder

        // Parámetro de entrada al servicio
        RemoveFolder_req inbean = new RemoveFolder_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        RemoveFolder_resp outbean = new RemoveFolder_resp();

        // Crear un objeto que implementa la operación
        RemoveFolderService serviceImplementation = new RemoveFolderService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: RemoveFolder]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreBinaryFile")) {

        // SERVICIO: StoreBinaryFile

        // Parámetro de entrada al servicio
        StoreBinaryFile_req inbean = new StoreBinaryFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        StoreBinaryFile_resp outbean = new StoreBinaryFile_resp();

        // Crear un objeto que implementa la operación
        StoreBinaryFileService serviceImplementation = new StoreBinaryFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: StoreBinaryFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreFile")) {

        // SERVICIO: StoreFile

        // Parámetro de entrada al servicio
        StoreFile_req inbean = new StoreFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        StoreFile_resp outbean = new StoreFile_resp();

        // Crear un objeto que implementa la operación
        StoreFileService serviceImplementation = new StoreFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: StoreFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestLoopback")) {

        // SERVICIO: TestLoopback

        // Parámetro de entrada al servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestLoopback inbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestLoopback outbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback();

        // Crear un objeto que implementa la operación
        TestLoopbackService serviceImplementation = new TestLoopbackService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: TestLoopback]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestParser")) {

        // SERVICIO: TestParser

        // Parámetro de entrada al servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestParser inbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestParser();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestParser outbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestParser();

        // Crear un objeto que implementa la operación
        TestParserService serviceImplementation = new TestParserService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: TestParser]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else {

        throw new Exception(getClass().getName() + ".service() Operación " + action + " no válida");
      }

    } catch (ServletException e) {

      // Ha ocurrido un error en los filtros

      // Traza
      // new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);
      new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);

      // Enviar <Fault> al cliente
      if (output == null) {
        output = response.getWriter();
      }
      TdiServiceException se = new TdiServiceException(-1, "Filter exception", e.getMessage());
      sendError(output, se);

    } catch (Throwable t) {

      // Invocar el método onException() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].onException(request, response, t, "QualiPSoStorage", action);
      }

      // Traza
      // new es.tid.frawa.common.TdiFrawaTraceListener().trace(t);
      new es.tid.frawa.common.TdiFrawaTraceListener().trace(t);

      // Elevar una ServletException
      throw new ServletException(
          getClass().getName()
              + ".service() Server Exception: "
              + t.getClass().getName()
              + " -> "
              + t.getMessage());
      // if (output == null) {
      //	output = response.getWriter();
      // }
      // TdiServiceException se = new TdiServiceException(-2,t.getClass().getName(),t.getMessage());
      // sendError(output,se);

    } finally {

      // Invocar el método onFinally() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].onFinally(request, response, "QualiPSoStorage", action);
      }
    }
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
Exemplo n.º 19
0
  public void init() throws ServletException {

    final String CONFIG_PATH = getServletContext().getRealPath("/") + "config.ini";
    final String APPLICATION_NAME = getServletContext().getServletContextName();

    BasicConfigurator.configure();

    FileInputStream config_file = null;
    File config = new File(CONFIG_PATH);

    if (config.canRead()) {
      log.debug("Parsing " + CONFIG_PATH);
      try {
        config_file = new FileInputStream(CONFIG_PATH);
      } catch (java.io.FileNotFoundException e) {
        throw new ServletException(e);
      }

      Properties config_prop = new Properties();

      try {
        config_prop.load(config_file);
      } catch (java.io.IOException e) {
        throw new ServletException(e);
      }
      this.config = config_prop;

      log.debug("Parsing finished");
    } else {
      log.fatal("Error, cannot read " + CONFIG_PATH);
    }

    log.debug("maximumRecords : " + this.config.getProperty("default_maximumRecords"));
    log.debug("srw_header_file: " + this.config.getProperty("srw_header_file"));
    log.debug("srw_diag: " + this.config.getProperty("srw_diag_file"));
    // log.debug("server_list:     " + this.config.getProperty("server_list"));

    try {
      FileReader fis =
          new FileReader(
              getServletContext().getRealPath("/") + this.config.getProperty("srw_header_file"));
      BufferedReader in1 = new BufferedReader(fis);
      fis =
          new FileReader(
              getServletContext().getRealPath("/") + this.config.getProperty("srw_footer_file"));
      BufferedReader in2 = new BufferedReader(fis);
      fis =
          new FileReader(
              getServletContext().getRealPath("/") + this.config.getProperty("srw_diag_file"));
      BufferedReader in3 = new BufferedReader(fis);
      try {
        String line = null;

        while ((line = in1.readLine()) != null) {
          this.SRW_HEADER = this.SRW_HEADER + line;
        }
        while ((line = in2.readLine()) != null) {
          this.SRW_FOOTER = this.SRW_FOOTER + line;
        }
        while ((line = in3.readLine()) != null) {
          this.SRW_DIAG = this.SRW_DIAG + line;
        }
      } finally {
        in1.close();
        in2.close();
        in3.close();
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 20
0
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter webPageOutput = null;
   try {
     webPageOutput = response.getWriter();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "getWriter error : " + error, false, context);
   }
   HttpSession session = request.getSession();
   session.setAttribute("redirect", request.getRequestURL() + "?" + request.getQueryString());
   Connection database = null;
   try {
     database = pool.getConnection(servletName);
   } catch (SQLException error) {
     Routines.writeToLog(servletName, "Unable to connect to database : " + error, false, context);
   }
   if (Routines.loginCheck(true, request, response, database, context)) {
     return;
   }
   String server = context.getInitParameter("server");
   boolean liveSever = false;
   if (server == null) {
     server = "";
   }
   if (server.equals("live")) {
     response.setHeader("Refresh", "60");
   }
   Routines.WriteHTMLHead(
       "View System Log", // title
       false, // showMenu
       13, // menuHighLight
       false, // seasonsMenu
       false, // weeksMenu
       false, // scores
       false, // standings
       false, // gameCenter
       false, // schedules
       false, // previews
       false, // teamCenter
       false, // draft
       database, // database
       request, // request
       response, // response
       webPageOutput, // webPageOutput
       context); // context
   webPageOutput.println("<CENTER>");
   webPageOutput.println(
       "<IMG SRC=\"../Images/Admin.gif\"" + " WIDTH='125' HEIGHT='115' ALT='Admin'>");
   webPageOutput.println("</CENTER>");
   pool.returnConnection(database);
   webPageOutput.println(Routines.spaceLines(1));
   Routines.tableStart(false, webPageOutput);
   Routines.tableHeader("System Log", 0, webPageOutput);
   Routines.tableDataStart(true, false, false, true, true, 0, 0, "scoresrow", webPageOutput);
   boolean firstLine = true;
   int numOfLines = 0;
   try {
     String file = context.getRealPath("/");
     FileReader logFile = new FileReader(file + "/Data/log.txt");
     BufferedReader logFileBuffer = new BufferedReader(logFile);
     boolean endOfFile = false;
     while (!endOfFile) {
       String logFileText = logFileBuffer.readLine();
       if (logFileText == null) {
         endOfFile = true;
       } else {
         if (firstLine) {
           firstLine = false;
         } else {
           webPageOutput.println(Routines.spaceLines(1));
         }
         numOfLines++;
         webPageOutput.println(logFileText);
       }
     }
     logFileBuffer.close();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "Problem with log file : " + error, false, context);
   }
   Routines.tableDataEnd(false, true, true, webPageOutput);
   Routines.tableEnd(webPageOutput);
   if (numOfLines < 20) {
     webPageOutput.println(Routines.spaceLines(20 - numOfLines));
   }
   Routines.WriteHTMLTail(request, response, webPageOutput);
 }
Exemplo n.º 21
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    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 {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext =
          _jspxFactory.getPageContext(this, request, response, "error.jsp", true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n");
      org.jivesoftware.admin.AdminPageBean pageinfo = null;
      synchronized (request) {
        pageinfo =
            (org.jivesoftware.admin.AdminPageBean)
                _jspx_page_context.getAttribute("pageinfo", PageContext.REQUEST_SCOPE);
        if (pageinfo == null) {
          pageinfo = new org.jivesoftware.admin.AdminPageBean();
          _jspx_page_context.setAttribute("pageinfo", pageinfo, PageContext.REQUEST_SCOPE);
        }
      }
      out.write('\n');
      out.write('\n');
      out.write('\n');
      out.write('\n');

      // Get parameters
      String log = ParamUtils.getParameter(request, "log");
      String numLinesParam = ParamUtils.getParameter(request, "lines");
      int numLines = ParamUtils.getIntParameter(request, "lines", 50);
      String mode = ParamUtils.getParameter(request, "mode");

      // Only allow requests for valid log file names.
      if (!("debug".equals(log)
          || "warn".equals(log)
          || "info".equals(log)
          || "error".equals(log))) {
        log = null;
      }

      // Set defaults
      if (log == null) {
        log = "error";
      }
      if (mode == null) {
        mode = "asc";
      }
      if (numLinesParam == null) {
        numLinesParam = "50";
      }

      // Other vars
      File logDir = new File(Log.getLogDirectory());
      String filename = log + ".log";
      File logFile = new File(logDir, filename);

      String lines[] = new String[0];
      int start = 0;
      try {
        BufferedReader in =
            new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "UTF-8"));
        String line;
        int totalNumLines = 0;
        while ((line = in.readLine()) != null) {
          totalNumLines++;
        }
        in.close();
        // adjust the 'numLines' var to match totalNumLines if 'all' was passed in:
        if ("All".equals(numLinesParam)) {
          numLines = totalNumLines;
        }
        lines = new String[numLines];
        in = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "UTF-8"));
        // skip lines
        start = totalNumLines - numLines;
        if (start < 0) {
          start = 0;
        }
        for (int i = 0; i < start; i++) {
          in.readLine();
        }
        int i = 0;
        if ("asc".equals(mode)) {
          while ((line = in.readLine()) != null && i < numLines) {
            line = StringUtils.escapeHTMLTags(line);
            line = parseDate(line);
            line = hilite(line);
            lines[i] = line;
            i++;
          }
        } else {
          int end = lines.length - 1;
          while ((line = in.readLine()) != null && i < numLines) {
            line = StringUtils.escapeHTMLTags(line);
            line = parseDate(line);
            line = hilite(line);
            lines[end - i] = line;
            i++;
          }
        }
        numLines = start + i;
      } catch (FileNotFoundException ex) {
        Log.info("Could not open (log)file.", ex);
      }

      out.write("\n\n<html>\n<head>\n    <title>");
      out.print(log);
      out.write(
          "</title>\n    <meta name=\"decorator\" content=\"none\"/>\n    <style type=\"text/css\">\n    .log TABLE {\n        border : 1px #ccc solid;\n    }\n    .log TH {\n        font-family : verdana, arial, sans-serif;\n        font-weight : bold;\n        font-size : 8pt;\n    }\n    .log TR TH {\n        background-color : #ddd;\n        border-bottom : 1px #ccc solid;\n        padding-left : 2px;\n        padding-right : 2px;\n        text-align : left;\n    }\n    .log .head-num {\n        border-right : 1px #ccc solid;\n    }\n    .log TD {\n        font-family : courier new,monospace;\n        font-size : 9pt;\n        background-color : #ffe;\n    }\n    .log .num {\n        width : 1%;\n        background-color : #eee !important;\n        border-right : 1px #ccc solid;\n        padding-left : 2px;\n        padding-right : 2px;\n    }\n    .log .line {\n        padding-left : 10px;\n    }\n    .hilite {\n        color : #900;\n    }\n    .hilite-marker {\n        background-color : #ff0;\n        color : #000;\n        font-weight : bold;\n    }\n    </style>\n");
      out.write(
          "</head>\n<body>\n\n<div class=\"log\">\n<table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n<tr>\n    <th class=\"head-num\">");
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(
          "</th>\n    <th>&nbsp;</th>\n</tr>\n<tr>\n    <td width=\"1%\" nowrap class=\"num\">\n        ");
      if ("asc".equals(mode)) {
        out.write("\n            ");
        for (int j = start + 1; j <= numLines; j++) {
          out.write("\n                ");
          out.print(j);
          out.write("<br>\n            ");
        }
        out.write("\n        ");
      } else {
        out.write("\n            ");
        for (int j = numLines; j >= start + 1; j--) {
          out.write("\n                ");
          out.print(j);
          out.write("<br>\n            ");
        }
        out.write("\n        ");
      }
      out.write("\n    </td>\n    <td width=\"99%\" class=\"line\">\n        ");
      for (String line1 : lines) {
        if (line1 != null) {

          out.write("\n        <nobr>");
          out.print(line1);
          out.write("\n        </nobr>\n        <br>\n\n        ");
        }
      }

      out.write("\n    </td>\n</tr>\n</table>\n</div>\n\n</body>\n</html>");
    } 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);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateReturnsTrue()) {
      /* 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;
    }

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* uses badsource and badsink - see how tools report flaws that don't always occur */
  public void bad() throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      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 {

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

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink by changing the "if" so that
   * both branches use the GoodSource */
  private void goodG2B() throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {

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

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Exemplo n.º 25
0
  /**
   * Process an HTML get or post.
   *
   * @exception ServletException From inherited class.
   * @exception IOException From inherited class.
   */
  public void scanOutXML(
      PrintWriter out,
      String strDirectory,
      String strFilename,
      String[] strPlus,
      String[] strMinus,
      boolean bExcludeParams,
      boolean bAnalyzeParams)
      throws IOException {
    File dir = new File(strDirectory + '/' + strFilename);
    if (dir.isDirectory()) return;

    try {
      FileReader is = new FileReader(strDirectory + '/' + strFilename);
      BufferedReader r = new BufferedReader(is);
      String string = null;
      Hashtable ht = new Hashtable();
      Set setstrExtensions = new HashSet();
      int iCount = 0;
      int iBytes = 0;
      while ((string = r.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(string, " \"", false);
        Data data = new Data();
        int iTokenCount = 0;
        while (st.hasMoreTokens()) {
          iTokenCount++;
          string = st.nextToken();
          if (iTokenCount == IP) data.m_IP = string;
          if (iTokenCount == URL) {
            if (bExcludeParams)
              if (string.indexOf('?') != -1) string = string.substring(0, string.indexOf('?'));
            if (bAnalyzeParams)
              if (string.indexOf('?') != -1) string = string.substring(string.indexOf('?') + 1);
            data.m_URL = string;
          }
          if (iTokenCount == PROTOCOL)
            if (!string.startsWith("HTTP")) {
              data.m_URL += " " + string;
              iTokenCount--;
            }
          if (iTokenCount == BYTES) data.m_iBytes = Integer.parseInt(string);
        }
        if (!this.filterURL(data.m_URL, strPlus, strMinus, setstrExtensions)) continue;
        iCount++;
        iBytes += data.m_iBytes;
        if (ht.get(data.m_URL) == null) ht.put(data.m_URL, data);
        else {
          int iThisBytes = data.m_iBytes;
          data = (Data) ht.get(data.m_URL);
          data.m_iCount++;
          data.m_iBytes += iThisBytes;
        }
      }
      Comparator comparator = new Test();
      TreeMap tm = new TreeMap(comparator);
      Iterator iterator = ht.values().iterator();
      while (iterator.hasNext()) {
        Data data = (Data) iterator.next();
        tm.put(new Integer(data.m_iCount), data);
      }
      out.println("<file>");
      this.printXML(out, "directory", strDirectory);
      this.printXML(out, "name", strFilename);
      iterator = tm.values().iterator();
      while (iterator.hasNext()) {
        out.println("<data>");
        Data data = (Data) iterator.next();
        this.printXML(out, "url", data.m_URL);
        this.printXML(out, "count", Integer.toString(data.m_iCount));
        out.println("</data>");
      }
      this.printXML(out, "hits", Integer.toString(iCount));
      this.printXML(out, "bytes", Integer.toString(iBytes));
      this.printXML(out, "unique", Integer.toString(tm.size()));

      iterator = setstrExtensions.iterator();
      out.println("<extensions>");
      while (iterator.hasNext()) {
        this.printXML(out, "extension", (String) iterator.next());
      }
      out.println("</extensions>");

      out.println("</file>");
    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */
  private void goodG2B1() throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_FALSE) {
      /* 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";
    }

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

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

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