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.springframework.boot.ops.trace.WebRequestTraceFilter.java

protected Map<String, Object> getTrace(HttpServletRequest request) {

    Map<String, Object> map = new LinkedHashMap<String, Object>();
    Enumeration<String> names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = names.nextElement();
        List<String> values = Collections.list(request.getHeaders(name));
        Object value = values;//from ww w .  j a va  2 s. c o  m
        if (values.size() == 1) {
            value = values.get(0);
        } else if (values.isEmpty()) {
            value = "";
        }
        map.put(name, value);

    }
    Map<String, Object> trace = new LinkedHashMap<String, Object>();
    trace.put("method", request.getMethod());
    trace.put("path", request.getRequestURI());
    trace.put("headers", map);
    return trace;
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00258.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("BenchmarkTest00258");

    if (headers != null && headers.hasMoreElements()) {
        param = headers.nextElement(); // just grab first element
    }// w w  w.  ja  v a2 s . 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 = 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
    //       };
    java.security.SecureRandom random = new java.security.SecureRandom();
    byte[] iv = random.generateSeed(8); // DES requires 8 byte keys

    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:guru.nidi.raml.doc.servlet.MirrorServlet.java

private void headers(HttpServletRequest req, PrintWriter out) {
    out.println("headers");
    final Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = headerNames.nextElement();
        out.print(name + ": ");
        final Enumeration<String> headers = req.getHeaders(name);
        while (headers.hasMoreElements()) {
            out.print("'" + headers.nextElement() + "', ");
        }// ww w. j  av  a 2 s .c  om
        out.println();
    }
    out.println();
}

From source file:org.niord.proxy.web.ETagServletFilter.java

/**
 * Inspired by javax.ws.rs.core.Request.evaluatePreconditions().
 * Evaluate request preconditions based on the passed in value.
 *
 * @param etag an ETag for the current state of the resource
 * @return if the preconditions are met.
 *///from  w w  w .  j a v a2s.  co  m
private boolean evaluatePreconditions(EntityTag etag, HttpServletRequest request,
        HttpServletResponse response) {
    if (etag == null) {
        return false;
    }

    response.setHeader(HEADER_ETAG, etag.toString());

    boolean match = Collections.list(request.getHeaders(HEADER_IF_NONE_MATCH)).stream().map(this::trimEtagValue) // Strip any "-gzip" suffix added by Apache modules
            .anyMatch(val -> val.equals(etag.toString()));

    if (match) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }

    // No matching etag headers
    return false;
}

From source file:org.apache.camel.component.gae.http.GHttpTestServlet.java

@SuppressWarnings("unchecked")
@Override/*from   w  ww. j a  v a 2s  .c  o  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Set default response code
    resp.setStatus(200);
    // Copy headers from request to response
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headers = req.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String headerValue = headers.nextElement();
            resp.addHeader(headerName, headerValue);
            // Set custom response code
            // if requested by client
            if (headerName.equals("code")) {
                resp.setStatus(Integer.parseInt(headerValue));
            }
        }
    }

    // add some special response headers
    resp.addHeader("testUrl", req.getRequestURL().toString());
    resp.addHeader("testMethod", req.getMethod().toString());
    if (req.getQueryString() != null) {
        resp.addHeader("testQuery", req.getQueryString());
    }

    // Copy body from request to response
    resp.getWriter().println(IOUtils.toString(req.getInputStream()));
    resp.getWriter().flush();
}

From source file:com.ibm.util.merge.web.rest.servlet.RequestData.java

private Map<String, List<String>> readHeaderValues(HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    Map<String, List<String>> headerValues = new HashMap<>();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> values = request.getHeaders(headerName);
        List<String> vals = new ArrayList<>();
        while (values.hasMoreElements()) {
            String val = values.nextElement();
            vals.add(val);
        }//from   www .j  a v a 2  s  .co  m
    }
    return headerValues;
}

From source file:guru.nidi.raml.doc.servlet.MirrorServlet.java

private Map<String, Object> headers(HttpServletRequest req) {
    final Map<String, Object> map = new HashMap<>();
    final Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = headerNames.nextElement();
        final List<String> values = new ArrayList<>();
        final Enumeration<String> headers = req.getHeaders(name);
        while (headers.hasMoreElements()) {
            values.add(headers.nextElement());
        }// w  ww.j a v a  2 s  . c o  m
        map.put(name, values);
    }
    return map;
}

From source file:org.springframework.boot.actuate.trace.WebRequestTraceFilter.java

private Map<String, Object> getRequestHeaders(HttpServletRequest request) {
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        List<String> values = Collections.list(request.getHeaders(name));
        Object value = values;/*from  ww  w.  j  av a 2 s .c om*/
        if (values.size() == 1) {
            value = values.get(0);
        } else if (values.isEmpty()) {
            value = "";
        }
        headers.put(name, value);
    }
    return headers;
}

From source file:edu.gatech.i3l.fhir.jpa.provider.BaseJpaProvider.java

public void startRequest(HttpServletRequest theRequest) {
    if (theRequest == null) {
        return;//  w  w  w.  j  a va 2  s  .  co  m
    }

    Set<String> headerNames = new TreeSet<String>();
    for (Enumeration<String> enums = theRequest.getHeaderNames(); enums.hasMoreElements();) {
        headerNames.add(enums.nextElement());
    }
    ourLog.debug("Request headers: {}", headerNames);

    Enumeration<String> forwardedFors = theRequest.getHeaders("x-forwarded-for");
    StringBuilder b = new StringBuilder();
    for (Enumeration<String> enums = forwardedFors; enums.hasMoreElements();) {
        if (b.length() > 0) {
            b.append(" / ");
        }
        b.append(enums.nextElement());
    }

    String forwardedFor = b.toString();
    String ip = theRequest.getRemoteAddr();
    if (StringUtils.isBlank(forwardedFor)) {
        org.slf4j.MDC.put(REMOTE_ADDR, ip);
        ourLog.debug("Request is from address: {}", ip);
    } else {
        org.slf4j.MDC.put(REMOTE_ADDR, forwardedFor);
        ourLog.debug("Request is from forwarded address: {}", forwardedFor);
    }

    String userAgent = StringUtils.defaultString(theRequest.getHeader("user-agent"));
    org.slf4j.MDC.put(REMOTE_UA, userAgent);

}

From source file:com.idega.core.cache.filter.Filter.java

/**
 * Checks if request contains the header value.
 *///from  w  w  w .  j  a  v  a  2  s. co  m
private boolean headerContains(final HttpServletRequest request, final String header, final String value) {

    logRequestHeaders(request);

    final Enumeration accepted = request.getHeaders(header);
    while (accepted.hasMoreElements()) {
        final String headerValue = (String) accepted.nextElement();
        if (headerValue.indexOf(value) != -1) {
            return true;
        }
    }
    return false;
}