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.BenchmarkTest01141.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 ww  .j av  a  2  s .c  o m
                    flag = false;
                }
            }
        }
    }

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

    try {
        java.util.Properties benchmarkprops = new java.util.Properties();
        benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
        String algorithm = benchmarkprops.getProperty("cryptoAlg1", "DESede/ECB/PKCS5Padding");
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm);

        // Prepare the cipher to encrypt
        javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey();
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, key);

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

    response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
}

From source file:org.esigate.servlet.MockHttpServletRequestBuilder.java

/**
 * Build the request as defined in the current builder.
 * //from   w ww  .  ja  v a 2 s. c om
 * @return the request
 */
public HttpServletRequest build() {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

    Mockito.when(request.getMethod()).thenReturn(this.method);
    Mockito.when(request.getProtocol()).thenReturn(this.protocolVersion);
    Mockito.when(request.getRequestURI()).thenReturn(this.uriString);

    Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headers));
    for (Header h : headers) {
        List<String> hresult = new ArrayList<String>();
        hresult.add(h.getValue());
        Mockito.when(request.getHeaders(h.getName())).thenReturn(Collections.enumeration(hresult));
        Mockito.when(request.getHeader(h.getName())).thenReturn(h.getValue());
    }

    if (session == null) {
        Mockito.when(request.getSession()).thenReturn(null);
    } else {
        HttpSession sessionMock = Mockito.mock(HttpSession.class);
        Mockito.when(request.getSession()).thenReturn(sessionMock);
    }
    return request;
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01139.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;/* ww  w . j a v a 2s  .com*/
                    flag = false;
                }
            }
        }
    }

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

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

    try {
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        // Prepare the cipher to encrypt
        java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic();
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey);

        // 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 (java.security.NoSuchProviderException 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);
    }
    response.getWriter()
            .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
}

From source file:org.ambraproject.action.FeedbackAction.java

@SuppressWarnings("unchecked")
public Map<String, String> getUserSessionAttributes() {
    final Map<String, String> headers = new LinkedHashMap<String, String>();
    final HttpServletRequest request = ServletActionContext.getRequest();

    {/*from w  w w .  j  a v  a 2s. c om*/
        final Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headerName = (String) headerNames.nextElement();
            final List<String> headerValues = EnumerationUtils.toList(request.getHeaders(headerName));
            headers.put(headerName, StringUtils.join(headerValues.iterator(), ","));
        }
    }

    headers.put("server-name", request.getServerName() + ":" + request.getServerPort());
    headers.put("remote-addr", request.getRemoteAddr());
    headers.put("local-addr", request.getLocalAddr() + ":" + request.getLocalPort());

    /*
     * Keeping this in case more values get passed from the client other than just the visible form
     * fields
     */
    {
        final Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            final String paramName = (String) parameterNames.nextElement();
            final String[] paramValues = request.getParameterValues(paramName);
            headers.put(paramName, StringUtils.join(paramValues, ","));
        }
    }

    return headers;
}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

private void populateHeaders(HttpServletRequest request, MessageBuilder<?> builder) {
    Enumeration<?> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration<?> headerEnum = request.getHeaders(headerName);
            if (headerEnum != null) {
                List<Object> headers = new ArrayList<Object>();
                while (headerEnum.hasMoreElements()) {
                    headers.add(headerEnum.nextElement());
                }/*from   w w  w.j  av  a  2 s  .co  m*/
                if (headers.size() == 1) {
                    builder.setHeader(headerName, headers.get(0));
                } else if (headers.size() > 1) {
                    builder.setHeader(headerName, headers);
                }
            }
        }
    }
    builder.setHeader(HttpHeaders.REQUEST_URL, request.getRequestURL().toString());
    builder.setHeader(HttpHeaders.REQUEST_METHOD, request.getMethod());
    builder.setHeader(HttpHeaders.USER_PRINCIPAL, request.getUserPrincipal());
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private Map<String, String> getRequestHeaders(HttpServletRequest request) {
    Map<String, String> requestHeaders = new HashMap<String, String>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerKey = headerNames.nextElement();
        if (!headerKey.equalsIgnoreCase("Accept-Encoding") && !headerKey.equalsIgnoreCase("Host")) { //Encoding doesnt work???
            String headerValue = StringUtils.join(Collections.list(request.getHeaders(headerKey)), ",");
            requestHeaders.put(headerKey, headerValue);
        }/*from w  w  w.  ja v  a2s.  c  o  m*/
    }
    return requestHeaders;
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01138.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;// ww  w .  j  a  va2 s.c  om
                    flag = false;
                }
            }
        }
    }

    String bar = new Test().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", "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 (java.security.NoSuchProviderException 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.lang.String) executed");
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest02001.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  w  w .  j av  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 = doSomething(request, param);

    float rand = new java.util.Random().nextFloat();
    String rememberMeKey = Float.toString(rand).substring(2); // Trim off the 0. at the front.

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

    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextFloat() executed");
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00249.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 w  w . ja v a  2  s . c  o m*/

        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 = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        long l = java.security.SecureRandom.getInstance("SHA1PRNG").nextLong();
        String rememberMeKey = Long.toString(l);

        String user = "SafeLogan";
        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.nextLong() - TestCase");
        throw new ServletException(e);
    }
    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextLong() executed");

}

From source file:com.adito.vfs.webdav.DAVServlet.java

private void debugRequest(HttpServletRequest req) {
    if (SystemProperties.get("adito.webdav.debug", "false").equalsIgnoreCase("true")) {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String header = (String) e.nextElement();
            for (Enumeration e2 = req.getHeaders(header); e2.hasMoreElements();) {
                log.info(header + ": " + (String) e2.nextElement());
            }//from  w  w  w  . j av  a2 s.co  m
        }
    }

    if (log.isDebugEnabled())
        log.debug("Processing " + req.getMethod() + " " + req.getPathInfo());
}