/**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Beispiel #2
0
 @Override
 public void parseRequestParameters(
     final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files)
     throws RequestParseException {
   try {
     if (isMultiPart()) {
       parseQueryString(params, req.getQueryString());
       @SuppressWarnings("unchecked")
       final List<FileItem> items = new ServletFileUpload().parseRequest(req);
       for (final FileItem item : items) {
         if (item.isFormField()) params.put(item.getFieldName(), item.getString());
         else files.put(item.getFieldName(), new FileItemWrapper(item));
       }
     } else {
       final Enumeration<String> en = req.getParameterNames();
       while (en.hasMoreElements()) {
         final String nm = en.nextElement();
         final String val = req.getParameter(nm);
         params.put(nm, val);
       }
     }
   } catch (final FileUploadException ex) {
     throw new RequestParseException("FileUploadException", ex);
   } catch (final Throwable ex) {
     throw new RequestParseException(ex.getMessage(), ex);
   }
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    System.out.println("queryString: " + request.getQueryString());
    out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL"));
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println(
        "MyProtectedServlet.processRequest "
            + request.getRequestURI()
            + " "
            + request.getQueryString());

    String myUrl = request.getRequestURI();
    if (myUrl.indexOf("login") >= 0) {
      login(request, response);
      return;
    } else if (myUrl.indexOf("redirect") >= 0) {
      redirect(request, response);
      return;
    }

    if (request.getRemoteUser() == null) {
      String callUrl = request.getRequestURI();
      String query = request.getQueryString();
      if (query != null) {
        callUrl = callUrl + "?" + query;
      }
      String nextEncUrl = java.net.URLEncoder.encode(callUrl);
      String redirectUrl =
          request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl;
      response.sendRedirect(redirectUrl);
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet MyProtectedServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");

      out.close();
    }
  }
  /**
   * Forward this request to the CatalogServices servlet ("/catalog.html").
   *
   * @param req request
   * @param res response
   * @throws IOException on IO error
   * @throws ServletException other error
   */
  public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    String reqs = "catalog=" + getReletiveURL(req);
    String query = req.getQueryString();
    if (query != null) reqs = reqs + "&" + query;
    log.info("forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"");

    // dispatch to CatalogHtml servlet
    RequestForwardUtils.forwardRequestRelativeToCurrentContext("/catalog.html?" + reqs, req, res);
  }
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
  public URL getUrl(HttpServletRequest req) throws IOException {
    String servletPath = req.getServletPath();

    String selectedServerFullPath = getServerAddress(servletPath);
    String queryString = req.getQueryString();
    String newUrl = "";
    HttpSession session = req.getSession(false);

    newUrl = selectedServerFullPath + servletPath;

    if (req.getRequestedSessionId() != null)
      newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId();

    if (queryString != null) newUrl = newUrl + "?" + queryString;

    // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId();

    return new URL(newUrl);
  }
Beispiel #8
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

    req = rq;
    res = rs;
    params = new HTTPParams(this);

    method = rq.getMethod();

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log('[' + method + "] " + uri, null);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);
    segments = decode(toSegments(req.getPathInfo()));

    // adopt servlet-specific credentials or use global ones
    final GlobalOptions mprop = context().globalopts;
    user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER);
    pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD);

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Beispiel #9
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);
 }
