Example usage for javax.servlet.http HttpServletRequest getHeaderNames

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

Introduction

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

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

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  www  .  j  ava2s  . co  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.wso2.carbon.analytics.message.tracer.MessageTracerFilter.java

private Map<String, String> getHeaderDetail(HttpServletRequest servletRequest) {
    Enumeration headerNames = servletRequest.getHeaderNames();
    Map<String, String> headers = new HashMap<String, String>();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        if (!MessageTracerConstants.ACTIVITY_ID_KEY.equals(headerName)) {
            headers.put(HEADER_PREFIX + headerName, servletRequest.getHeader(headerName));
        }/*w ww.  jav a2  s  . c o  m*/
    }
    return headers;
}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Get request//w ww  .j av  a2  s . c o m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        // Transfer bytes from in to out
        log.debug("HTTP GET: transferring...");

        //execute the GET
        String serverUrl = request.getParameter("url");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            log.info("GET param serverUrl:" + serverUrl);
            HttpClient client = new HttpClient();
            GetMethod httpget = new GetMethod(serverUrl);
            client.executeMethod(httpget);

            if (log.isDebugEnabled()) {
                Header[] respHeaders = httpget.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            //dump response to out
            if (httpget.getStatusCode() == HttpStatus.SC_OK) {
                //force the response to have XML content type (WMS servers generally don't)
                response.setContentType("text/xml");
                String responseBody = httpget.getResponseBodyAsString().trim();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
                response.flushBuffer();
            } else {
                log.error("Unexpected failure: " + httpget.getStatusLine().toString());
            }
            httpget.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

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 . j av a  2  s  .  c  o  m*/
                    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:io.apiman.gateway.platforms.servlet.GatewayServlet.java

/**
 * Reads the inbound request headers from the request and sets them on
 * the {@link ServiceRequest}.//from   ww  w .j a  va2  s.  c  o  m
 * @param request
 * @param request
 */
protected void readHeaders(ServiceRequest srequest, HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = headerNames.nextElement();
        String hval = request.getHeader(hname);
        srequest.getHeaders().put(hname, hval);
    }
}

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

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

    String param = "";
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();

        if (org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)) {
            continue;
        }//from w ww.  j a  v a 2  s .c  om

        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null && values.hasMoreElements()) {
            param = name;
            break;
        }
    }
    // Note: We don't URL decode header names because people don't normally do that

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

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/

    try {
        javax.crypto.Cipher c = org.owasp.benchmark.helpers.Utils.getCipher();
        // encrypt and store the results
        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);
        }
        byte[] result = c.doFinal(input);

        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("secret_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))
                        + "' encrypted and stored<br/>");

    } catch (javax.crypto.IllegalBlockSizeException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.BadPaddingException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    }
    response.getWriter()
            .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
}

From source file:org.wso2.carbon.identity.oauth.ui.endpoints.token.OAuth2TokenEndpoint.java

private void logAccessTokenRequest(HttpServletRequest request) {
    log.debug("Received a request : " + request.getRequestURI());
    // log the headers.
    log.debug("----------logging request headers.----------");
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        Enumeration headers = request.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            log.debug(headerName + " : " + headers.nextElement());
        }/*from   ww w  . j  a  v a 2s  . c om*/
    }
    // log the parameters.
    log.debug("----------logging request parameters.----------");
    log.debug(OAuth.OAUTH_GRANT_TYPE + " - " + request.getParameter(OAuth.OAUTH_GRANT_TYPE));
    log.debug(OAuth.OAUTH_CLIENT_ID + " - " + request.getParameter(OAuth.OAUTH_CLIENT_ID));
    log.debug(OAuth.OAUTH_CODE + " - " + request.getParameter(OAuth.OAUTH_CODE));
    log.debug(OAuth.OAUTH_REDIRECT_URI + " - " + request.getParameter(OAuth.OAUTH_REDIRECT_URI));
}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Pasa los headers de un request a otro. Copia todos salvo algunos
 * prohibidos que no tienen sentido.// ww  w  .jav a  2 s  . c  o  m
 */
// CHECKSTYLE:DESIGN:OFF
protected void proxyHeaders(final HttpServletRequest request, final HttpMethod method) {

    Enumeration<String> names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = names.nextElement().toLowerCase();
        Enumeration<String> headers = request.getHeaders(name);
        if (!forbiddenHeader.contains(name)) {
            while (headers.hasMoreElements()) {
                method.addRequestHeader(name, headers.nextElement());

            }
        }
    }
}

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   www.  j  a  v a 2 s .c  o m*/
                    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:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request/* ww w . j  a  v  a2s  .  c om*/
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        String serverUrl = request.getHeader("serverUrl");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = new PostMethod(serverUrl);

            // Transfer bytes from in to out
            log.info("HTTP POST transfering..." + serverUrl);
            String body = inputStreamAsString(request.getInputStream());

            HttpClient client = new HttpClient();

            httppost.setRequestBody(body);
            if (0 == httppost.getParameters().length) {
                log.debug("No Name/Value pairs found ... pushing as raw_post_data");
                httppost.setParameter("raw_post_data", body);
            }
            if (log.isDebugEnabled()) {
                log.debug("Body = " + body);
                NameValuePair[] nameValuePairs = httppost.getParameters();
                log.debug("NameValuePairs found: " + nameValuePairs.length);
                for (int i = 0; i < nameValuePairs.length; ++i) {
                    log.debug("parameters:" + nameValuePairs[i].toString());
                }
            }
            //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);

            client.executeMethod(httppost);
            if (log.isDebugEnabled()) {
                Header[] respHeaders = httppost.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                response.setContentType("text/xml");
                String responseBody = httppost.getResponseBodyAsString();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
            } else {
                log.error("Unexpected failure: " + httppost.getStatusLine().toString());
            }
            httppost.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}