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.apache.shindig.gadgets.servlet.ServletUtilTest.java

@Test
public void testFromHttpServletRequest() throws Exception {
    HttpServletRequest original = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(original.getScheme()).andReturn("https");
    EasyMock.expect(original.getServerName()).andReturn("www.example.org");
    EasyMock.expect(original.getServerPort()).andReturn(444);
    EasyMock.expect(original.getRequestURI()).andReturn("/path/foo");
    EasyMock.expect(original.getQueryString()).andReturn("one=two&three=four");
    Vector<String> headerNames = new Vector<String>();
    headerNames.add("Header1");
    headerNames.add("Header2");
    EasyMock.expect(original.getHeaderNames()).andReturn(headerNames.elements());
    EasyMock.expect(original.getHeaders("Header1")).andReturn(makeEnumeration("HVal1", "HVal3"));
    EasyMock.expect(original.getHeaders("Header2")).andReturn(makeEnumeration("HVal2", "HVal4"));
    EasyMock.expect(original.getMethod()).andReturn("post");
    final ByteArrayInputStream bais = new ByteArrayInputStream("post body".getBytes());
    ServletInputStream sis = new ServletInputStream() {
        @Override/* w  w w. j a v a  2s  . co m*/
        public int read() throws IOException {
            return bais.read();
        }
    };
    EasyMock.expect(original.getInputStream()).andReturn(sis);
    EasyMock.expect(original.getRemoteAddr()).andReturn("1.2.3.4");

    EasyMock.replay(original);
    HttpRequest request = ServletUtil.fromHttpServletRequest(original);
    EasyMock.verify(original);

    assertEquals(Uri.parse("https://www.example.org:444/path/foo?one=two&three=four"), request.getUri());
    assertEquals(3, request.getHeaders().size());
    assertEquals("HVal1", request.getHeaders("Header1").get(0));
    assertEquals("HVal3", request.getHeaders("Header1").get(1));
    assertEquals("HVal2", request.getHeaders("Header2").get(0));
    assertEquals("HVal4", request.getHeaders("Header2").get(1));
    assertEquals("post", request.getMethod());
    assertEquals("post body", request.getPostBodyAsString());
    assertEquals("1.2.3.4", request.getParam(ServletUtil.REMOTE_ADDR_KEY));
}

From source file:com.sdl.odata.controller.AbstractODataController.java

/**
 * Converts an {@code HttpServletRequest} to an {@code ODataRequest}.
 *
 * @param servletRequest The {@code HttpServletRequest}.
 * @return An {@code ODataRequest} containing the request information.
 * @throws java.io.IOException If an I/O error occurs.
 *///from ww  w. jav a 2s .  c  om
private ODataRequest buildODataRequest(HttpServletRequest servletRequest) throws IOException {
    ODataRequest.Builder builder = new ODataRequest.Builder();

    builder.setMethod(ODataRequest.Method.valueOf(servletRequest.getMethod()));

    // Unfortunately, HttpServletRequest makes it difficult to get the full URI
    StringBuilder sb = getRequestURL(servletRequest);
    String queryString = servletRequest.getQueryString();
    if (!isNullOrEmpty(queryString)) {
        sb.append('?').append(queryString);
    }
    builder.setUri(sb.toString());

    // Unfortunately, HttpServletRequest has a very old-style API to iterate the headers
    Enumeration e = servletRequest.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = servletRequest.getHeader(name);
        builder.setHeader(name, value);
    }

    // Read the request body
    InputStream in = servletRequest.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int count;
    byte[] buffer = new byte[BUFFER_SIZE];
    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }
    builder.setBody(out.toByteArray());

    return builder.build();
}

From source file:org.overlord.gadgets.web.server.servlets.RestProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*  w w w .  j a v  a 2  s  . com*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Proxy inbound endpoint: " + req.getRequestURI());
    // Connect to proxy URL.
    String urlStr = getProxyUrl(req);
    String queryString = req.getQueryString();
    if (queryString != null) {
        urlStr = urlStr + "?" + queryString;
    }
    System.out.println("Proxying to: " + urlStr);
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    // Proxy all of the request headers.
    Enumeration<?> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = String.valueOf(headerNames.nextElement());
        Enumeration<?> headerValues = req.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            String headerValue = String.valueOf(headerValues.nextElement());
            conn.addRequestProperty(headerName, headerValue);
        }
    }

    // Handle authentication
    RestProxyAuthProvider authProvider = getAuthProvider();
    if (authProvider != null) {
        authProvider.provideAuthentication(conn);
    }

    // Now connect and proxy the response.
    InputStream proxyUrlResponseStream = null;
    try {
        proxyUrlResponseStream = conn.getInputStream();
        resp.setStatus(conn.getResponseCode());
        // Proxy the response headers
        for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
            String respHeaderName = entry.getKey();
            if (respHeaderName != null && !respHeaderName.equalsIgnoreCase("transfer-encoding")) {
                for (String respHeaderValue : entry.getValue()) {
                    resp.addHeader(respHeaderName, respHeaderValue);
                }
            }
        }

        // Proxy the response body.
        IOUtils.copy(proxyUrlResponseStream, resp.getOutputStream());
    } finally {
        IOUtils.closeQuietly(proxyUrlResponseStream);
        conn.disconnect();
    }
}

From source file:httpmultiplexer.httpproxy.ProxyServlet.java

/**
 * Copy request headers from the servlet client to the proxy request.
 *//*from w ww.  jav a2s . co m*/
protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    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;
        }
        if (hopByHopHeaders.containsHeader(headerName)) {
            continue;
        }

        Enumeration headers = servletRequest.getHeaders(headerName);
        while (headers.hasMoreElements()) {//sometimes more than one value
            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 = getTargetHost(servletRequest);
                headerValue = host.getHostName();
                if (host.getPort() != -1) {
                    headerValue += ":" + host.getPort();
                }
            }
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest.java

public void applyRequest(final HttpServletRequest request) {
    setClientIP(request.getRemoteAddr());
    setPath(request.getPathInfo());/* w  w  w.j  a  v  a  2s. c o m*/
    setQueryString(request.getQueryString());
    setHostname(request.getServerName());
    setRequestedUrl(request.getRequestURL().toString());
    setUri(request.getRequestURI());

    final String xmm = request.getHeader(X_MM_CLIENT_IP);
    final String fip = request.getParameter(FAKE_IP);

    if (xmm != null) {
        setClientIP(xmm);
    } else if (fip != null) {
        setClientIP(fip);
    }

    final Map<String, String> headers = new HashMap<String, String>();
    final Enumeration<?> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = (String) headerNames.nextElement();
        final String value = request.getHeader(name);
        headers.put(name, value);
    }
    setHeaders(headers);
    secure = request.isSecure();
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@SuppressWarnings("unchecked")
@Override//from  www  .j  av a2s  .c om
public void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String method = req.getMethod();
    if (LOGGER.isDebugEnabled()) {
        List<String> headers = Collections.list((Enumeration<String>) req.getHeaderNames());
        LOGGER.debug("Command : {}, Appel : {}, headers {}",
                new Object[] { method, req.getRequestURI(), headers });
    }

    if (!authent(req)) {
        resp.addHeader("WWW-Authenticate", "BASIC realm=\"Noweco CalDAV\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    String requestURI = req.getRequestURI();
    if (requestURI.length() != 0 && requestURI.charAt(0) != '/') {
        // unknown relative URI
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    try {
        if (METHOD_PROPFIND.equals(method)) {
            doPropfind(req, resp);
        } else if (METHOD_REPORT.equals(method)) {
            doReport(req, resp);
        } else {
            super.service(req, resp);
        }
    } catch (Throwable e) {
        LOGGER.error("Unexpected throwable", e);
    }
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

private void debug(HttpServletRequest request, String activity) {
    if (LOG.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        PrintWriter out = new PrintWriter(writer);
        out.println(activity + " - " + request.getRequestURL());
        out.println("\tMethod: " + request.getMethod());

        @SuppressWarnings("rawtypes")
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement().toString();
            String headerValue = request.getHeader(headerName);
            headerValue = headerFilter.processRequestHeader(headerName, headerValue);
            if (headerValue != null) {
                out.println("\theader: " + headerName + ": " + headerValue);
            }/*w w  w. j  av  a2s .co m*/
        }
        out.close();
        LOG.debug(writer.toString());
    }
}

From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java

@Override
public void beforeHandler(ActionHandler actionHandler) {
    if (!this.monitor) { // ?
        return;//  w  w w  .j  a  va  2 s.c  o  m
    }
    Long userId = OnlineUserManager.getUserId();
    if (userId == null) { // 
        return;
    }
    HttpServletRequest request = actionHandler.getRequest();

    String url = request.getRequestURI();

    // ?
    if (!logInfoRemoteService.canRecord(url)) {
        return;
    }

    // 
    LogInfoDto domain = new LogInfoDto();
    domain.setRequestUrl(url);

    // ??
    String cnName = OnlineUserManager.getCnName();
    domain.setUserName(cnName);

    String remoteAddr = request.getRemoteAddr();
    domain.setRemoteAddr(remoteAddr);

    // request headers
    JSONObject jsonObj = new JSONObject();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerValues = request.getHeaders(headerName);
        StringBuilder sb = new StringBuilder();
        while (headerValues.hasMoreElements()) {
            sb.append(headerValues.nextElement());
            sb.append(",");
        }
        if (sb.length() > 0) {
            sb.substring(0, sb.length() - 1);
        }
        jsonObj.put(headerName, sb.toString());
    }
    domain.setRequestHeader(jsonObj.toString());

    // request data
    jsonObj = new JSONObject();
    Map<String, String[]> paramMap = request.getParameterMap();
    if (MapUtils.isNotEmpty(paramMap)) {
        Set<Entry<String, String[]>> set = paramMap.entrySet();
        for (Entry<String, String[]> entry : set) {
            String key = entry.getKey();
            String value = ArrayUtils.toString(entry.getValue());
            jsonObj.put(key, value);
        }
    }
    domain.setRequestData(jsonObj.toString());
    threadLocal.set(domain);

}

From source file:org.eiichiro.bootleg.AbstractRequest.java

/**
 * Returns the Web endpoint method parameter from HTTP request header.
 * /* w w  w .  j  a v  a2  s.  c o m*/
 * @param type The parameter type.
 * @param name The parameter name.
 * @return The Web endpoint method parameter from the HTTP request header.
 */
protected Object header(Type type, String name) {
    return parameter(type, name, new Function<String, Object>() {

        public Object apply(String name) {
            return context.request().getHeader(name);
        }

    }, new Function<String, Collection<Object>>() {

        @SuppressWarnings("unchecked")
        public Collection<Object> apply(String name) {
            HttpServletRequest request = context.request();
            Map<String, Object> map = new TreeMap<String, Object>();

            for (Object object : Collections.list(request.getHeaderNames())) {
                String key = (String) object;

                if (key.startsWith(name + "[")) {
                    map.put(key, request.getHeader(key));
                }
            }

            return (map.isEmpty()) ? null : map.values();
        }

    });
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from  w ww . j a  va 2  s  .  com*/
 *
 * @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
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod 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 = getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}