コード例 #1
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    String sql = "{call verifyUserPassword('foo','" + bar + "')}";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.CallableStatement statement =
          connection.prepareCall(
              sql,
              java.sql.ResultSet.TYPE_FORWARD_ONLY,
              java.sql.ResultSet.CONCUR_READ_ONLY,
              java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT);
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
コード例 #2
0
ファイル: WebUtil.java プロジェクト: djafaka/jboss-as
 /**
  * Obtain debug information from the servlet request object
  *
  * @param httpRequest
  * @return
  */
 public static String deriveUsefulInfo(HttpServletRequest httpRequest) {
   StringBuilder sb = new StringBuilder();
   sb.append("[").append(httpRequest.getContextPath());
   sb.append(":cookies=").append(httpRequest.getCookies()).append(":headers=");
   // Append Header information
   Enumeration<?> en = httpRequest.getHeaderNames();
   while (en.hasMoreElements()) {
     String headerName = (String) en.nextElement();
     sb.append(headerName).append("=");
     // Ensure HTTP Basic Password is not logged
     if (headerName.contains("authorization") == false)
       sb.append(httpRequest.getHeader(headerName)).append(",");
   }
   sb.append("]");
   // Append Request parameter information
   sb.append("[parameters=");
   Enumeration<?> enparam = httpRequest.getParameterNames();
   while (enparam.hasMoreElements()) {
     String paramName = (String) enparam.nextElement();
     String[] paramValues = httpRequest.getParameterValues(paramName);
     int len = paramValues != null ? paramValues.length : 0;
     for (int i = 0; i < len; i++) sb.append(paramValues[i]).append("::");
     sb.append(",");
   }
   sb.append("][attributes=");
   // Append Request attribute information
   Enumeration<?> enu = httpRequest.getAttributeNames();
   while (enu.hasMoreElements()) {
     String attrName = (String) enu.nextElement();
     sb.append(attrName).append("=");
     sb.append(httpRequest.getAttribute(attrName)).append(",");
   }
   sb.append("]");
   return sb.toString();
 }
コード例 #3
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    // Create the file first so the test won't throw an exception if it doesn't exist.
    // Note: Don't actually do this because this method signature could cause a tool to find THIS
    // file constructor
    // as a vuln, rather than the File signature we are trying to actually test.
    // If necessary, just run the benchmark twice. The 1st run should create all the necessary
    // files.
    // new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar).createNewFile();

    java.io.FileInputStream fileInputStream =
        new java.io.FileInputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
    java.io.FileDescriptor fd = fileInputStream.getFD();
    java.io.FileOutputStream anotOutputStream = new java.io.FileOutputStream(fd);
  } // end doPost
コード例 #4
0
ファイル: HttpClient.java プロジェクト: sponte/selenium-grid
  private PutMethod convertHttpServletRequestToPutMethod(String url, HttpServletRequest request) {
    PutMethod method = new PutMethod(url);

    for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
      String headerName = (String) headers.nextElement();
      String headerValue = (String) request.getHeader(headerName);
      method.addRequestHeader(headerName, headerValue);
    }

    method.removeRequestHeader("Host");
    method.addRequestHeader("Host", request.getRequestURL().toString());

    StringBuilder requestBody = new StringBuilder();
    try {
      BufferedReader reader = request.getReader();
      String line;
      while (null != (line = reader.readLine())) {
        requestBody.append(line);
      }
      reader.close();
    } catch (IOException e) {
      requestBody.append("");
    }

    method.setRequestEntity(new StringRequestEntity(requestBody.toString()));

    return method;
  }
コード例 #5
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar;

    // Simple if statement that assigns param to bar on true condition
    int i = 196;
    if ((500 / 42) + i > 200) bar = param;
    else bar = "This should never happen";

    String sql = "UPDATE USERS SET PASSWORD='******' WHERE USERNAME='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      int count = statement.executeUpdate(sql, new String[] {"user", "password"});
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
コード例 #6
0
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    boolean result = false;
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = (String) headerNames.nextElement();
      if ("user-agent".equals(headerName.toLowerCase())) {
        if ("android".equals(request.getHeader(headerName).toLowerCase())) {
          return true;
        }
      }
    }

    // 开发环境拦截策略
    if (Constants.ENV_DEVELOPMENT.equals(
        com.lefthand.comm.context.SystemContextHolder.getEnvironment())) {
      result = this.preHandleDevelopment(request, response, handler);
    }
    // 测试环境拦截策略
    if (Constants.ENV_TEST.equals(com.lefthand.comm.context.SystemContextHolder.getEnvironment())) {
      result = this.preHandleTest(request, response, handler);
    }
    // 生产环境拦截策略
    if (Constants.ENV_PRODUCTION.equals(
        com.lefthand.comm.context.SystemContextHolder.getEnvironment())) {
      result = this.preHandleProduction(request, response, handler);
    }

    return result;
  }