Beispiel #10
0
  /**
   * Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to
   * the given directory, and limiting the upload size to the specified length. If the content is
   * too large, an IOException is thrown. This constructor actually parses the
   * <tt>multipart/form-data</tt> and throws an IOException if there's any problem reading or
   * parsing the request.
   *
   * <p>To avoid file collisions, this constructor takes an implementation of the FileRenamePolicy
   * interface to allow a pluggable rename policy.
   *
   * @param request the servlet request.
   * @param saveDirectory the directory in which to save any uploaded files.
   * @param maxPostSize the maximum size of the POST content.
   * @param encoding the encoding of the response, such as ISO-8859-1
   * @param policy a pluggable file rename policy
   * @exception IOException if the uploaded content is larger than <tt>maxPostSize</tt> or there's a
   *     problem reading or parsing the request.
   */
  public MultipartRequest(
      HttpServletRequest request,
      String saveDirectory,
      int maxPostSize,
      String encoding,
      FileRenamePolicy policy)
      throws IOException {
    // Sanity check values
    if (request == null) throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null) throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }

    // Save the dir
    File dir = new File(saveDirectory);

    // Check saveDirectory is truly a directory
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory: " + saveDirectory);

    // Check saveDirectory is writable
    if (!dir.canWrite()) throw new IllegalArgumentException("Not writable: " + saveDirectory);

    // Parse the incoming multipart, storing files in the dir provided,
    // and populate the meta objects which describe what we found
    MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding);

    // Some people like to fetch query string parameters from
    // MultipartRequest, so here we make that possible.  Thanks to
    // Ben Johnson, [email protected], for the idea.
    if (request.getQueryString() != null) {
      // Let HttpUtils create a name->String[] structure
      Hashtable queryParameters = HttpUtils.parseQueryString(request.getQueryString());
      // For our own use, name it a name->Vector structure
      Enumeration queryParameterNames = queryParameters.keys();
      while (queryParameterNames.hasMoreElements()) {
        Object paramName = queryParameterNames.nextElement();
        String[] values = (String[]) queryParameters.get(paramName);
        Vector newValues = new Vector();
        for (int i = 0; i < values.length; i++) {
          newValues.add(values[i]);
        }
        parameters.put(paramName, newValues);
      }
    }

    Part part;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
      if (name == null) {
        throw new IOException("Malformed input: parameter name missing (known Opera 7 bug)");
      }
      if (part.isParam()) {
        // It's a parameter part, add it to the vector of values
        ParamPart paramPart = (ParamPart) part;
        String value = paramPart.getStringValue();
        Vector existingValues = (Vector) parameters.get(name);
        if (existingValues == null) {
          existingValues = new Vector();
          parameters.put(name, existingValues);
        }
        existingValues.addElement(value);
      } else if (part.isFile()) {
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          filePart.setRenamePolicy(policy); // null policy is OK
          // The part actually contained a file
          filePart.writeTo(dir);
          files.put(
              name,
              new UploadedFile(
                  dir.toString(), filePart.getFileName(), fileName, filePart.getContentType()));
        } else {
          // The field did not contain a file
          files.put(name, new UploadedFile(null, null, null, null));
        }
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

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

    /* parse the query string for value of 'id' */
    String id_str = null;
    StringTokenizer st = new StringTokenizer(request.getQueryString(), "&");
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      int i = token.indexOf("=");
      if ((i > 0) && (i < (token.length() - 1)) && (token.substring(0, i).equals("id"))) {
        id_str = token.substring(i + 1);
        break;
      }
    }

    if (id_str != null) {
      Connection conn = null;
      PreparedStatement statement = null;
      ResultSet rs = null;
      try {
        int id = Integer.parseInt(id_str);
        conn = IO.getDBConnection();
        statement = conn.prepareStatement("select * from pages where id=?");
        /* FLAW: no check to see whether the user has privileges to view the data */
        statement.setInt(1, id);
        rs = statement.executeQuery();
        data = rs.toString();
      } catch (SQLException se) {
        log_bad.warning("Error");
      } finally {
        /* clean up database objects */
        try {
          if (rs != null) {
            rs.close();
          }
        } catch (SQLException se) {
          log_bad.warning("Error closing rs");
        } finally {
          try {
            if (statement != null) {
              statement.close();
            }
          } catch (SQLException se) {
            log_bad.warning("Error closing statement");
          } finally {
            try {
              if (conn != null) {
                conn.close();
              }
            } catch (SQLException se) {
              log_bad.warning("Error closing conn");
            }
          }
        }
      }
    }

    Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
    Object instance = c.newInstance();

    IO.writeLine(instance.toString());
  }
