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.BenchmarkTest01198.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> headers = request.getHeaders("BenchmarkTest01198");

    if (headers != null && headers.hasMoreElements()) {
        param = headers.nextElement(); // just grab first element
    }/*from ww w. ja v  a2s  .c o  m*/

    // URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
    param = java.net.URLDecoder.decode(param, "UTF-8");

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

    try {
        double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();

        String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.

        String user = "SafeDonna";
        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();
        if (cookies != null) {
            for (int i = 0; !foundUser && i < cookies.length; i++) {
                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);
            //         rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
            rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
            // e.g., /benchmark/sql-01/BenchmarkTest01001
            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.nextDouble() - TestCase");
        throw new ServletException(e);
    }
    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}

From source file:cn.sel.wetty.interceptor.AccessLogger.java

private String getHeaders(HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    List<String> result = new ArrayList<>();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        result.add(String.format("%s=%s", name, getEnumerationString(request.getHeaders(name))));
    }//from w  ww  .j ava2 s . co  m
    return Arrays.toString(result.toArray());
}

From source file:org.openrepose.powerfilter.intrafilterlogging.RequestLog.java

private Map<String, String> convertRequestHeadersToMap(HttpServletRequest httpServletRequest) {
    Map<String, String> headerMap = new LinkedHashMap<>();
    List<String> headerNames = Collections.list(httpServletRequest.getHeaderNames());

    for (String headerName : headerNames) {
        StringJoiner stringJoiner = new StringJoiner(",");
        Collections.list(httpServletRequest.getHeaders(headerName)).forEach(stringJoiner::add);
        headerMap.put(headerName, stringJoiner.toString());
    }//from w  ww.ja va 2  s.  co  m

    return headerMap;
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

/**
 * If the etag does not match any of the etags in any of the "If-None-Match"
 * headers, then they are all stale. An asterisk matches anything.
 */// www .j  a  v  a  2  s . c o m
private boolean cacheIsStale(HttpServletRequest req, String etag) {
    for (Enumeration<?> values = req.getHeaders("If-None-Match"); values.hasMoreElements();) {
        String value = (String) values.nextElement();
        log.debug("If-None-Match: " + value);

        String[] matches = value.split("\\s*,\\s*");
        for (String match : matches) {
            if (etag.equalsIgnoreCase(match) || "*".equals(match)) {
                log.debug("Cache is not stale: etag=" + match);
                return false;
            }
        }
    }
    log.debug("Cache is stale.");
    return true;
}

From source file:HeaderSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    out.println("Request Headers:");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = req.getHeaders(name); // support multiple values
        if (values != null) {
            while (values.hasMoreElements()) {
                String value = (String) values.nextElement();
                out.println(name + ": " + value);
            }/*w w w  . j  a v a  2s  . c  o m*/
        }
    }
}

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

@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
    }//from ww w .  jav  a  2  s .  c o m

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

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/
    // 8-byte initialization vector
    byte[] iv = { (byte) 0xB2, (byte) 0x12, (byte) 0xD5, (byte) 0xB2, (byte) 0x44, (byte) 0x21, (byte) 0xC3,
            (byte) 0xC3033 };

    try {
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING",
                java.security.Security.getProvider("SunJCE"));

        // Prepare the cipher to encrypt
        javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey();
        java.security.spec.AlgorithmParameterSpec paramSpec = new javax.crypto.spec.IvParameterSpec(iv);
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, key, paramSpec);

        // 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 (java.security.NoSuchAlgorithmException 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.NoSuchPaddingException 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.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);
    } catch (java.security.InvalidKeyException 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 (java.security.InvalidAlgorithmParameterException 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.security.Provider) executed");
}

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

@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
    }/*from  w ww  .  ja va 2  s. c  o  m*/

    String bar = doSomething(param);

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/
    // 8-byte initialization vector
    byte[] iv = { (byte) 0xB2, (byte) 0x12, (byte) 0xD5, (byte) 0xB2, (byte) 0x44, (byte) 0x21, (byte) 0xC3,
            (byte) 0xC3033 };

    try {
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5Padding");

        // Prepare the cipher to encrypt
        javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey();
        java.security.spec.AlgorithmParameterSpec paramSpec = new javax.crypto.spec.IvParameterSpec(iv);
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, key, paramSpec);

        // 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 (java.security.NoSuchAlgorithmException 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.NoSuchPaddingException 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.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);
    } catch (java.security.InvalidKeyException 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 (java.security.InvalidAlgorithmParameterException 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) executed");
}

From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java

/**
 * Parse the OAuth header parameters. The parameters will be oauth-decoded.
 *
 * @param request The request.//from   w w  w .j a  v a  2 s  .  c o  m
 * @return The parsed parameters, or null if no OAuth authorization header was supplied.
 */
protected String parseHeaderToken(HttpServletRequest request) {
    Enumeration<String> headers = request.getHeaders("Authorization");
    while (headers.hasMoreElements()) {
        String value = headers.nextElement();
        if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) {
            String authHeaderValue = value.substring(BEARER_TYPE.length()).trim();

            if (authHeaderValue.contains("oauth_signature_method")
                    || authHeaderValue.contains("oauth_verifier")) {
                // presence of oauth_signature_method or oauth_verifier implies an oauth 1.x request
                continue;
            }

            int commaIndex = authHeaderValue.indexOf(',');
            if (commaIndex > 0) {
                authHeaderValue = authHeaderValue.substring(0, commaIndex);
            }

            // todo: parse any parameters...

            return authHeaderValue;
        } else {
            // todo: support additional authorization schemes for different token types, e.g. "MAC" specified by
            // http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token
        }
    }

    return null;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    out.println("Request Headers:");
    out.println();/*from   ww w . j av  a  2s.com*/
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = req.getHeaders(name); // support multiple values
        if (values != null) {
            while (values.hasMoreElements()) {
                String value = (String) values.nextElement();
                out.println(name + ": " + value);
            }
        }
    }
}

From source file:org.ajax4jsf.tests.MockExternalContext.java

public Map getRequestHeaderValuesMap() {
    if (null == requestHeaderValuesMap) {
        requestHeaderValuesMap = new TreeMap(CASE_INSENSITIVE_COMPARATOR);

        HttpServletRequest request = (HttpServletRequest) getRequest();

        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();

            requestHeaderValuesMap.put(name, EnumerationUtils.toList(request.getHeaders(name)).toArray());
        }/*from  w  ww .ja va  2s . c  om*/
    }

    return Collections.unmodifiableMap(requestHeaderValuesMap);
}