コード例 #7
0
ファイル: BaseXServlet.java プロジェクト: james-jw/basex
  @Override
  public final void service(final HttpServletRequest req, final HttpServletResponse res)
      throws IOException {

    final HTTPContext http = new HTTPContext(req, res, this);
    final boolean restxq = this instanceof RestXqServlet;
    try {
      http.authorize();
      run(http);
      http.log(SC_OK, "");
    } catch (final HTTPException ex) {
      http.status(ex.getStatus(), Util.message(ex), restxq);
    } catch (final LoginException ex) {
      http.status(SC_UNAUTHORIZED, Util.message(ex), restxq);
    } catch (final IOException | QueryException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final ProcException ex) {
      http.status(SC_BAD_REQUEST, Text.INTERRUPTED, restxq);
    } catch (final Exception ex) {
      final String msg = Util.bug(ex);
      Util.errln(msg);
      http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq);
    } finally {
      if (Prop.debug) {
        Util.outln("_ REQUEST _________________________________" + Prop.NL + req);
        final Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
          final String key = en.nextElement();
          Util.outln(Text.LI + key + Text.COLS + req.getHeader(key));
        }
        Util.out("_ RESPONSE ________________________________" + Prop.NL + res);
      }
    }
  }
コード例 #8
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo");

    String[] argsEnv = {bar};
    Runtime r = Runtime.getRuntime();

    try {
      Process p = r.exec(cmd, argsEnv);
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  } // end doPost
コード例 #9
0
ファイル: UserAction.java プロジェクト: cheeryfly/ors
 @RequestMapping("/user/getinfo")
 public void getUserInfo(HttpServletRequest request, HttpServletResponse response, String json) {
   Enumeration<String> headers = request.getHeaderNames();
   String repStr = "";
   while (headers.hasMoreElements()) {
     String head = headers.nextElement();
   }
   try {
     User user = (User) request.getSession().getAttribute("user");
     if (user == null) {
       repStr = getResponse("500", "没有有效用户");
     } else {
       StringBuffer data = new StringBuffer();
       data.append(
           "\"showname\":"
               + JSON.toJSONString(user.getShowname())
               + ","
               + "\"name\":"
               + JSON.toJSONString(user.getName()));
       repStr = getResponse("200", "查询信息成功", data.toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     repStr = getResponse("500", "获取信息失败!");
   }
   sendJSONToClient(repStr, response);
 }
コード例 #10
0
 /**
  * 功能:评论添加保存,返回json对象
  *
  * @date 2016年1月18日
  * @param record
  * @return jsonString
  * @throws null
  */
 @RequestMapping(value = "/comment_add.html", method = RequestMethod.POST)
 @ResponseBody
 public String insertAction(@RequestBody Comment record, HttpServletRequest request)
     throws Exception {
   // TODO Auto-generated method stub
   logger.debug("评论添加保存,返回json对象");
   record.setUserid(1);
   record.setIp(getIpAddr(request));
   record.setPraisetime(Tool.getCurrentUnixTime());
   // 封装用户请求头信息
   Map<String, String> osInfoMap = new HashMap<String, String>();
   Enumeration<String> headerNames = request.getHeaderNames();
   for (Enumeration<String> e = headerNames; e.hasMoreElements(); ) {
     String headerName = e.nextElement().toString();
     String headerValue = request.getHeader(headerName);
     osInfoMap.put(headerName, headerValue);
   }
   record.setOsinfo(JSON.toJSONString(osInfoMap));
   // 插入数据
   int lastInsertId = commentService.insertRecord(record);
   if (lastInsertId > 0) {
     jsonCallObj.setForward("/admin/comment_list.html");
     jsonCallObj.setStatusCode(1);
     jsonCallObj.setCloseCurrent(true);
     jsonCallObj.setMessage("添加成功,请前往评论中心查看详情列表");
   }
   String jsonCallString = JSON.toJSONString(jsonCallObj);
   return jsonCallString;
 }
コード例 #11
0
ファイル: UserAction.java プロジェクト: cheeryfly/ors
  @RequestMapping("/login/validate")
  public void validate(HttpServletRequest request, HttpServletResponse response, String json) {
    Enumeration<String> headers = request.getHeaderNames();
    String repStr = "";
    while (headers.hasMoreElements()) {
      String head = headers.nextElement();
    }
    try {
      if (json == null || json.equals("")) {
        repStr = getResponse("500", "网络传输错误!");
      }

      Map map = (Map) JSON.parse(json);
      if (map == null) {
        map = new HashMap();
      }

      User user = new User();
      String name = map.get("name") == null ? null : (String) map.get("name");
      String pwd = map.get("pwd") == null ? null : (String) map.get("pwd");
      boolean isLog = userService.loginValidate(name, pwd);

      if (isLog) {
        user = userService.getUserByName(name);
        request.getSession().setAttribute("user", user);
        repStr = getResponse("200", "登陆成功");
      } else {
        repStr = getResponse("500", "登陆失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
      repStr = getResponse("500", "登陆失败!");
    }
    sendJSONToClient(repStr, response);
  }
コード例 #12
0
ファイル: DebugTag.java プロジェクト: automenta/lojix
  /**
   * Returns a String with all header information as an HTML table.
   *
   * @return A String with all header information as an HTML table.
   */
  public String getHeaders() {
    Map info = new TreeMap();
    HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
    Enumeration names = req.getHeaderNames();

    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name);
      StringBuffer sb = new StringBuffer();
      boolean first = true;

      while (values.hasMoreElements()) {
        if (!first) {
          sb.append(" | ");
        }

        first = false;
        sb.append(values.nextElement());
      }

      info.put(name, sb.toString());
    }

    return toHTMLTable("headers", info);
  }
コード例 #13
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar;

    // Simple if statement that assigns constant to bar on true condition
    int i = 86;
    if ((7 * 42) - i > 200) bar = "This_should_always_happen";
    else bar = param;

    try {
      java.nio.file.Path path =
          java.nio.file.Paths.get(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
      java.io.InputStream is =
          java.nio.file.Files.newInputStream(path, java.nio.file.StandardOpenOption.READ);
    } catch (Exception e) {
      // OK to swallow any exception for now
      // TODO: Fix this, if possible.
      System.out.println("File exception caught and swallowed: " + e.getMessage());
    }
  }
コード例 #14
0
  private static Properties createCGIEnvironment(
      HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException {

    URI full_request_uri =
        new URI(
            sreq.getScheme(),
            null,
            sreq.getServerName(),
            sreq.getServerPort(),
            sreq.getRequestURI(),
            sreq.getQueryString(),
            null);

    Properties p =
        createCGIEnvironment(
            sreq.getMethod(),
            sreq.getProtocol(),
            full_request_uri,
            new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()),
            new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()),
            sreq.getContextPath() + "/",
            root_uri,
            canonical_script_file);

    // Add request headers

    for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) {
      String h = (String) e.nextElement();
      p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h));
    }

    return p;
  }