Beispiel #12
0
  // get pathInfo and parmameters from servlet call
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    PrintWriter pw = null;
    try {
      long startms = System.currentTimeMillis();

      if (cat == null || rm.nexradList == null) { // something major wrong
        res.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            "radarServer Radar Station/Catalog initialization problem");
        return;
      }
      // setup
      String pathInfo = req.getPathInfo();
      if (pathInfo == null) pathInfo = "";
      RadarType radarType = RadarType.nexrad; // default
      if (pathInfo.indexOf('/', 1) > 1) {
        String rt = pathInfo.substring(1, pathInfo.indexOf('/', 1));
        radarType = RadarType.valueOf(rt);
      }
      // default is xml, assume errors will be recorded by logger from this point
      if (!pathInfo.endsWith("html")) {
        pw = res.getWriter();
        res.setContentType("text/xml; charset=iso-8859-1"); // default
      }
      // radar  query
      if (req.getQueryString() != null) {
        // log.debug("RadarServer query ="+ req.getQueryString() );
        if (log.isDebugEnabled())
          log.debug("<documentation>\n" + req.getQueryString() + "</documentation>\n");
        rm.radarQuery(radarType, req, res, pw);
        if (log.isDebugEnabled())
          log.debug("after doGet " + (System.currentTimeMillis() - startms));
        pw.flush();
        return;
      }
      // return radarCollections catalog   xml or html
      if (pathInfo.startsWith("/catalog.xml") || pathInfo.startsWith("/dataset.xml")) {
        InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation
        String catAsString = factory.writeXML(cat);
        pw.println(catAsString);
        res.setStatus(HttpServletResponse.SC_OK);
        pw.flush();
        return;
      } else if (pathInfo.startsWith("/catalog.html") || pathInfo.startsWith("/dataset.html")) {
        try {
          int i =
              HtmlWriter.getInstance().writeCatalog(req, res, cat, true); // show catalog as HTML
        } catch (Exception e) {
          log.error("Radar HtmlWriter failed ", e);
          res.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "radarServer HtmlWriter error " + pathInfo);
          return;
        }
        return;
      }
      // level2 and level3 catalog/dataset
      if (pathInfo.contains("level2/catalog.")
          || pathInfo.contains("level3/catalog.")
          || pathInfo.contains("level2/dataset.")
          || pathInfo.contains("level3/dataset.")) {
        level2level3catalog(radarType, pathInfo, pw, req, res);
        return;
      }
      // return stations of dataset
      if (pathInfo.endsWith("stations.xml")) {
        pathInfo = pathInfo.replace("/stations.xml", "");
        Element rootElem = new Element("stationsList");
        Document doc = new Document(rootElem);
        doc = rm.stationsXML(radarType, doc, rootElem, pathInfo.substring(1));
        XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
        pw.println(fmt.outputString(doc));
        pw.flush();
        return;
      }
      // return specific dataset information, ie IDD
      if (pathInfo.endsWith("dataset.xml") || pathInfo.endsWith("catalog.xml")) {
        datasetInfoXml(radarType, pathInfo, pw);
        return;
      }
      // needs work nobody using it now
      // return Dataset information in html form format
      if (pathInfo.endsWith("dataset.html") || pathInfo.endsWith("catalog.html")) {
        datasetInfoHtml(radarType, pathInfo, pw, res);
        return;
      }
      // mal formed request with no exceptions
      res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (FileNotFoundException e) {
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (Throwable e) {
      log.error("RadarServer.doGet failed", e);
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  } // end doGet
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    //		权限判断
    StringBuffer sb = new StringBuffer();
    String actionType = null;
    String queryString = null;
    String userid = null;
    String isCanAccess = "1";
    HttpServletRequest hrequest = (HttpServletRequest) request;
    String strContext = hrequest.getContextPath();

    if (request instanceof HttpServletRequest) {

      // 获取用户信息
      userid = (String) hrequest.getSession().getAttribute("AuthorizedUserID");

      strContext = hrequest.getContextPath();
      queryString = hrequest.getQueryString(); // 整个参数串
      actionType = hrequest.getParameter("actionType"); // 一般操作
      if (actionType == null) {
        actionType = hrequest.getParameter("formSN"); // 针对查询的操作
        if (actionType != null) {
          actionType = "formSN=" + actionType;
        }
      } else {
        actionType = "actionType=" + actionType;
      }
    }

    if (actionType != null) { // 如果参数不为空,则判断权限,通过存储过程判断
      DBConnectionManager dbManager = new DBConnectionManager();
      CallableStatement cstmt = null;
      Connection conn = null;
      try {
        conn = dbManager.getConnection();
        String query = "{call pkg_security.userAccessFunction(?,?,?,?)}";
        cstmt = conn.prepareCall(query);
        cstmt.registerOutParameter(1, OracleTypes.VARCHAR);
        cstmt.setString(2, userid);
        cstmt.setString(3, actionType == null ? null : actionType.trim());
        cstmt.setString(4, queryString == null ? null : queryString.trim());
        cstmt.execute();
        isCanAccess = cstmt.getString(1);

      } catch (SQLException e) {
        e.printStackTrace();
      } finally {
        try {
          if (cstmt != null) {
            cstmt.close();
          }
        } catch (Exception ex) {
          if (conn != null)
            try {
              conn.close();
            } catch (SQLException e1) {
              e1.printStackTrace();
            }
        }
        if (conn != null)
          try {
            conn.close();
          } catch (SQLException e1) {
            e1.printStackTrace();
          }
      }
    }

    // 如果没有权限,定位到提示页面。
    if (!isCanAccess.equals("1")) {
      HttpServletResponse out = (HttpServletResponse) response;
      out.sendRedirect(strContext + "/common/erroraccess.jsp");
      return;
    } else {

      // 汉字问题
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      httpRequest.setCharacterEncoding(encoding);
      //  chain.doFilter(request, response);

      // 压缩传输

      HttpServletResponse httpResponse = (HttpServletResponse) response;
      String uri = httpRequest.getRequestURI();

      String transferEncoding = getGZIPEncoding((HttpServletRequest) request);
      if (transferEncoding == null) {
        setResponseHeader(httpResponse, uri, transferEncoding);
        chain.doFilter(request, response);
      } else {
        if (!uri.endsWith("dd.xml")) // 不处理的有哪些??????
        {
          chain.doFilter(request, response);
        } else {
          System.out.println("FrameworkFilter::  Filter handle dd.xml");
          setResponseHeader(httpResponse, uri, transferEncoding);
          httpResponse.setHeader("Content-Encoding", transferEncoding);
          GZIPEncodableResponse wrappedResponse =
              new GZIPEncodableResponse((HttpServletResponse) response);
          chain.doFilter(request, wrappedResponse);
          wrappedResponse.flush();
        }
      }
    }

    //		 Pass control on to the next filter
    // chain.doFilter(request, response);

  }
  public void generateFileDetails(JspWriter out, HttpServletRequest req, Configuration conf)
      throws IOException, InterruptedException {

    int chunkSizeToView = 0;
    long startOffset = 0;
    int datanodePort;

    String blockIdStr = null;
    long currBlockId = 0;
    blockIdStr = req.getParameter("blockId");
    if (blockIdStr == null) {
      out.print("Invalid input (blockId absent)");
      return;
    }
    currBlockId = Long.parseLong(blockIdStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
      out.print("Invalid input (datanodePort absent)");
      return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);

    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null) namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    String chunkSizeToViewStr = req.getParameter("chunkSizeToView");
    if (chunkSizeToViewStr != null && Integer.parseInt(chunkSizeToViewStr) > 0) {
      chunkSizeToView = Integer.parseInt(chunkSizeToViewStr);
    } else {
      chunkSizeToView = JspHelper.getDefaultChunkSize(conf);
    }

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0) startOffset = 0;
    else startOffset = Long.parseLong(startOffsetStr);

    String filename = HtmlQuoting.unquoteHtmlChars(req.getParameter("filename"));
    if (filename == null || filename.length() == 0) {
      out.print("Invalid input");
      return;
    }

    String blockSizeStr = req.getParameter("blockSize");
    long blockSize = 0;
    if (blockSizeStr == null || blockSizeStr.length() == 0) {
      out.print("Invalid input");
      return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    DFSClient dfs = JspHelper.getDFSClient(ugi, jspHelper.nameNodeAddr, conf);
    List<LocatedBlock> blocks =
        dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks();
    // Add the various links for looking at the file contents
    // URL for downloading the full file
    String downloadUrl =
        "http://"
            + req.getServerName()
            + ":"
            + +req.getServerPort()
            + "/streamFile"
            + URLEncoder.encode(filename, "UTF-8")
            + "?"
            + JspHelper.DELEGATION_PARAMETER_NAME
            + "="
            + tokenString;
    out.print("<a name=\"viewOptions\"></a>");
    out.print("<a href=\"" + downloadUrl + "\">Download this file</a><br>");

    DatanodeInfo chosenNode;
    // URL for TAIL
    LocatedBlock lastBlk = blocks.get(blocks.size() - 1);
    long blockId = lastBlk.getBlock().getBlockId();
    try {
      chosenNode = jspHelper.bestNode(lastBlk);
    } catch (IOException e) {
      out.print(e.toString());
      dfs.close();
      return;
    }
    String fqdn = InetAddress.getByName(chosenNode.getHost()).getCanonicalHostName();
    String tailUrl =
        "http://"
            + fqdn
            + ":"
            + chosenNode.getInfoPort()
            + "/tail.jsp?filename="
            + URLEncoder.encode(filename, "UTF-8")
            + "&namenodeInfoPort="
            + namenodeInfoPort
            + "&chunkSizeToView="
            + chunkSizeToView
            + "&referrer="
            + URLEncoder.encode(req.getRequestURL() + "?" + req.getQueryString(), "UTF-8")
            + JspHelper.getDelegationTokenUrlParam(tokenString);
    out.print("<a href=\"" + tailUrl + "\">Tail this file</a><br>");

    out.print("<form action=\"/browseBlock.jsp\" method=GET>");
    out.print("<b>Chunk size to view (in bytes, up to file's DFS block size): </b>");
    out.print("<input type=\"hidden\" name=\"blockId\" value=\"" + currBlockId + "\">");
    out.print("<input type=\"hidden\" name=\"blockSize\" value=\"" + blockSize + "\">");
    out.print("<input type=\"hidden\" name=\"startOffset\" value=\"" + startOffset + "\">");
    out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">");
    out.print("<input type=\"hidden\" name=\"datanodePort\" value=\"" + datanodePort + "\">");
    out.print(
        "<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" + namenodeInfoPort + "\">");
    out.print(
        "<input type=\"text\" name=\"chunkSizeToView\" value="
            + chunkSizeToView
            + " size=10 maxlength=10>");
    out.print("&nbsp;&nbsp;<input type=\"submit\" name=\"submit\" value=\"Refresh\">");
    out.print("</form>");
    out.print("<hr>");
    out.print("<a name=\"blockDetails\"></a>");
    out.print("<B>Total number of blocks: " + blocks.size() + "</B><br>");
    // generate a table and dump the info
    out.println("\n<table>");
    for (LocatedBlock cur : blocks) {
      out.print("<tr>");
      blockId = cur.getBlock().getBlockId();
      blockSize = cur.getBlock().getNumBytes();
      String blk = "blk_" + Long.toString(blockId);
      out.print("<td>" + Long.toString(blockId) + ":</td>");
      DatanodeInfo[] locs = cur.getLocations();
      for (int j = 0; j < locs.length; j++) {
        String datanodeAddr = locs[j].getName();
        datanodePort =
            Integer.parseInt(
                datanodeAddr.substring(datanodeAddr.indexOf(':') + 1, datanodeAddr.length()));
        fqdn = InetAddress.getByName(locs[j].getHost()).getCanonicalHostName();
        String blockUrl =
            "http://"
                + fqdn
                + ":"
                + locs[j].getInfoPort()
                + "/browseBlock.jsp?blockId="
                + Long.toString(blockId)
                + "&blockSize="
                + blockSize
                + "&filename="
                + URLEncoder.encode(filename, "UTF-8")
                + "&datanodePort="
                + datanodePort
                + "&genstamp="
                + cur.getBlock().getGenerationStamp()
                + "&namenodeInfoPort="
                + namenodeInfoPort
                + "&chunkSizeToView="
                + chunkSizeToView;
        out.print(
            "<td>&nbsp</td>" + "<td><a href=\"" + blockUrl + "\">" + datanodeAddr + "</a></td>");
      }
      out.println("</tr>");
    }
    out.println("</table>");
    out.print("<hr>");
    String namenodeHost = jspHelper.nameNodeAddr.getHostName();
    out.print(
        "<br><a href=\"http://"
            + InetAddress.getByName(namenodeHost).getCanonicalHostName()
            + ":"
            + namenodeInfoPort
            + "/dfshealth.jsp\">Go back to DFS home</a>");
    dfs.close();
  }
