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:be.milieuinfo.core.proxy.controller.ProxyServlet.java

/** Copy request headers from the servlet client to the proxy request. */
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;
        // 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 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 = URIUtils.extractHost(this.targetUri);
                headerValue = host.getHostName();
                if (host.getPort() != -1)
                    headerValue += ":" + host.getPort();
            }//  ww w .  j a va  2  s .  co m
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

/**
 * <p>/*from w  w  w . ja  va  2s.  c  om*/
 * This method calls the Fedora Access Subsystem to retrieve a MIME-typed
 * stream corresponding to the dissemination request.
 * </p>
 *
 * @param context
 *        The read only context of the request.
 * @param PID
 *        The persistent identifier of the Digital Object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The method name.
 * @param userParms
 *        An array of user-supplied method parameters.
 * @param asOfDateTime
 *        The version datetime stamp of the digital object.
 * @param response
 *        The servlet response.
 * @param request
 *        The servlet request.
 * @throws IOException
 *         If an error occurrs with an input or output operation.
 * @throws ServerException
 *         If an error occurs in the Access Subsystem.
 */
public void getDissemination(Context context, String PID, String sDefPID, String methodName,
        Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
        throws IOException, ServerException {
    ServletOutputStream out = null;
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime);
    out = response.getOutputStream();
    try {
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            response.setContentType(dissemination.getMIMEType());
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET  RESPONSE HEADER FROM ORIGINATING  PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}

From source file:net.oauth.signature.GoogleCodeCompatibilityTests.java

/**
 * tests compatibility of calculating the signature base string.
 *//*ww w.  j a  v  a 2 s. c o  m*/
@Test
public void testCalculateSignatureBaseString() throws Exception {
    final String baseUrl = "http://www.springframework.org/schema/security/";
    CoreOAuthProviderSupport support = new CoreOAuthProviderSupport() {
        @Override
        protected String getBaseUrl(HttpServletRequest request) {
            return baseUrl;
        }
    };

    Map<String, String[]> parameterMap = new HashMap<String, String[]>();
    parameterMap.put("a", new String[] { "value-a" });
    parameterMap.put("b", new String[] { "value-b" });
    parameterMap.put("c", new String[] { "value-c" });
    parameterMap.put("param[1]", new String[] { "aaa", "bbb" });

    when(request.getParameterNames()).thenReturn(Collections.enumeration(parameterMap.keySet()));
    for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
        when(request.getParameterValues(param.getKey())).thenReturn(param.getValue());
    }

    String header = "OAuth realm=\"http://sp.example.com/\","
            + "                oauth_consumer_key=\"0685bd9184jfhq22\","
            + "                oauth_token=\"ad180jjd733klru7\","
            + "                oauth_signature_method=\"HMAC-SHA1\","
            + "                oauth_signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\","
            + "                oauth_timestamp=\"137131200\"," + "                oauth_callback=\""
            + OAuthCodec.oauthEncode("http://myhost.com/callback") + "\","
            + "                oauth_nonce=\"4572616e48616d6d65724c61686176\","
            + "                oauth_version=\"1.0\"";
    when(request.getHeaders("Authorization")).thenReturn(Collections.enumeration(Arrays.asList(header)));
    when(request.getMethod()).thenReturn("GET");
    String ours = support.getSignatureBaseString(request);

    when(request.getHeaders("Authorization")).thenReturn(Collections.enumeration(Arrays.asList(header)));
    when(request.getParameterMap()).thenReturn(parameterMap);
    when(request.getHeaderNames()).thenReturn(null);
    OAuthMessage message = OAuthServlet.getMessage(request, baseUrl);

    String theirs = OAuthSignatureMethod.getBaseString(message);
    assertEquals(theirs, ours);
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request//from  w w w . j a va2  s  .c  om
 *
 * @param proxyDetails
 * @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
 */
private void setProxyRequestHeaders(ProxyDetails proxyDetails, 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)
                || ProxySupport.isHopByHopHeader(stringHeaderName))
            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 = proxyDetails.getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from   ww  w .j  av  a  2s  .  c  o  m*/
 *
 * @param proxyDetails
 * @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
 */