コード例 #15
0
 private void printHeader() {
   Enumeration e = req.getHeaderNames();
   while (e.hasMoreElements()) {
     String h = (String) e.nextElement();
     System.out.println(h + "   " + req.getHeader(h));
   }
 }
コード例 #16
0
ファイル: ServletRequestCopy.java プロジェクト: haster/wicket
  public ServletRequestCopy(HttpServletRequest request) {
    this.servletPath = request.getServletPath();
    this.contextPath = request.getContextPath();
    this.pathInfo = request.getPathInfo();
    this.requestUri = request.getRequestURI();
    this.requestURL = request.getRequestURL();
    this.method = request.getMethod();
    this.serverName = request.getServerName();
    this.serverPort = request.getServerPort();

    HttpSession session = request.getSession(true);
    httpSession = new HttpSessionCopy(session);

    String s;
    Enumeration<String> e = request.getHeaderNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      Enumeration<String> headerValues = request.getHeaders(s);
      this.headers.put(s, headerValues);
    }

    e = request.getAttributeNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      attributes.put(s, request.getAttribute(s));
    }

    e = request.getParameterNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      parameters.put(s, request.getParameterValues(s));
    }
  }
コード例 #17
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
コード例 #18
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = doSomething(param);

    String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='******'";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.PreparedStatement statement =
          connection.prepareStatement(
              sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
      statement.setString(1, "foo");
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
コード例 #19
0
  private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request)
      throws IOException {
    URI targetUri;
    try {
      targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod =
        httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      Enumeration<String> headerVals = request.getHeaders(headerName);
      while (headerVals.hasMoreElements()) {
        String headerValue = headerVals.nextElement();
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
          commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
        }
      }
    }

    return commonsHttpMethod;
  }
