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.atricore.idbus.kernel.main.mediation.camel.component.logging.HttpLogMessageBuilder.java

public String buildLogMessage(Message message) {

    HttpExchange httpEx = (HttpExchange) message.getExchange();

    if (message instanceof HttpMessage) {

        HttpServletRequest hreq = httpEx.getRequest();

        StringBuffer logMsg = new StringBuffer(1024);

        logMsg.append("<http-request method=\"").append(hreq.getMethod()).append("\"").append("\n\t url=\"")
                .append(hreq.getRequestURL()).append("\"").append("\n\t content-type=\"")
                .append(hreq.getContentType()).append("\"").append("\n\t content-length=\"")
                .append(hreq.getContentLength()).append("\"").append("\n\t content-encoding=\"")
                .append(hreq.getCharacterEncoding()).append("\"").append(">");

        Enumeration headerNames = hreq.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration headers = hreq.getHeaders(headerName);

            logMsg.append("\n\t<header name=\"").append(headerName).append("\">");

            while (headers.hasMoreElements()) {
                String headerValue = (String) headers.nextElement();
                logMsg.append("\n\t\t<header-value>").append(headerValue).append("</header-value>");
            }/*from ww w .ja  va2  s.  c  om*/

            logMsg.append("\n\t</header>");

        }

        Enumeration params = hreq.getParameterNames();
        while (params.hasMoreElements()) {
            String param = (String) params.nextElement();
            logMsg.append("\n\t<parameter name=\"").append(param).append("\">");
            logMsg.append("\n\t\t\t<value>").append(hreq.getParameter(param)).append("</value>");
            logMsg.append("\n\t</parameter>");
        }

        logMsg.append("\n</http-request>");

        return logMsg.toString();
    } else {
        StringBuffer logMsg = new StringBuffer(1024);
        logMsg.append("\t<http-response />");
        return logMsg.toString();
    }
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java

@SuppressWarnings("unchecked")
protected HttpHeaders getHeaders(HttpServletRequest request) {
    HttpHeaders httpHeaders = new HttpHeaders();

    Enumeration<String> headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        httpHeaders.put(headerName, Collections.list(request.getHeaders(headerName)));
    }/* w  w w. j av a 2 s.co  m*/

    return httpHeaders;
}

From source file:org.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java

private String constructForwardableURL(HttpServletRequest httpRequest) {
    String xForwardedProto = "";
    String xForwardedHost = "";
    String xForwardedContext = "";
    Enumeration<?> names = httpRequest.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration<?> values = httpRequest.getHeaders(name);
        String value = "";
        if (values != null) {
            while (values.hasMoreElements()) {
                value = (String) values.nextElement();
            }//from   w w w.  j ava2 s. com
        }
        if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) {
            if (name.equalsIgnoreCase("x-forwarded-proto")) {
                xForwardedProto = value;
            } else if (name.equalsIgnoreCase("x-forwarded-host")) {
                xForwardedHost = value;
            } else if (name.equalsIgnoreCase("x-forwarded-context")) {
                xForwardedContext = value;
            }
        }
    }
    String xForwardedURL = "";
    if (StringUtils.trimToNull(xForwardedProto) != null && StringUtils.trimToNull(xForwardedHost) != null
            && StringUtils.trimToNull(xForwardedContext) != null) {
        xForwardedURL = xForwardedProto + "://" + xForwardedHost + xForwardedContext + PROXY_RANGER_URL_PATH
                + httpRequest.getRequestURI();
    }
    return xForwardedURL;
}

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/*from   w w w  .  j  a va2s . com*/
        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: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   w w  w.  j a  v  a  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);
    }

}

From source file:com.imaginary.home.cloud.api.RestApi.java

private @Nonnull Map<String, Object> parseHeaders(@Nonnull HttpServletRequest req) throws RestException {
    @SuppressWarnings("unchecked")
    Enumeration<String> names = (Enumeration<String>) req.getHeaderNames();
    HashMap<String, Object> headers = new HashMap<String, Object>();

    while (names.hasMoreElements()) {
        String name = names.nextElement();

        //noinspection unchecked
        headers.put(name, getHeader(name, req.getHeaders(name)));
    }//from   ww w  .  j av  a 2  s .c om
    return headers;
}