Beispiel #15
0
    public Writer getErrorReport(
        Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException {
      final Writer logMsg = new StringWriter();
      final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg);
      Writer msg = tee;

      LinkedList<Throwable> stack = getStack();
      String ticket = new Date().toString();

      Map<String, String> props;
      try {
        props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage");
      } catch (javax.naming.NamingException ne) {
        props = Collections.emptyMap();
        log.info(ne);
      }

      if (request != null) {
        {
          msg.append("Headers\n----------\n");
          // request properties
          for (Object name : Collections.list(request.getHeaderNames())) {
            msg.append(
                escape.transform(
                    name + ": " + escape.transform(request.getHeader((String) name)) + "\n"));
          }
        }
        {
          msg.append("\nAttributes\n----------\n");
          Pattern p = requestIgnore;
          if (p == null && props.get("request_ignore") != null) {
            p = Pattern.compile(props.get("request_ignore"));
          }
          for (Object name : Collections.list(request.getAttributeNames())) {
            if (p == null || !p.matcher((String) name).matches()) {
              msg.append(
                  escape.transform(name + ": " + request.getAttribute((String) name) + "\n"));
            }
          }
        }
        if (Boolean.TRUE.equals(showSession)
            || (showSession == null && !"false".equals(props.get("show_session")))) {
          HttpSession ses = request.getSession(false);
          if (ses != null) {
            msg.append("\nSession\n----------\n");
            Pattern p = sessionIgnore;
            if (p == null && props.get("session_ignore") != null) {
              p = Pattern.compile(props.get("session_ignore"));
            }
            for (Object name : Collections.list(ses.getAttributeNames())) {
              if (p == null || !p.matcher((String) name).matches()) {
                msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n"));
              }
            }
          }
        }
      }
      msg.append("\n");
      msg.append("Misc. properties\n----------\n");

      if (request != null) {
        msg.append("method: ").append(escape.transform(request.getMethod())).append("\n");
        msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n");
        msg.append("requesturl: ")
            .append(escape.transform(request.getRequestURL().toString()))
            .append("\n");
      }
      if (Boolean.TRUE.equals(showMMBaseVersion)
          || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) {
        msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n");
      }
      msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n");

      if (request != null) {
        msg.append("Parameters\n----------\n");
        // request parameters
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String name = (String) en.nextElement();
          msg.append(name)
              .append(": ")
              .append(escape.transform(request.getParameter(name)))
              .append("\n");
        }
      }
      msg.append("\nException ")
          .append(ticket)
          .append("\n----------\n\n")
          .append(
              exception != null
                  ? (escape.transform(exception.getClass().getName()))
                  : "NO EXCEPTION")
          .append(": ");

      int wroteCauses = 0;
      while (!stack.isEmpty()) {

        Throwable t = stack.removeFirst();
        // add stack stacktraces
        if (t != null) {
          if (stack.isEmpty()) { // write last message always
            msg = tee;
          }
          String message = t.getMessage();
          if (msg != tee) {
            to.append("\n=== skipped(see log)  : ")
                .append(escape.transform(t.getClass().getName()))
                .append(": ")
                .append(message)
                .append("\n");
          }

          msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message));
          StackTraceElement[] stackTrace = t.getStackTrace();
          for (StackTraceElement e : stackTrace) {
            msg.append("\n        at ").append(escape.transform(e.toString()));
          }
          if (!stack.isEmpty()) {
            msg.append("\n-------caused:\n");
          }
          wroteCauses++;
          if (wroteCauses >= MAX_CAUSES) {
            msg = logMsg;
          }
        }
      }
      // write errors to  log
      if (status == 500) {
        try {
          if (props.get("to") != null && props.get("to").length() > 0) {
            javax.naming.Context initCtx = new javax.naming.InitialContext();
            javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
            Object mailSession = envCtx.lookup("mail/Session");
            Class sessionClass = Class.forName("javax.mail.Session");
            Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType");
            Class messageClass = Class.forName("javax.mail.internet.MimeMessage");
            Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession);
            messageClass
                .getMethod("addRecipients", recipientTypeClass, String.class)
                .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to"));
            messageClass.getMethod("setSubject", String.class).invoke(mail, ticket);
            mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString());
            Class.forName("javax.mail.Transport")
                .getMethod("send", Class.forName("javax.mail.Message"))
                .invoke(null, mail);
            tee.append("\nmailed to (").append(String.valueOf(props)).append(")");
          }

        } catch (Exception nnfe) {
          tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")");
          if (log.isDebugEnabled()) {
            log.debug(nnfe.getMessage(), nnfe);
          }
        }
        log.error("TICKET " + ticket + ":\n" + logMsg);
      }
      return to;
    }
  /**
   * ************************************************************************ Default handler for
   * OPeNDAP ascii requests. Returns OPeNDAP DAP2 data in comma delimited ascii columns for
   * ingestion into some not so OPeNDAP enabled application such as MS-Excel. Accepts constraint
   * expressions in exactly the same way as the regular OPeNDAP dataserver.
   *
   * @param request
   * @param response
   * @param dataSet
   * @throws opendap.dap.DAP2Exception
   * @throws ParseException
   */
  public void sendASCII(HttpServletRequest request, HttpServletResponse response, String dataSet)
      throws DAP2Exception, ParseException {

    if (Debug.isSet("showResponse"))
      System.out.println(
          "Sending OPeNDAP ASCII Data For: "
              + dataSet
              + "    CE: '"
              + request.getQueryString()
              + "'");

    String requestURL, ce;
    DConnect2 url;
    DataDDS dds;

    if (request.getQueryString() == null) {
      ce = "";
    } else {
      ce = "?" + request.getQueryString();
    }

    int suffixIndex = request.getRequestURL().toString().lastIndexOf(".");

    requestURL = request.getRequestURL().substring(0, suffixIndex);

    if (Debug.isSet("showResponse")) {
      System.out.println("New Request URL Resource: '" + requestURL + "'");
      System.out.println("New Request Constraint Expression: '" + ce + "'");
    }

    try {

      if (_Debug) System.out.println("Making connection to .dods service...");
      url = new DConnect2(requestURL, true);

      if (_Debug) System.out.println("Requesting data...");
      dds = url.getData(ce, null, new asciiFactory());

      if (_Debug) System.out.println(" ASC DDS: ");
      if (_Debug) dds.print(System.out);

      PrintWriter pw = new PrintWriter(response.getOutputStream());
      PrintWriter pwDebug = new PrintWriter(System.out);

      if (dds != null) {
        dds.print(pw);
        pw.println("---------------------------------------------");

        String s = "";
        Enumeration e = dds.getVariables();

        while (e.hasMoreElements()) {
          BaseType bt = (BaseType) e.nextElement();
          if (_Debug) ((toASCII) bt).toASCII(pwDebug, true, null, true);
          // bt.toASCII(pw,addName,getNAme(),true);
          ((toASCII) bt).toASCII(pw, true, null, true);
        }
      } else {

        String betterURL =
            request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("."))
                + ".dods?"
                + request.getQueryString();

        pw.println("-- ASCII RESPONSE HANDLER PROBLEM --");
        pw.println("");
        pw.println("The ASCII response handler was unable to obtain requested data set.");
        pw.println("");
        pw.println("Because this handler calls it's own OPeNDAP server to get the requested");
        pw.println("data the source error is obscured.");
        pw.println("");
        pw.println("To get a better idea of what is going wrong, try requesting the URL:");
        pw.println("");
        pw.println("    " + betterURL);
        pw.println("");
        pw.println("And then look carefully at the returned document. Note that if you");
        pw.println("are using a browser to access the URL the returned document will");
        pw.println("more than likely be treated as a download and written to your");
        pw.println("local disk. It should be a file with the extension \".dods\"");
        pw.println("");
        pw.println("Locate it, open it with a text editor, and find your");
        pw.println("way to happiness and inner peace.");
        pw.println("");
      }

      // pw.println("</pre>");
      pw.flush();
      if (_Debug) pwDebug.flush();

    } catch (FileNotFoundException fnfe) {
      System.out.println("OUCH! FileNotFoundException: " + fnfe.getMessage());
      fnfe.printStackTrace(System.out);
    } catch (MalformedURLException mue) {
      System.out.println("OUCH! MalformedURLException: " + mue.getMessage());
      mue.printStackTrace(System.out);
    } catch (IOException ioe) {
      System.out.println("OUCH! IOException: " + ioe.getMessage());
      ioe.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println("OUCH! Throwable: " + t.getMessage());
      t.printStackTrace(System.out);
    }

    if (_Debug) System.out.println(" GetAsciiHandler done");
  }