コード例 #20
0
 public String fetchUser(HttpServletRequest request) {
   ALNTLogger.info(
       "ALNTHttpHeaderValidator".getClass().getName(),
       "fetchUser",
       "fetching user using HTTP header");
   String headerName = "";
   String encodedHeaderValue = "";
   String userId = "";
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     headerName = (String) headerNames.nextElement();
     if (headerName.equalsIgnoreCase(CommonConstants.CALLING_APP_LOGGEDIN_USER)) {
       encodedHeaderValue = request.getHeader(headerName);
       break;
     }
   }
   if (encodedHeaderValue != null && !encodedHeaderValue.equals("")) {
     try {
       userId = EncodeDecodeUtil.decodeBase64(encodedHeaderValue);
     } catch (Exception e) {
       ALNTLogger.error("ALNTHttpHeaderValidator".getClass().getName(), "fetchUser", e, true);
       userId = "";
     }
   }
   return userId;
 }
コード例 #21
0
ファイル: ClientAuthServlet.java プロジェクト: rac2030/CAPS
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_OK);
    X509Certificate[] certs =
        (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");

    PrintWriter writer = resp.getWriter();

    if (certs == null) {
      writer.println("Cert: 0");
    } else {
      writer.println("Cert: " + certs.length);
      for (X509Certificate c : certs) {
        writer.println("<cert>" + certs[0].getSubjectDN() + "</cert>");
      }
    }

    writer.println();
    writer.println("<method>" + req.getMethod() + "</method>");
    writer.println("<headers>");
    writer.println("Request Headers:");
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String hdr = (String) headerNames.nextElement();
      Enumeration headers = req.getHeaders(hdr);
      while (headers.hasMoreElements()) {
        String val = (String) headers.nextElement();
        writer.println(hdr + ": " + val);
      }
    }
    writer.println("</headers>");

    writer.close();
  }
コード例 #22
0
ファイル: ProxyServlet.java プロジェクト: alesj/hawtio
 /**
  * Retreives all of the headers from the servlet request and sets them on the proxy request
  *
  * @param httpServletRequest The request object representing the client's request to the servlet
  *     engine
  * @param httpMethodProxyRequest The request that we are about to send to the proxy host
  */
 @SuppressWarnings("unchecked")
 private void setProxyRequestHeaders(
     HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
   // Get an Enumeration of all of the header names sent by the client
   Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
   while (enumerationOfHeaderNames.hasMoreElements()) {
     String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
     if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue;
     // As per the Java Servlet API 2.5 documentation:
     //		Some headers, such as Accept-Language can be sent by clients
     //		as several headers each with a different value rather than
     //		sending the header as a comma separated list.
     // Thus, we get an Enumeration of the header values sent by the client
     Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
     while (enumerationOfHeaderValues.hasMoreElements()) {
       String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
       // In case the proxy host is running multiple virtual servers,
       // rewrite the Host header to ensure that we get content from
       // the correct virtual server
       if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
         stringHeaderValue = getProxyHostAndPort();
       }
       Header header = new Header(stringHeaderName, stringHeaderValue);
       // Set the same header on the proxy request
       httpMethodProxyRequest.setRequestHeader(header);
     }
   }
 }
コード例 #23
0
  public AbstractMockRequest(
      HttpServletRequest request, HttpServletResponse response, WsdlMockRunContext context) {
    this.request = request;
    this.response = response;
    this.context = context;

    requestContext = new WsdlMockRunContext(context.getMockService(), null);

    requestHeaders = new StringToStringsMap();
    for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements(); ) {
      String header = (String) e.nextElement();
      String lcHeader = header.toLowerCase();
      if (lcHeader.equals("soapaction"))
        requestHeaders.put("SOAPAction", request.getHeader(header));
      else if (lcHeader.equals("content-type"))
        requestHeaders.put("Content-Type", request.getHeader(header));
      else if (lcHeader.equals("content-length"))
        requestHeaders.put("Content-Length", request.getHeader(header));
      else if (lcHeader.equals("content-encoding"))
        requestHeaders.put("Content-Encoding", request.getHeader(header));
      else requestHeaders.put(header, request.getHeader(header));
    }

    protocol = request.getProtocol();
    path = request.getPathInfo();
    if (path == null) path = "";
  }