private void setProxyRequestHeaders(ProxyDetails proxyDetails, 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)
                || ProxySupport.isHopByHopHeader(stringHeaderName))
            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 = proxyDetails.getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
        httpMethodProxyRequest.setRequestHeader("Accept-Encoding", "");
    }
}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;/*from   w  w w. ja  va  2s.c o m*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Retreives all of the headers from the servlet request and sets them on the proxy request.
 *
 * @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
 *//*from  w  w w .  j a  v  a  2  s.c o  m*/
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(HEADER_CONTENT_LENGTH)) {
            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<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = 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(HEADER_HOST)) {
                stringHeaderValue = getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

private void monitoring(Map<HttpParameter, String> parameters, boolean checkResultContent)
        throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    final Random random = new Random();
    if (random.nextBoolean()) {
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("application/gzip"))).anyTimes();
    } else {//from w  w w  . j a  va2 s .co  m
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("text/html"))).anyTimes();
    }
    for (final Map.Entry<HttpParameter, String> entry : parameters.entrySet()) {
        if (HttpParameter.REQUEST == entry.getKey()) {
            expect(request.getHeader(entry.getKey().getName())).andReturn(entry.getValue()).anyTimes();
        } else {
            expect(entry.getKey().getParameterFrom(request)).andReturn(entry.getValue()).anyTimes();
        }
    }
    final Range range = Period.JOUR.getRange();
    final List<JavaInformations> javaInformationsList = Collections
            .singletonList(new JavaInformations(null, false));
    // getAttribute("range") et getAttribute("javaInformationsList") pour PdfController
    expect(request.getAttribute("range")).andReturn(range).anyTimes();
    expect(request.getAttribute("javaInformationsList")).andReturn(javaInformationsList).anyTimes();
    if (parameters.isEmpty() || HttpPart.JNLP.getName().equals(parameters.get(HttpParameter.PART))) {
        // dans au moins un cas on met un cookie
        final Cookie[] cookies = { new Cookie("dummy", "dummy"),
                new Cookie(PERIOD_COOKIE_NAME, Period.SEMAINE.getCode()), };
        expect(request.getCookies()).andReturn(cookies).anyTimes();
    }
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();
    final FilterChain chain = createNiceMock(FilterChain.class);

    replay(request);
    replay(response);
    replay(chain);
    monitoringFilter.doFilter(request, response, chain);
    verify(request);
    verify(response);
    verify(chain);

    if (checkResultContent) {
        assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from w  ww.j av  a  2  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
 */
@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(httpServletRequest);
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java

/**
 * {@inheritDoc}/*www  .  java2 s.  c  o m*/
 * 
 * This method has no resource requirements to operate successfully allowing for it to
 * be called by a filter without any cost to resource resolution.
 * 
 * @see org.sakaiproject.nakamura.api.http.usercontent.ServerProtectionService#isMethodSafe(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
public boolean isMethodSafe(HttpServletRequest hrequest, HttpServletResponse hresponse) throws IOException {
    if (disableProtectionForDevMode) {
        LOGGER.warn("XSS Protection is disabled [isMethodSafe]");
        return true;
    }
    String method = hrequest.getMethod();
    boolean safeHost = isSafeHost(hrequest);

    // protect against POST originating from other domains, this assumes that there is no
    // browser bug in this area
    // and no flash bug.
    if (!("GET".equals(method) || "HEAD".equals(method))) {
        String path = hrequest.getRequestURI();
        for (String okPostStem : postWhiteList) {
            if (path.startsWith(okPostStem)) {
                return true;
            }
        }
        // check the Referer
        @SuppressWarnings("unchecked")
        Enumeration<String> referers = hrequest.getHeaders("Referer");
        String referer = null;
        if (referers == null || !referers.hasMoreElements()) {
            LOGGER.debug("No Referer header present ");
            hresponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "POST Requests with no Referer are not acceptable");
            return false;
        }
        referer = referers.nextElement();
        if (referer == null) {
            LOGGER.debug("No Referer header present, was null ");
            hresponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "POST Requests with no Referer are not acceptable");
            return false;
        }

        // Do we allow non get operations to this host ?
        if (safeHost) {
            // and if we do, do we accept them from the Referer mentioned ?
            String safeReferer = applicationReferrerHeaders.get(buildTrustedHostHeader(hrequest));
            if (referer.startsWith("/")) {
                LOGGER.warn("Referer header from test script, allowed safe:[{}] request:[{}] ", safeReferer,
                        referer);
                safeHost = true;
            } else if (referer.startsWith(safeReferer)) {
                safeHost = true;
                LOGGER.debug("Accepted referred safe:[{}] request:[{}]", safeReferer, referer);
            } else {
                safeHost = false;
                LOGGER.debug("Rejecting referred safe:[{}] request:[{}]", safeReferer, referer);
            }
        }
        if (!safeHost) {
            hresponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "POST Requests are only accepted from the Application, this request was not from the application.");
            return false;
        }
    }
    return true;
}