From source file:de.goldbachinteractive.gbi.redirecthandler.client.Error404HandlerServlet.java

/**
 * Requests a redirect processor for redirect (with the original request as
 * parameter r).//from w ww .  j  a v a  2 s .c o  m
 * 
 * @param redirectProcessorUrl
 *            The redirect processor to use (with the original request as
 *            parameter r).
 * @param httpClient
 *            The HttpClient to execute the request.
 * @param req
 *            The original request.
 * @param resp
 *            The original response.
 * @param timeout
 *            The timeout for request.
 * @return True, if redirected or false, if not.
 */
private boolean redirectRequest(String redirectProcessorUrl, CloseableHttpClient httpClient,
        HttpServletRequest req, HttpServletResponse resp, int timeout) {
    try {
        HttpGet httpGet = new HttpGet(redirectProcessorUrl);
        httpGet.setConfig(RequestConfig.custom().setRedirectsEnabled(false).setSocketTimeout(timeout).build());

        // copy all headers from original request
        final Enumeration<String> headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String header = headers.nextElement();
            if (header.equalsIgnoreCase("host")) {
                continue;
            }
            final Enumeration<String> values = req.getHeaders(header);
            while (values.hasMoreElements()) {
                final String value = values.nextElement();
                httpGet.setHeader(header, value);
            }
        }

        // to remove host header
        if (httpGet.getHeaders("host") != null) {
            httpGet.removeHeaders("host");
        }
        // to add X-gbi-key header
        httpGet.setHeader(GBI_KEY_HEADER, xGbiKey);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        logger.info(String.format("status code :%d", statusCode));
        if (statusCode >= 300 && statusCode < 400) {
            // if status code is 3XX, the Location header of response is set
            String location = response.getHeaders("Location")[0].getValue();
            resp.sendRedirect(location);
            return true;
        }
    } catch (Exception e) {
        logger.error(String.format("error while trying to request redirect:[%s]", e.getMessage()), e);
    }
    return false;
}

From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java

public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
    Assert.notNull(request, "Request required");
    Assert.notNull(portResolver, "PortResolver required");

    // Cookies//from ww w .  j a  va2  s .co m
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            this.addCookie(cookies[i]);
        }
    }

    // Headers
    Enumeration names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = request.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            this.addHeader(name, value);
        }
    }

    // Locales
    Enumeration locales = request.getLocales();

    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        this.addLocale(locale);
    }

    // Parameters
    Map parameters = request.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();

    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        Object o = parameters.get(paramName);
        if (o instanceof String[]) {
            String[] paramValues = (String[]) o;
            this.addParameter(paramName, paramValues);
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("ServletRequest.getParameterMap() returned non-String array");
            }
        }
    }

    // Primitives
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.serverPort = portResolver.getServerPort(request);
    this.requestURL = request.getRequestURL().toString();
    this.scheme = request.getScheme();
    this.serverName = request.getServerName();
    this.contextPath = request.getContextPath();
    this.servletPath = request.getServletPath();
}

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;
        }// w ww.  j a va  2s  . co  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:org.infoscoop.web.JsonProxyServlet.java

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String uid = (String) req.getSession().getAttribute("Uid");
    Map<String, String> params = getSingleParams(req.getParameterMap());

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    for (Enumeration names = req.getHeaderNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();

        List<String> vlist = new ArrayList<String>();
        headers.put(name, vlist);/*w  w w  . j ava2s.c  o  m*/
        for (Enumeration values = req.getHeaders(name); values.hasMoreElements();) {
            String value = (String) values.nextElement();
            vlist.add(value);
        }
    }

    JSONObject result;
    try {
        result = invokeJSONProxyRequest(uid, params, headers);
    } catch (Exception ex) {
        if (ex.getCause() != null)
            ex = (Exception) ex.getCause();

        log.error("", ex);

        throw new ServletException(ex);
    }

    byte[] body = ("throw 1; < don't be evil' >" + result.toString()).getBytes("UTF-8");

    resp.setStatus(200);
    resp.setHeader("Cache-Control", "no-cache");
    resp.setContentType("text/plain;charset=UTF-8");
    //      resp.setContentType("text/plain;charset=UTF-8");
    resp.setContentLength(body.length);
    resp.getOutputStream().write(body);
    resp.getOutputStream().flush();
}