Beispiel #17
0
  public void getEnv(VariableTable vt) {
    Enumeration e = null;
    HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
    HttpSession session = request.getSession(false);

    String db_charset = "gb2312";
    String url_charset = null;

    vt.remove("SESSION.LOGINID");
    vt.remove("SESSION.LOGINNAME");
    vt.remove("SESSION.LOGINROLE");

    if (vt.exists("WEBCHART.DB_CHARSET")) {
      db_charset = vt.getString("WEBCHART.DB_CHARSET");
    }

    if (vt.exists("WEBCHART.URL_CHARSET")) {
      url_charset = vt.getString("WEBCHART.URL_CHARSET");
    }

    if (session != null) {
      e = session.getAttributeNames();
      while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        Object value = session.getAttribute(name);
        vt.add(name, java.sql.Types.VARCHAR);
        if (value != null) vt.setValue(name, value.toString());
      }
      vt.add("SESSION.ID", java.sql.Types.VARCHAR);
      vt.setValue("SESSION.ID", session.getId());
      vt.add("SESSION.CREATE", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.CREATE",
          DBOperation.toString(
              new java.util.Date(session.getCreationTime()), "yyyy-MM-dd HH:mm:ss"));
      vt.add("SESSION.ACCESS", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.ACCESS",
          DBOperation.toString(
              new java.util.Date(session.getLastAccessedTime()), "yyyy-MM-dd HH:mm:ss"));
    }
    e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String value = request.getParameter(name);
      ;
      String par_values[] = request.getParameterValues(name);
      name = name.toUpperCase();
      if (name.equalsIgnoreCase("WEBCHART.SECURITY")
          || name.equalsIgnoreCase("WEBCHART.DEFAULTACCESS")
          || name.equalsIgnoreCase("WEBCHART.ALLOW")
          || name.equalsIgnoreCase("WEBCHART.DENY")
          || name.equalsIgnoreCase("WEBCHART.IPSECURITY")
          || name.equalsIgnoreCase("WEBCHART.IPACCESS")
          || name.equalsIgnoreCase("WEBCHART.IPALLOW")
          || name.equalsIgnoreCase("WEBCHART.IPDENY")
          || name.equalsIgnoreCase("WEBCHART.XSLDOC")
          || name.equalsIgnoreCase("WEBCHART.IMAGEONLY")
          || name.equalsIgnoreCase("WEBCHART.XMLDATA")
          || name.equalsIgnoreCase("WEBCHART.LOGSQL")
          || name.equalsIgnoreCase("WEBCHART.DATATYPE")
          || name.equalsIgnoreCase("WEBCHART.URLS")
          || name.equalsIgnoreCase("WEBCHART.TOPURLS")
          || name.equalsIgnoreCase("WEBCHART.TOPCURR")
          || name.equalsIgnoreCase("WEBCHART.LEFTURLS")
          || name.equalsIgnoreCase("WEBCHART.LEFTCURR")
          || name.equalsIgnoreCase("WEBCHART.INPUTS")
          || name.equalsIgnoreCase("WEBCHART.CACHE")
          || name.equalsIgnoreCase("WEBCHART.DATA")
          || name.equalsIgnoreCase("WEBCHART.CSS")
          || name.equalsIgnoreCase("WEBCHART.RELOAD")
          || name.equalsIgnoreCase("WEBCHART.EXPIRE")
          || name.equalsIgnoreCase("WEBCHART.DMLKEY")
          || name.equalsIgnoreCase("WEBCHART.ENGINE")
          || name.equalsIgnoreCase("WEBCHART.EXCELURL")
          || name.equalsIgnoreCase("WEBCHART.DBID")
          || name.equalsIgnoreCase("WEBCHART.DBIDSEED")
          || name.equalsIgnoreCase("WEBCHART.SECUREFIELDS")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_IMAGE")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_TIME")
          || name.startsWith("WEBCHART.SECUREMEMO")
          || name.startsWith("WEBCHART.QUERY_")
          || name.startsWith("WEBCHART.HEADHTML_")
          || name.startsWith("WEBCHART.DATAHTML_")
          || name.startsWith("WEBCHART.VARLIST_")
          || name.startsWith("WEBCHART.FORALL_")
          || name.startsWith("WEBCHART.XMLDATA_")
          || name.startsWith("WEBCHART.TABLE_")
          || name.startsWith("WEBCHART.COLUMN_")
          || name.startsWith("SESSION.")) continue;
      if (name.startsWith("WEBCHART.") && !name.equals("WEBCHART.DOCTYPE")) continue;
      vt.add(name, java.sql.Types.VARCHAR);

      if (par_values != null && par_values.length > 1) {
        StringBuffer temp = new StringBuffer();
        for (int i = 0; i < par_values.length; i++) {
          if (par_values[i] != null && par_values[i].trim().length() > 0) {
            if (temp.length() > 0) {
              temp.append(",");
            }
            temp.append(par_values[i]);
          }
        }
        value = temp.toString();
      }
      if (url_charset != null) {
        try {
          value = new String(value.getBytes(url_charset), db_charset);
        } catch (java.io.UnsupportedEncodingException uee) {
        }
        ;
      }
      vt.setValue(name, value);
    }
    vt.add("REQUEST.REMOTEADDR", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEADDR", getClientIPAddr());
    vt.add("REQUEST.REMOTEHOST", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEHOST", request.getRemoteAddr());
    vt.add("REQUEST.REFERER", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REFERER", request.getHeader("Referer"));
    vt.add("REQUEST.QUERYSTRING", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.QUERYSTRING", request.getQueryString());
  }
Beispiel #18
0
  /**
   * Show details about the request
   *
   * @param servlet used to get teh servlet context, may be null
   * @param req the request
   * @return string showing the details of the request.
   */
  public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Request Info\n");
    sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n");
    sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n");
    sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n");
    sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n");
    sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n");
    sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n");
    sbuff
        .append(" getQueryStringDecoded:")
        .append(EscapeStrings.urlDecode(req.getQueryString()))
        .append("\n");
    /*try {
      sbuff.append(" getQueryStringDecoded:").append(URLDecoder.decode(req.getQueryString(), "UTF-8")).append("\n");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }*/
    sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n");
    sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n");
    sbuff.append(" getRequestServer:").append(getRequestServer(req)).append("\n");
    sbuff.append(" getRequest:").append(getRequest(req)).append("\n");
    sbuff.append("\n");

    sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n");
    String path = req.getPathTranslated();
    if ((path != null) && (servlet != null)) {
      ServletContext context = servlet.getServletContext();
      sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n");
    }
    sbuff.append("\n");
    sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n");
    sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n");
    sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n");
    sbuff.append("\n");
    sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n");
    sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n");

    sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr());
    try {
      sbuff
          .append(" getRemoteHost():")
          .append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName())
          .append("\n");
    } catch (java.net.UnknownHostException e) {
      sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n");
    }
    sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n");

    sbuff.append("\n");
    sbuff.append("Request Parameters:\n");
    Enumeration params = req.getParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      String values[] = req.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          sbuff
              .append("  ")
              .append(name)
              .append("  (")
              .append(i)
              .append("): ")
              .append(values[i])
              .append("\n");
        }
      }
    }
    sbuff.append("\n");

    sbuff.append("Request Headers:\n");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          sbuff.append("  ").append(name).append(": ").append(value).append("\n");
        }
      }
    }
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
Beispiel #19
0
 /**
  * The entire request including query string
  *
  * @param req the HttpServletRequest
  * @return entire parsed request
  */
 public static String getRequest(HttpServletRequest req) {
   String query = req.getQueryString();
   return getRequestBase(req) + (query == null ? "" : "?" + query);
 }