@Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.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 {
      double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
      throw new ServletException(e);
    }

    response
        .getWriter()
        .println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

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

    try {
      javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE");
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
      throw new ServletException(e);
    } catch (java.security.NoSuchProviderException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
      throw new ServletException(e);
    }

    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
  } // end doPost
  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;
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String bar;

    // Simple ? condition that assigns param to bar on false condition
    int i = 106;

    bar = (7 * 42) - i > 200 ? "This should never happen" : param;

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

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

    try {
      Process p = r.exec(cmd, argsEnv, new java.io.File(System.getProperty("user.dir")));
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String bar = doSomething(param);

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

    String[] argsEnv = {"Foo=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
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String bar;

    // Simple ? condition that assigns param to bar on false condition
    int i = 106;

    bar = (7 * 42) - i > 200 ? "This should never happen" : param;

    try {
      java.io.FileInputStream fis =
          new java.io.FileInputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
    } catch (Exception e) {
      // OK to swallow any exception
      // TODO: Fix this.
      System.out.println("File exception caught and swallowed: " + e.getMessage());
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    StringBuilder sbxyz98365 = new StringBuilder(param);
    String bar = sbxyz98365.append("_SafeStuff").toString();

    // FILE URIs are tricky because they are different between Mac and Windows because of lack of
    // standardization.
    // Mac requires an extra slash for some reason.
    String startURIslashes = "";
    if (System.getProperty("os.name").indexOf("Windows") != -1)
      if (System.getProperty("os.name").indexOf("Windows") != -1) startURIslashes = "/";
      else startURIslashes = "//";

    try {
      java.net.URI fileURI =
          new java.net.URI(
              "file:"
                  + startURIslashes
                  + org.owasp.benchmark.helpers.Utils.testfileDir
                      .replace('\\', '/')
                      .replace(' ', '_')
                  + bar);
      new java.io.File(fileURI);
    } catch (java.net.URISyntaxException e) {
      throw new ServletException(e);
    }
  }
Example #8
0
  @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();
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String bar = doSomething(param);

    try {
      java.security.SecureRandom secureRandomGenerator =
          java.security.SecureRandom.getInstance("SHA1PRNG");

      // Get 40 random bytes
      byte[] randomBytes = new byte[40];
      secureRandomGenerator.nextBytes(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");
    }
  } // end doPost
Example #10
0
 /**
  * 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);
     }
   }
 }
Example #11
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

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

    try {
      java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA1", "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");
  } // end doPost
Example #12
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String bar;
    String guess = "ABC";
    char switchTarget = guess.charAt(1); // condition 'B', which is safe

    // Simple case statement that assigns param to bar on conditions 'A' or 'C'
    switch (switchTarget) {
      case 'A':
        bar = param;
        break;
      case 'B':
        bar = "bob";
        break;
      case 'C':
      case 'D':
        bar = param;
        break;
      default:
        bar = "bob's your uncle";
        break;
    }

    float rand = new java.util.Random().nextFloat();

    response.getWriter().println("Weak Randomness Test java.util.Random.nextFloat() executed");
  }
Example #13
0
  @SuppressWarnings("unchecked")
  private void ifMatchConditionalProcessing(HttpServletRequest request, XcapResourceImpl resource)
      throws XcapException {
    Enumeration ifMatchEnum = request.getHeaders(Constants.IF_MATCH);
    String currentEtag = getEtag(resource);
    resource.setPreviousEtag(currentEtag);

    if (ifMatchEnum != null && ifMatchEnum.hasMoreElements()) {

      while (ifMatchEnum.hasMoreElements()) {
        String element = (String) ifMatchEnum.nextElement();
        String[] matchEtags = element.split(",");

        for (int i = 0; i < matchEtags.length; i++) {
          if (Constants.WILCARD.equals(matchEtags[i].trim())) {
            if (resource.isAllDocument() && resource.isCreation()) {
              throw new XcapException(
                  "Conditional processing failed: " + "If-match: * and new document creation",
                  HttpServletResponse.SC_PRECONDITION_FAILED);
            } else if (_log.isDebugEnabled()) _log.debug("wilcard entity tags has matched");
          } else if (currentEtag.equals(matchEtags[i].trim())) {
            if (_log.isDebugEnabled()) _log.debug("entity tag has matched");
            return;
          }
        }
      }
      throw new XcapException(
          "Conditional processing failed: " + "If-match: present and none match",
          HttpServletResponse.SC_PRECONDITION_FAILED);
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

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

    String bar = param;
    if (param != null && param.length() > 1) {
      StringBuilder sbxyz87271 = new StringBuilder(param);
      bar = sbxyz87271.replace(param.length() - "Z".length(), param.length(), "Z").toString();
    }

    double value = new java.util.Random().nextDouble();
    String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextDouble() executed");
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

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

    String bar = doSomething(param);

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

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      statement.execute(sql, java.sql.Statement.RETURN_GENERATED_KEYS);
      org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response);
    } catch (java.sql.SQLException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  } // end doPost
Example #16
0
  /**
   * 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);
  }
Example #17
0
 @SuppressWarnings("unchecked")
 public static List<String> getHeaders(String name, HttpServletRequest req) {
   Enumeration<String> enumeration = req.getHeaders(name);
   return enumeration == null
       ? Collections.<String>emptyList()
       : Expressive.list(Expressive.iterable(enumeration));
 }
Example #18
0
  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));
    }
  }
Example #19
0
  private void doGet(Map<String, String> parameters, boolean checkResultContent)
      throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    for (final Map.Entry<String, String> entry : parameters.entrySet()) {
      if (REQUEST_PARAMETER.equals(entry.getKey())) {
        expect(request.getHeader(entry.getKey())).andReturn(entry.getValue()).anyTimes();
      } else {
        expect(request.getParameter(entry.getKey())).andReturn(entry.getValue()).anyTimes();
      }
    }
    expect(request.getHeaders("Accept-Encoding"))
        .andReturn(Collections.enumeration(Arrays.asList("application/gzip")))
        .anyTimes();
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();

    replay(request);
    replay(response);
    reportServlet.doGet(request, response);
    verify(request);
    verify(response);

    if (checkResultContent) {
      assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
  }
 @Override
 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory)
     throws ServerAuthException {
   HttpServletRequest request = ((HttpServletRequest) req);
   if (getAdapterConfig().isBearerOnly() == false
       && request.getQueryString() != null
       && request.getQueryString().contains("code=")) {
     // we receive a code as part of the query string that is returned by OAuth
     // but only assume control is this is not bearer only!
     mandatory = true;
   } else if (request.getHeaders("Authorization").hasMoreElements()) {
     // we receive Authorization, might be Bearer or Basic Auth (both supported by Keycloak)
     mandatory = true;
   }
   HttpSession session = ((HttpServletRequest) req).getSession(false);
   if (session != null
       && session.getAttribute(JettyAdapterSessionStore.CACHED_FORM_PARAMETERS) != null) {
     // this is a redirect after the code has been received for a FORM
     mandatory = true;
   } else if (session != null
       && session.getAttribute(KeycloakSecurityContext.class.getName()) != null) {
     // there is an existing authentication in the session, use it
     mandatory = true;
   }
   Authentication authentication = super.validateRequest(req, res, mandatory);
   if (authentication instanceof DeferredAuthentication) {
     // resolving of a deferred authentication later will otherwise lead to a NullPointerException
     authentication = null;
   }
   return authentication;
 }
Example #21
0
 @Override
 public Enumeration<String> getHeaders(String name) {
   Enumeration<String> headers = super.getHeaders(name);
   if (headers == null) {
     headers = originalRequest.getHeaders(name);
   }
   return headers;
 }
Example #22
0
 public static List<String> getHeader(HttpServletRequest req, String h) {
   final LinkedList<String> list = new LinkedList<>();
   final Enumeration<?> e = req.getHeaders(h);
   while (e.hasMoreElements()) {
     list.add(e.nextElement().toString());
   }
   return list;
 }
  @Override
  @SuppressWarnings("unchecked")
  protected boolean accepts(HttpServletRequest request) {

    if (super.accepts(request)) {
      Enumeration<String> cacheHeader = request.getHeaders(CACHE_CONTROL_NAME);
      return cacheHeader == null || !cacheHeader.hasMoreElements();
    }
    return false;
  }
Example #24
0
 /**
  * Check if the user agent supports gzip encoding.
  *
  * @param request The servlet request we are processing
  * @return boolean true if the user agent supports gzip encoding, and false if the user agent does
  *     not support gzip encoding
  */
 protected boolean checkIfGzip(HttpServletRequest request) {
   Enumeration<String> headers = request.getHeaders("Accept-Encoding");
   while (headers.hasMoreElements()) {
     String header = headers.nextElement();
     if (header.indexOf("gzip") != -1) {
       return true;
     }
   }
   return false;
 }
Example #25
0
    @Override
    public List<String> getHeaderValues(String s) {
      Enumeration<String> values = m_request.getHeaders(s);
      List<String> ret = new ArrayList<String>();
      while (values.hasMoreElements()) {
        ret.add(values.nextElement());
      }

      return (ret);
    }
 private void echo(HttpServletRequest request, HttpServletResponse response) throws IOException {
   response.setStatus(HttpServletResponse.SC_OK);
   for (Enumeration<?> e1 = request.getHeaderNames(); e1.hasMoreElements(); ) {
     String headerName = (String) e1.nextElement();
     for (Enumeration<?> e2 = request.getHeaders(headerName); e2.hasMoreElements(); ) {
       String headerValue = (String) e2.nextElement();
       response.addHeader(headerName, headerValue);
     }
   }
   FileCopyUtils.copy(request.getInputStream(), response.getOutputStream());
 }
 /**
  * Checks if request contains the header value.
  *
  * @param request the current request
  * @param header the header name
  * @param value the value or partial value
  * @return <code>true</code> if the header contains the value, <code>false</code> otherwise.
  */
 protected boolean headerContains(
     final HttpServletRequest request, final String header, final String value) {
   final Enumeration accepted = request.getHeaders(header);
   while (accepted.hasMoreElements()) {
     final String headerValue = (String) accepted.nextElement();
     if (headerValue.contains(value)) {
       return true;
     }
   }
   return false;
 }
 private boolean containsHeader(HttpServletRequest req, String name, String value) {
   for (Enumeration<?> e1 = req.getHeaderNames(); e1.hasMoreElements(); ) {
     String headerName = (String) e1.nextElement();
     for (Enumeration<?> e2 = req.getHeaders(headerName); e2.hasMoreElements(); ) {
       String headerValue = (String) e2.nextElement();
       if (headerName.equals(name) && headerValue.equals(value)) {
         return true;
       }
     }
   }
   return false;
 }
Example #29
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    /*
     * Recuperando o nome de todos os headers da requisicao.
     */
    Enumeration<String> headerNames = req.getHeaderNames();
    StringBuilder hNames = new StringBuilder("Headers:\n");
    while (headerNames.hasMoreElements()) {
      hNames.append(headerNames.nextElement() + "\n");
    }

    /*
     * Recuperando os valores do header hTeste. Os valores dos parametros de
     * cabecalhos vem em uma lista separados por virgula (,). Ou seja, caso
     * haja mais de um valor, eles virao na forma val1,val2, etc.
     */
    Enumeration<String> headerTeste = req.getHeaders("hTeste");
    StringBuilder hTeste = new StringBuilder("hTeste:\n");
    while (headerTeste.hasMoreElements()) {
      hTeste.append(headerTeste.nextElement() + "\n");
    }

    /*
     * Recuperando o valor do parametro header Accept. Como os header sao
     * case-insensitive, nao ha problemas em passar o nome do header em
     * caixa baixa.
     */
    String accept = req.getHeader("accept");

    /*
     * metodo conveniente que recupera o header testeInt e realiza o cast
     * para um numero inteiro.
     */
    int headerInt = req.getIntHeader("testeInt");

    /*
     * Os m├ętodos setHeader e addheader aceitam duas Strings como
     * parametros.
     */
    // resp.addHeader("br.com.servlets.header", "header Test");
    // resp.setHeader("br.com.servlets.header", "header Test");

    PrintWriter writer = resp.getWriter();
    writer.write(hNames.toString());
    writer.write("\n==================================\n");
    writer.write(hTeste.toString());
    writer.write("\n==================================\n");
    writer.write(accept);
    writer.write("\n==================================\n");
    writer.write(headerInt);
  }
  @Override
  @SuppressWarnings("unchecked")
  public HttpHeader header(String key) {
    List<String> headerNames = list(request.getHeaderNames());
    for (String currentKey : headerNames) {
      if (currentKey.toLowerCase().equals(key.toLowerCase())) {
        List<String> valueList = list(request.getHeaders(currentKey));
        return new HttpHeader(key, valueList);
      }
    }

    return HttpHeader.absent(key);
  }