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:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadContentTemplate(TemplateBean template, String domain, Integer port, boolean https,
        HttpServletRequest httpRequest) throws Exception {
    HTMLInfoBean htmlInfo = templates.get("/" + template.path);

    String sport = (port == null) ? "" : ":" + String.valueOf(port);

    String url = htmlInfo.getProtocol() + "://" + domain + sport + "/" + template.path;

    Request request = Request.Get(url);

    Enumeration<String> headerNames = httpRequest.getHeaderNames();

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

        Enumeration<String> headerValues = httpRequest.getHeaders(name);
        while (headerValues.hasMoreElements()) {
            String value = headerValues.nextElement();
            request = request.addHeader(name, value);
        }/*from  ww  w  .ja v a2 s. com*/
    }

    String content = request.execute().returnContent().asString();

    Pattern pattern = Pattern.compile("<INJECT[ ]{1,}selector=[\"'](.*?)[\"']/>",
            Pattern.CASE_INSENSITIVE + Pattern.DOTALL);

    Matcher matcher = pattern.matcher(content);

    List<String> selectors = new ArrayList<String>();

    while (matcher.find()) {
        String tagInject = matcher.group(0);
        String selector = matcher.group(1);
        selectors.add(selector);
        content = content.replace(tagInject, "<INJECT selector='" + selector + "'/>");
    }

    String key = null;

    if (template.cache.equals("SESSION")) {
        String cookiesNames = getCookieHashs(httpRequest);
        key = template.path + cookiesNames;
    } else {
        key = template.path;
    }

    HtmlContentBean contentBean = new HtmlContentBean();
    contentBean.setContent(content);
    contentBean.setLastAccess(System.currentTimeMillis());
    htmlContents.remove(key);
    htmlContents.put(key, contentBean);
    htmlInfo.setSelectors(selectors);
}

From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java

/**
 * Copy request headers from the servlet client to the proxy request.
 *///from   w w  w  .j  a  va2 s  .  c  om
protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest, HttpHost host) {
    // 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)) {
                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);
        }
    }
}

From source file:edu.ucmerced.cas.adaptors.casshib.web.flow.PrincipalFromHttpHeadersNonInteractiveCredentialsAction.java

