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:io.mapzone.controller.vm.http.HttpRequestForwarder.java

/** Copy request headers from the servlet client to the proxy request. */
protected void copyRequestHeaders(HttpServletRequest servletRequest) {
    Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String headerName = (String) enumerationOfHeaderNames.nextElement();
        // Instead the content-length is effectively set via InputStreamEntity
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        }//from  ww  w .j ava2s.  c  o  m
        if (hopByHopHeaders.containsHeader(headerName)) {
            log.debug("    Header: " + headerName + " ... skipped.");
            continue;
        }

        Enumeration headers = servletRequest.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String headerValue = (String) headers.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 (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
                HttpHost host = targetHost;
                headerValue = host.getHostName();
                if (host.getPort() != -1) {
                    headerValue += ":" + host.getPort();
                }
            }
            //
            else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) {
                headerValue = getRealCookie(headerValue);
            }
            proxyRequest.addHeader(headerName, headerValue);
            log.debug("    Header: " + headerName + " = " + headerValue);
        }
    }
}

From source file:com.apipulse.bastion.controllers.ApiController.java

@RequestMapping(value = "/api/admittance/{id}", produces = "application/json", method = RequestMethod.POST)
@ResponseBody/*from  ww w. j  a v  a 2s  .c  o  m*/
public String admittance(final @PathVariable String id, final HttpServletRequest request) throws IOException {
    final InputStream is = request.getInputStream();
    final String payload = IOUtils.toString(is);
    is.close();
    final StepMessage message = new StepMessage(payload);
    final HashMap<String, String> headers = new HashMap<String, String>();
    final Enumeration<String> eh = request.getHeaderNames();
    while (eh.hasMoreElements()) {
        final String headerName = eh.nextElement();
        headers.put(headerName, request.getHeader(headerName));
    }
    message.getContext().put("headers", headers);
    message.getContext().put("id", id);
    final String uuid = UUID.randomUUID().toString();
    message.getContext().put("uuid", uuid);
    BastionActors.getInstance().getHttpRouter().tell(message, null);
    return "{\"accepted\":true,\"id\":\"" + uuid + "\"}";
}

From source file:org.rhq.coregui.server.gwt.AbstractGWTServiceImpl.java

@SuppressWarnings("unchecked")
private void printHeaders(HttpServletRequest req) {
    // TODO: figure out why SESSION_NAME header and other GWT-specific headers are missing occasionally
    //       seems to only happen on polling for recent alerts when there is no user activity for a few minutes
    Enumeration<String> headerNames = req.getHeaderNames();
    log.trace(req.getRequestURL().toString());
    while (headerNames.hasMoreElements()) {
        log.trace("   " + headerNames.nextElement());
    }/*from  ww w. j  ava 2 s  .  c  om*/
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01167.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 ww  w .j a  v  a2  s  .  c o  m*/
                    flag = false;
                }
            }
        }
    }

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

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        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.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

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

/**
 * Build the request as defined in the current builder.
 * /*  w  ww.jav  a  2 s  .  c o  m*/
 * @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:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho//from  ww w. j  a  v a 2  s  . co  m
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}

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   ww w .j av  a2  s. c o m*/
        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:jp.co.opentone.bsol.linkbinder.view.exception.LinkBinderExceptionHandler.java

private void logRequest(HttpServletRequest req) {
    log.error("Requested: {} {}", req.getMethod(), req.getRequestURI());
    Enumeration<?> enm = req.getHeaderNames();
    log.error("Header:");
    while (enm.hasMoreElements()) {
        String name = (String) enm.nextElement();
        log.error("   {} = {}", name, req.getHeader(name));
    }/*  www  . ja v  a  2s. co m*/

    log.error(" Parameters:");
    @SuppressWarnings("unchecked")
    Map<String, String[]> parameterMap = req.getParameterMap();
    for (Map.Entry<String, String[]> e : parameterMap.entrySet()) {
        log.error("  {} = {}", e.getKey(), StringUtils.join(e.getValue()));
    }
}

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());
                }/*  ww  w.  java2 s  .c  o 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:org.jkcsoft.web.struts.http.HttpHelper.java

public static void logRequest(HttpServletRequest request, Object logCategory) {
    // quick reject
    if (!LogHelper.getLogger(logCategory).isDebugEnabled())
        return;//  w  ww.ja  v a 2  s .  co m

    StringBuilder sbMsg = new StringBuilder(100);
    appendLine(sbMsg, "");
    appendLine(sbMsg, "---------- Start Request Dump:");
    appendLine(sbMsg, "method [" + request.getMethod() + "]");
    appendLine(sbMsg, "servletPath [" + request.getServletPath() + "]");
    appendLine(sbMsg, "pathInfo [" + request.getPathInfo() + "]");
    appendLine(sbMsg, "queryString [" + request.getQueryString() + "]");

    Enumeration e = null;
    String name = null;

    appendLine(sbMsg, "-------------- Header Information");
    e = request.getHeaderNames();
    String header;
    while (e.hasMoreElements()) {
        header = (String) e.nextElement();
        appendLine(sbMsg, header + " [" + request.getHeader(header) + "]");
    }

    appendLine(sbMsg, "-------------- Parameter Information");

    e = request.getParameterNames();
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        String[] values = request.getParameterValues(name);
        String value = "";
        if (values.length > 1) {
            for (int inx = 0; inx < values.length; inx++) {
                value = value + values[inx] + ",";
            }
        } else {
            value = values[0];
        }
        if (name.startsWith("password")) {
            value = "******";
        }
        appendLine(sbMsg, name + " [" + value + "]");
    }

    appendLine(sbMsg, "-------------- Attribute Information");
    e = request.getAttributeNames();
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        appendLine(sbMsg, name + " [" + request.getAttribute(name).toString() + "]");
    }

    appendLine(sbMsg, "---------- End Request Dump:");
    LogHelper.debug(logCategory, sbMsg);
}