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.opengeoportal.proxy.controllers.DynamicOgcController.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();
        //TODO why?
        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();
            //Don't do this unless we need to
            /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){
               headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0";
            }*//*w ww. j a  va  2  s. c  o m*/
            // 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();
            }
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

private void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*www .  j  av a 2  s. c  o  m*/

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:org.wso2.carbon.identity.core.filter.AuthorizationHeaderFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final String authHeader = req.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
    if (StringUtils.isEmpty(authHeader)) {
        chain.doFilter(request, response);
        return;//from   ww w  . j a  va 2s .c o m
    }

    String authType = null;
    if (authHeader.length() >= AUTH_TYPE_BASIC_LENGTH) {
        authType = authHeader.trim().substring(0, AUTH_TYPE_BASIC_LENGTH);
    }
    if (AUTH_TYPE_BASIC.equals(authType)) {
        final String authCredentials = (authHeader.trim().substring(AUTH_TYPE_BASIC_LENGTH)).trim();
        //if auth header comes in invalid format send error in response
        if (StringUtils.isBlank(authCredentials) || authCredentials.indexOf(' ') >= 0
                || authCredentials.length() < MINIMUM_CREDENTIAL_SIZE) {
            String errorMsg = "Internal Server Error";
            handleErrorResponse((HttpServletResponse) response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    errorMsg);
        } else if (authHeader.substring((AUTH_TYPE_BASIC + " ").length()).startsWith(" ")) {
            //if there is more than single space between auth_type and credentials modify the request header
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) {

                @Override
                public Enumeration<String> getHeaders(String name) {

                    if (StringUtils.equalsIgnoreCase(name, HTTPConstants.HEADER_AUTHORIZATION)) {

                        Enumeration<String> headerValues = req.getHeaders(name);
                        ArrayList<String> newHeaderValues = new ArrayList<>();
                        while (headerValues.hasMoreElements()) {
                            String value = headerValues.nextElement();
                            if (StringUtils.equals(value, authHeader)) {
                                value = AUTH_TYPE_BASIC + " " + authCredentials;
                                newHeaderValues.add(value);
                            } else {
                                newHeaderValues.add(value);
                            }
                        }
                        return Collections.enumeration(newHeaderValues);
                    }
                    return super.getHeaders(name);
                }
            };
            // pass the request along the filter chain
            chain.doFilter(wrapper, response);
        }
        //if auth header comes in correct format, forward
        else {
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.josso.gl2.agent.SSOAgentValve.java

/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException//from w w w . ja va  2  s .  c  o  m
 */
private void saveRequest(HttpRequest request, Session session) {

    // Create and populate a SavedRequest object for this request
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++)
            saved.addCookie(cookies[i]);
    }
    Enumeration names = hreq.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = hreq.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration locales = hreq.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        saved.addLocale(locale);
    }
    Map parameters = hreq.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();
    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        String paramValues[] = (String[]) parameters.get(paramName);
        saved.addParameter(paramName, paramValues);
    }
    saved.setMethod(hreq.getMethod());
    saved.setQueryString(hreq.getQueryString());
    saved.setRequestURI(hreq.getRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(org.apache.catalina.authenticator.Constants.FORM_REQUEST_NOTE, saved);

}

From source file:org.mocksy.rules.http.HttpProxyRule.java

protected HttpRequestBase getProxyMethod(HttpServletRequest request) {
    String proxyUrl = this.proxyUrl;
    proxyUrl += request.getPathInfo();/*from  ww w .j av a2  s  . com*/
    if (request.getQueryString() != null) {
        proxyUrl += "?" + request.getQueryString();
    }
    HttpRequestBase method = null;
    if ("GET".equals(request.getMethod())) {
        method = new HttpGet(proxyUrl);
        method.addHeader("Cache-Control", "no-cache");
        method.addHeader("Pragma", "no-cache");
    } else if ("POST".equals(request.getMethod())) {
        method = new HttpPost(proxyUrl);

        Map<String, String[]> paramMap = request.getParameterMap();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String paramName : paramMap.keySet()) {
            String[] values = paramMap.get(paramName);
            for (String value : values) {
                NameValuePair param = new BasicNameValuePair(paramName, value);
                params.add(param);
            }
        }

        try {
            ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {
            // don't worry, this won't happen
        }
    }

    Enumeration headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = (String) headers.nextElement();
        if ("If-Modified-Since".equals(header) || "Content-Length".equals(header)
                || "Transfer-Encoding".equals(header))
            continue;
        Enumeration values = request.getHeaders(header);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            method.addHeader(header, value);
        }
    }

    return method;
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 *//*  w  w  w  .  ja  va  2 s .c o m*/
private static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}

From source file:org.testdwr.plain.Test.java

@SuppressWarnings("unchecked")
public Map<String, String> listHeaders(HttpServletRequest request) {
    Map<String, String> reply = new HashMap<String, String>();

    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        StringBuilder value = new StringBuilder();
        while (values.hasMoreElements()) {
            String single = values.nextElement();
            value.append(single);/* ww w. j  a  v a 2 s.  c o  m*/
            if (values.hasMoreElements()) {
                value.append(", ");
            }
        }

        reply.put(name, value.toString());
    }
    return reply;
}

From source file:org.tuckey.web.filters.urlrewrite.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;/* w w w.  j  a va  2s  . com*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod putMethod = new PutMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        putMethod.setRequestEntity(inputStreamRequestEntity);
        method = putMethod;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod();
    } else {
        log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

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

    Enumeration e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) 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;
            }

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

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

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();

    try {//from  www.j  a  v a2s. com
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");

        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                    .getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles").split(","))
                        .anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }

                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }

        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null
                && ((X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }

        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}