protected Credentials constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Remote  User [" + remoteUser + "] found in HttpServletRequest");
        }/*ww  w  . ja  v  a 2  s .co  m*/

        /**
         * Grab the Shibboleth attributes from the HTTP headers, create a
         * map of them, and include the, in the SimplePrincipal.
         */
        HashMap<String, Object> attributes = new HashMap<String, Object>();

        Enumeration en = request.getHeaderNames();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            if (name.startsWith("shibattr-") || name.startsWith("Shib-")) {
                ArrayList<String> valueList = new ArrayList<String>();
                Enumeration en2 = request.getHeaders(name);
                while (en2.hasMoreElements()) {
                    String value = (String) en2.nextElement();
                    if (value.length() > 0) {
                        valueList.add(value);
                    }
                }
                if (valueList.size() > 0) {
                    if (name.startsWith("shibattr-"))
                        attributes.put(name.substring("shibattr-".length()),
                                (valueList.size() == 1 ? valueList.get(0) : valueList));
                    else
                        attributes.put(name, (valueList.size() == 1 ? valueList.get(0) : valueList));
                }
            }
        }

        return new PrincipalBearingCredentials(new SimplePrincipal(remoteUser, attributes));
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Remote User not found in HttpServletRequest.");
    }

    return null;
}

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);//from   ww  w  .  j  ava  2s. 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();
}

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/*  w  w w.ja v  a  2  s  .  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: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)));
    }/*from www  . j av  a2s  .  c om*/

    return httpHeaders;
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }/*from   w  w w  . j a v  a2  s  .  com*/
        if (headerNameKey.equals("Content-Type")) {
            contenttype = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.info("contenttype = " + contenttype);

    try {

        // TODO validate Content-Type

        String data = httpServletRequest.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));

        if (data == null || data.equals("")) {

            this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
            httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
        } else {

            String postableData = null;

            // TODO bind interface Preprocessing
            if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

                PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class);
                // init Authorization Service
                preprocessingInterface.init(this.config);

                postableData = preprocessingInterface.process(data);
            } else {

                // TODO correct error handling
                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }

            if (postableData != null) {

                // TODO if successful then POST as application/sparql-update to LinkedDataPlatform
                String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

                // HTTP Request
                int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

                CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultRequestConfig(defaultRequestConfig).build();

                try {

                    HttpPost httpPost = new HttpPost(sparql_url);
                    httpPost.addHeader("Content-Type", "application/sparql-update");
                    httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
                    httpPost.setEntity(new StringEntity(postableData));

                    CloseableHttpResponse httpResponse = null;

                    long start = System.nanoTime();
                    try {

                        httpResponse = httpclient.execute(httpPost);
                    } catch (ConnectTimeoutException | SocketTimeoutException e) {

                        this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": "
                                + e.getMessage());
                        httpResponse = httpclient.execute(httpPost);
                    }
                    long elapsed = System.nanoTime() - start;
                    this.logger.info("[" + this.getClass().getName() + "] LDP request - "
                            + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s");

                    try {

                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        HttpEntity httpEntity = httpResponse.getEntity();

                        // TODO
                        httpServletResponse.setStatus(statusCode);
                        httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase());

                        EntityUtils.consume(httpEntity);

                    } finally {
                        httpResponse.close();
                    }
                } finally {

                    httpclient.close();
                }
            }
        }
    } catch (Exception e) {

        this.logger.error("something went wrong", e);
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpointTest.java

@Test(dataProvider = "testIssueAccessTokenDataProvider", groups = "testWithConnection")
public void testIssueAccessToken(String clientId, String authzHeader, Object paramMapObj, String grantType,
        String idToken, Object headerObj, Object customResponseParamObj, Exception e, int expectedStatus,
        String expectedErrorCode) throws Exception {
    MultivaluedMap<String, String> paramMap = (MultivaluedMap<String, String>) paramMapObj;
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    Map<String, String> customResponseParameters = (Map<String, String>) customResponseParamObj;

    Map<String, String[]> requestParams = new HashMap<>();

    if (clientId != null) {
        requestParams.put(OAuth.OAUTH_CLIENT_ID, clientId.split(","));
    }//from   ww w.  j  a  v  a2s  . c o m
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
    requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
    requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });

    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {
        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));

    spy(EndpointUtil.class);
    doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");

    when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class)))
            .thenReturn(oAuth2AccessTokenRespDTO);
    when(oAuth2AccessTokenRespDTO.getAccessToken()).thenReturn(ACCESS_TOKEN);
    when(oAuth2AccessTokenRespDTO.getRefreshToken()).thenReturn(REFRESH_TOKEN);
    when(oAuth2AccessTokenRespDTO.getExpiresIn()).thenReturn(3600L);
    when(oAuth2AccessTokenRespDTO.getAuthorizedScopes()).thenReturn("scope1");
    when(oAuth2AccessTokenRespDTO.getIDToken()).thenReturn(idToken);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
    when(oAuth2AccessTokenRespDTO.getParameters()).thenReturn(customResponseParameters);

    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);

    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);

    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");

    Response response;
    try {
        response = oAuth2TokenEndpoint.issueAccessToken(request, paramMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }

    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");

    assertNotNull(response.getEntity(), "Response entity is null");

    final String responseBody = response.getEntity().toString();
    if (customResponseParameters != null) {
        customResponseParameters
                .forEach((key, value) -> assertTrue(responseBody.contains(key) && responseBody.contains(value),
                        "Expected custom response parameter: " + key + " not found in token response."));
    }

    if (expectedErrorCode != null) {
        assertTrue(responseBody.contains(expectedErrorCode), "Expected error code not found");
    } else if (HttpServletResponse.SC_OK == expectedStatus) {
        assertTrue(responseBody.contains(ACCESS_TOKEN), "Successful response should contain access token");
    }
}

From source file:org.smigo.log.LogHandler.java

public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) {
    StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ")
            .append(request.getRequestURL()).append(separator);
    s.append("Auth type:").append(request.getAuthType()).append(separator);
    s.append("Principal:").append(request.getUserPrincipal()).append(separator);
    s.append(Log.create(request, response).toString()).append(separator);
    s.append("Headers:").append(separator);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator);
    }//from  w w w.  j a v  a2  s  .  com
    s.append(separator);
    s.append("####RESPONSE").append(separator);
    s.append("Status:").append(response.getStatus()).append(separator);
    s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator);
    s.append("Locale:").append(response.getLocale()).append(separator);
    s.append("Content type:").append(response.getContentType()).append(separator);

    s.append("Headers:").append(separator);
    s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh))
            .collect(Collectors.joining(separator)));

    final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER);
    if (start != null) {
        final long elapsedTime = System.nanoTime() - start;
        s.append(separator).append("####Request time elapsed:").append(elapsedTime);
        s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator);
    }
    return s.toString();
}

From source file:org.apache.catalina.authenticator.FormAuthenticator.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
 *//*from ww w. jav  a  2s .  c om*/
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(Constants.FORM_REQUEST_NOTE, saved);

}