Example usage for javax.servlet.http HttpServletRequest getHeaders

List of usage examples for javax.servlet.http HttpServletRequest getHeaders

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaders.

Prototype

public Enumeration<String> getHeaders(String name);

Source Link

Document

Returns all the values of the specified request header as an Enumeration of String objects.

Usage

From source file:org.owasp.benchmark.testcode.BenchmarkTest00264.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;//from  ww w .j a va  2  s  .  c o m
                    flag = false;
                }
            }
        }
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        int randNumber = java.security.SecureRandom.getInstance("SHA1PRNG").nextInt(99);
        String rememberMeKey = Integer.toString(randNumber);

        String user = "SafeInga";
        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/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextInt(int) - TestCase");
        throw new ServletException(e);
    }
    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextInt(int) executed");
}

From source file:org.kuali.coeus.sys.framework.controller.interceptor.RequestLoggingFilter.java

/**
 * Constructs a log message that displays HTTP header information belonging to the given
 * {@link HttpServletRequest} instance. This method uses two nested loops to iterate headers
 * and then iterate through header values because a header may have one or more values.
 *//*from w w w .  j  a  v a 2 s .  c  o m*/
private String getRequestHeadersMessage(HttpServletRequest request) {
    StringBuilder retval = new StringBuilder();
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String headerName = headerNames.nextElement();
        retval.append(headerName).append(": {");

        for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues
                .hasMoreElements();) {
            String headerValue = headerValues.nextElement();

            retval.append(headerValue);
            if (headerValues.hasMoreElements()) {
                retval.append(",");
            }
        }

        retval.append("}\n");
    }

    return retval.toString();
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest02046.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;/*from  w w  w .ja  v a 2s .  com*/
                    flag = false;
                }
            }
        }
    }

    String bar = doSomething(param);

    try {
        java.util.Properties benchmarkprops = new java.util.Properties();
        benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
        String algorithm = benchmarkprops.getProperty("hashAlg1", "SHA512");
        java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
        byte[] input = { (byte) '?' };
        Object inputParam = bar;
        if (inputParam instanceof String)
            input = ((String) inputParam).getBytes();
        if (inputParam instanceof java.io.InputStream) {
            byte[] strInput = new byte[1000];
            int i = ((java.io.InputStream) inputParam).read(strInput);
            if (i == -1) {
                response.getWriter().println(
                        "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
                return;
            }
            input = java.util.Arrays.copyOf(strInput, i);
        }
        md.update(input);

        byte[] result = md.digest();
        java.io.File fileTarget = new java.io.File(
                new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
        java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data
        fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
        fw.close();
        response.getWriter()
                .println("Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                        + "' hashed and stored<br/>");
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing hash - TestCase");
        throw new ServletException(e);
    }

    response.getWriter()
            .println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01172.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;//from w ww  . j av  a  2s.com
                    flag = false;
                }
            }
        }
    }

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

    try {
        float rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextFloat();
        String rememberMeKey = Float.toString(rand).substring(2); // Trim off the 0. at the front.

        String user = "SafeFloyd";
        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/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextFloat() - TestCase");
        throw new ServletException(e);
    }
    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextFloat() executed");
}

From source file:com.woonoz.proxy.servlet.HttpRequestHandler.java

protected void copyHeaders(final HttpServletRequest from, final HttpRequestBase to,
        ClientHeadersHandler clientHeadersHandler) throws URISyntaxException, MalformedURLException {
    Enumeration<?> enumerationOfHeaderNames = from.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        final String headerName = (String) enumerationOfHeaderNames.nextElement();
        Enumeration<?> enumerationOfHeaderValues = from.getHeaders(headerName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            final String headerValue = (String) enumerationOfHeaderValues.nextElement();
            final String modifiedValue = clientHeadersHandler.handleHeader(headerName, headerValue);
            if (modifiedValue != null) {
                to.addHeader(headerName, modifiedValue);
            }/*from   ww w .  j a v a 2  s  . com*/
        }
    }
}

From source file:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho//ww w .  java  2s .  com
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01167.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;/* w w  w .j a  va 2  s .  c om*/
                    flag = false;
                }
            }
        }
    }

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

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

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        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/>");
        }

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

From source file:org.georchestra.security.HeadersManagementStrategy.java

private void handleRequestCookies(HttpServletRequest originalRequest, HttpRequestBase proxyRequest,
        StringBuilder headersLog) {

    Enumeration<String> headers = originalRequest.getHeaders(COOKIE_ID);
    StringBuilder cookies = new StringBuilder();
    while (headers.hasMoreElements()) {
        String value = headers.nextElement();
        for (String requestCookies : value.split(";")) {
            String trimmed = requestCookies.trim();
            if (trimmed.length() > 0) {
                if (!trimmed.startsWith(HeaderNames.JSESSION_ID)) {
                    if (cookies.length() > 0)
                        cookies.append("; ");
                    cookies.append(trimmed);
                }//from   ww  w  .  j  a v  a  2  s  .  c o m
            }
        }
    }
    HttpSession session = originalRequest.getSession();
    String requestPath = proxyRequest.getURI().getPath();
    if (session != null && session.getAttribute(HeaderNames.JSESSION_ID) != null) {
        Map<String, String> jessionIds = (Map) session.getAttribute(HeaderNames.JSESSION_ID);
        String currentPath = null;
        String currentId = null;
        for (String path : jessionIds.keySet()) {
            // see https://www.owasp.org/index.php/HttpOnly
            // removing extra suffixes for JSESSIONID cookie ("; HttpOnly")
            // This is related to some issues with newer versions of tomcat
            // and session loss, e.g.:
            // https://github.com/georchestra/georchestra/pull/913
            String actualPath = path.split(";")[0].trim();

            // the cookie we will use is the cookie with the longest matching path
            if (requestPath.startsWith(actualPath)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Found possible matching JSessionId: Path = " + actualPath + " id="
                            + jessionIds.get(path) + " for " + requestPath + " of uri "
                            + proxyRequest.getURI());
                }
                if (currentPath == null || currentPath.length() < actualPath.length()) {
                    currentPath = actualPath;
                    currentId = jessionIds.get(path);
                }
            }
        }
        if (currentPath != null) {
            if (cookies.length() > 0)
                cookies.append("; ");
            cookies.append(currentId);
        }
    }

    headersLog.append("\t" + COOKIE_ID);
    headersLog.append("=");
    headersLog.append(cookies);
    headersLog.append("\n");

    proxyRequest.addHeader(new BasicHeader(COOKIE_ID, cookies.toString()));

}

From source file:org.kuali.kra.web.filter.RequestLoggingFilter.java

/**
 * Constructs a log message that displays HTTP header information belonging to the given
 * {@link HttpServletRequest} instance. This method uses two nested loops to iterate headers
 * and then iterate through header values because a header may have one or more values.
 *
 * @param request/*w ww .  j  av  a2  s .  c o  m*/
 * @return Log message
 */
private String getRequestHeadersMessage(HttpServletRequest request) {
    StringBuilder retval = new StringBuilder();
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String headerName = headerNames.nextElement();
        retval.append(headerName).append(": {").toString();

        for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues
                .hasMoreElements();) {
            String headerValue = headerValues.nextElement();

            retval.append(headerValue);
            if (headerValues.hasMoreElements()) {
                retval.append(",");
            }
        }

        retval.append("}\n");
    }

    return retval.toString();
}

From source file:net.sf.j2ep.requesthandlers.RequestHandlerBase.java

/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * /*from w w w .  j av a 2 s .  c om*/
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");

    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));

        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            }
        }
    }

    setProxySpecificHeaders(method, request);
}