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.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;/*from  w w  w  . j a va2 s. c  o m*/
                    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.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

/**
 * Download link and have it be the response.
 * @param req the http request//from  w  ww  .  j  a  v a2 s .c o  m
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c,
        String proxyHost) throws IOException {
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false);
    HttpClientParams params = new HttpClientParams();
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    HttpClient client = new HttpClient(params);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    HostConfiguration config = new HostConfiguration();
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: " + localAddress.toString());
    }
    config.setLocalAddress(localAddress);
    HttpMethod method = new GetMethod(uri.getEscapedURI());
    @SuppressWarnings("unchecked")
    Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (passThroughHeaders.contains(name)) {
            String value = req.getHeader(name);
            LOG.debug("REQ HEADER: " + name + " : " + value);
            method.setRequestHeader(name, value);
        }
    }

    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        resp.setStatus(client.executeMethod(config, method));
        for (Header header : method.getResponseHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:grails.plugin.cache.web.filter.AbstractFilter.java

protected void logRequestHeaders(final HttpServletRequest request) {
    if (!log.isDebugEnabled()) {
        return;/*from  w  w w.  j  a  v  a  2 s. c o  m*/
    }

    Map<String, String> headers = new HashMap<String, String>();
    StringBuilder logLine = new StringBuilder("Request Headers");
    for (Enumeration<String> enumeration = request.getHeaderNames(); enumeration.hasMoreElements();) {
        String name = enumeration.nextElement();
        String headerValue = request.getHeader(name);
        headers.put(name, headerValue);
        logLine.append(": ").append(name).append(" -> ").append(headerValue);
    }
    log.debug(logLine.toString());
}

From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java

protected Map<String, String> getHeaders(HttpServletRequest request) {
    Map<String, String> headers = new HashMap<String, String>();
    Enumeration<?> enumeration = request.getHeaderNames();
    while (enumeration.hasMoreElements()) {
        String name = (String) enumeration.nextElement();
        String value = request.getHeader(name);
        headers.put(name, value);/*w  w  w  .  j a va2s . c  o m*/
    }

    return headers;
}

From source file:org.sakaiproject.sdata.tool.SnoopHandler.java

/**
 * @param request//from w w  w.j av  a 2  s . c  o m
 */
private void snoopRequest(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder("SData Request :").append(request);
    sb.append("\n\tRequest Path :").append(request.getPathInfo());
    sb.append("\n\tMethod :").append(request.getMethod());
    for (Enumeration<?> hnames = request.getHeaderNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tHeader :").append(name).append("=[").append(request.getHeader(name)).append("]");
    }
    for (Enumeration<?> hnames = request.getParameterNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tParameter :").append(name).append("=[").append(request.getParameter(name)).append("]");
    }
    if (request.getCookies() != null) {
        for (Cookie c : request.getCookies()) {
            sb.append("\n\tCookie:");
            sb.append("name[").append(c.getName());
            sb.append("]path[").append(c.getPath());
            sb.append("]value[").append(c.getValue());
        }
    }
    sb.append("]");
    for (Enumeration<?> hnames = request.getAttributeNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tAttribute :").append(name).append("=[").append(request.getAttribute(name)).append("]");
    }
    HttpSession session = request.getSession();
    sb.append("\n\tUser :").append(request.getRemoteUser());
    if (session != null) {
        sb.append("\n\tSession ID :").append(session.getId());
        for (Enumeration<?> hnames = session.getAttributeNames(); hnames.hasMoreElements();) {
            String name = (String) hnames.nextElement();
            sb.append("\n\tSession Attribute :").append(name).append("=[").append(session.getAttribute(name))
                    .append("]");
        }

    } else {
        sb.append("\n\tNo Session");
    }

    LOG.info(sb.toString());
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method,
        HttpState state) throws IOException, ServiceException {
    // create an HTTP client with the same cookies
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    String hostname = method.getURI().getHost();
    boolean hasZMAuth = hasZimbraAuthCookie(state);
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth)
                continue;
            state.addCookie(//ww  w.  java 2s.c o  m
                    new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false));
        }
    }
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (state != null)
        client.setState(state);

    int hopcount = 0;
    for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) {
        String hname = (String) enm.nextElement(), hlc = hname.toLowerCase();
        if (hlc.equals("x-zimbra-hopcount"))
            try {
                hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0);
            } catch (NumberFormatException e) {
            }
        else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization"))
            method.addRequestHeader(hname, req.getHeader(hname));
    }
    if (hopcount >= MAX_PROXY_HOPCOUNT)
        throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req));
    method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1));
    if (method.getRequestHeader("X-Zimbra-Orig-Url") == null)
        method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString());
    String ua = req.getHeader("User-Agent");
    if (ua != null)
        method.setRequestHeader("User-Agent", ua);

    // dispatch the request and copy over the results
    int statusCode = -1;
    for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) {
        statusCode = HttpClientUtil.executeMethod(client, method);
    }
    if (statusCode == -1) {
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached");
        return;
    } else if (statusCode >= 300) {
        resp.sendError(statusCode, method.getStatusText());
        return;
    }

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String hname = headers[i].getName(), hlc = hname.toLowerCase();
        if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-"))
            resp.addHeader(hname, headers[i].getValue());
    }
    InputStream responseStream = method.getResponseBodyAsStream();
    if (responseStream == null || resp.getOutputStream() == null)
        return;
    ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false);
}