コード例 #24
0
  private static void load(HttpServletRequest request, Builder b) {
    Enumeration<String> e = request.getHeaderNames();
    String s;
    while (e.hasMoreElements()) {
      s = e.nextElement();
      b.headers.put(s, request.getHeader(s));
    }

    e = request.getAttributeNames();
    while (e.hasMoreElements()) {
      s = e.nextElement();
      b.localAttributes.put(s, attributeWithoutException(request, s));
    }

    e = request.getParameterNames();
    while (e.hasMoreElements()) {
      s = e.nextElement();
      b.queryStrings.put(s, request.getParameterValues(s));
    }
    b.queryString = request.getQueryString();

    Enumeration<Locale> l = request.getLocales();
    while (l.hasMoreElements()) {
      b.locale(l.nextElement());
    }
  }
コード例 #25
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    try {
      java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG");

      // Get 40 random bytes
      byte[] randomBytes = new byte[40];
      getNextNumber(numGen, randomBytes);
      response.getWriter().println("Random bytes are: " + new String(randomBytes));

    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
      throw new ServletException(e);
    } finally {
      response
          .getWriter()
          .println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
  }
コード例 #26
0
 /**
  * Dump request headers
  *
  * @param request
  */
 public static void dumpHeaders(final HttpServletRequest request) {
   final Enumeration<String> headers = request.getHeaderNames();
   while (headers.hasMoreElements()) {
     String header = headers.nextElement();
     System.out.println(header + " = " + request.getHeader(header));
   }
 }
コード例 #27
0
  private void logRequest(HttpServletRequest request) {
    if (logger.isInfoEnabled()) {
      logger.info("Request method: " + request.getMethod());
      logger.info("Request contextPath: " + request.getContextPath());
      logger.info("Request pathInfo: " + request.getPathInfo());
      logger.info("Request pathTranslated: " + request.getPathTranslated());
      logger.info("Request queryString: " + request.getQueryString());
      logger.info("Request requestURI: " + request.getRequestURI());
      logger.info("Request requestURL: " + request.getRequestURL());
      logger.info("Request servletPath: " + request.getServletPath());
      Enumeration headers = request.getHeaderNames();
      if (headers != null) {
        while (headers.hasMoreElements()) {
          Object headerName = headers.nextElement();
          logger.info(
              "Request header " + headerName + ":" + request.getHeader((String) headerName));
        }
      }

      Enumeration params = request.getParameterNames();
      if (params != null) {
        while (params.hasMoreElements()) {
          Object paramName = params.nextElement();
          logger.info(
              "Request parameter " + paramName + ":" + request.getParameter((String) paramName));
        }
      }
      logger.info("- End of request -");
    }
  }
コード例 #28
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar;

    // Simple if statement that assigns param to bar on true condition
    int i = 196;
    if ((500 / 42) + i > 200) bar = param;
    else bar = "This should never happen";

    try {
      java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-512", "SUN");
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)");
      throw new ServletException(e);
    } catch (java.security.NoSuchProviderException e) {
      System.out.println(
          "Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)");
      throw new ServletException(e);
    }

    response
        .getWriter()
        .println(
            "Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.lang.String) executed");
  }
コード例 #29
0
    public void handle(
        String s, Request r, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException, ServletException {

      Enumeration<?> e = httpRequest.getHeaderNames();
      String param;
      while (e.hasMoreElements()) {
        param = e.nextElement().toString();
        httpResponse.addHeader("X-" + param, httpRequest.getHeader(param));
      }

      int size = 10 * 1024;
      if (httpRequest.getContentLength() > 0) {
        size = httpRequest.getContentLength();
      }
      byte[] bytes = new byte[size];
      if (bytes.length > 0) {
        final InputStream in = httpRequest.getInputStream();
        final OutputStream out = httpResponse.getOutputStream();
        int read;
        while ((read = in.read(bytes)) != -1) {
          out.write(bytes, 0, read);
        }
      }

      httpResponse.setStatus(200);
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
    }
コード例 #30
0
ファイル: Request.java プロジェクト: frankely/ServletIO
 /** @return all headers */
 public Set<String> headers() {
   Set<String> headers = new TreeSet<String>();
   Enumeration<String> enumeration = raw.getHeaderNames();
   while (enumeration.hasMoreElements()) {
     headers.add(enumeration.nextElement());
   }
   return headers;
 }