From source file:com.google.acre.servlet.ProxyPassServlet.java

/**
 * Retreives all of the headers from the servlet request and sets them on
 * the proxy request/*from  ww w. j a  va2 s . c o m*/
 * 
 * @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
 */
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,
        HttpRequestBase 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 = this.metawebAPIHostAndPort;
            }
            // Set the same header on the proxy request
            httpMethodProxyRequest.addHeader(stringHeaderName, stringHeaderValue);
        }
    }
}

From source file:de.undercouch.gradle.tasks.download.HeadersTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    //echo X-* headers back in response body
    ContextHandler echoHeadersHandler = new ContextHandler("/" + ECHO_HEADERS) {
        @Override/*from ww  w . j  ava2  s  .c o m*/
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.write(HEADERS + "\n");
            @SuppressWarnings("unchecked")
            Enumeration<String> headerNames = (Enumeration<String>) request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                if (name.startsWith("X-")) {
                    rw.write(String.format("  %s: %s\n", name, request.getHeader(name)));
                }
            }
            rw.close();
        }
    };
    return new Handler[] { echoHeadersHandler };
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void copyRequestHeaders(HttpServletRequest request, HttpMethodBase method) {

    Enumeration properties = request.getHeaderNames();
    while (properties.hasMoreElements()) {
        String propertyName = (String) properties.nextElement();
        String propertyNameToLower = propertyName.toLowerCase();
        if (!ignoreRequestHeaders.contains(propertyNameToLower) && !(method instanceof GetMethod
                && ignorePostToGetRequestHeaders.contains(propertyNameToLower))) {
            Enumeration values = request.getHeaders(propertyName);
            while (values.hasMoreElements()) {
                String property = (String) values.nextElement();
                // System.out.println(propertyName + ":" + property);
                method.setRequestHeader(propertyName, property);
            }/*from  www.  j a  va  2  s. c o  m*/
        }
    }

    // TODO consider what happens if the host is different after a redirect...
    // Conditional cookie transfer
    try {
        org.apache.commons.httpclient.URI uri = method.getURI();
        if (uri != null) {
            String host = uri.getHost();
            if (host != null) {
                if (host.equals(request.getHeader("host"))) {
                    String cookie = request.getHeader("cookie");
                    if (cookie != null)
                        method.setRequestHeader("cookie", cookie);
                }
            } else {
                log.warn("host is null for uri " + uri);
            }
        } else {
            log.warn("uri is null for method " + method);
        }
    } catch (URIException e) {
        log.warn(e, e);
    }

}