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:AIR.Common.Web.Session.HttpRequestLoggerInitializerFilter.java

@SuppressWarnings("unchecked")
private void addRequestDetailsToLoggers(HttpServletRequest request) {
    final String method = request.getMethod();
    logger.debug("========================== Request Logging Start ===================================");
    logger.debug("Method:       " + method);
    logger.debug("Request URI:  " + request.getRequestURI());
    logger.debug("Received at:  " + MDC.get("requestTime"));
    logger.debug("Query String: " + request.getQueryString());
    logger.debug("<<<<<<<<< Headers start >>>>>>>>>>");

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        logger.debug(headerName + " : " + headerValue);
    }/*  w  ww .j  a  v a2  s . c  o m*/
    logger.debug("<<<<<<<<< Headers end >>>>>>>>>>");
}

From source file:org.emergent.plumber.UserServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String subPath = (String) req.getAttribute(ATTRIB_SUBPATH_KEY);
    if (!"".equals(subPath)) {
        super.doPut(req, resp);
        return;/*  w  w w. j  a  va2 s . com*/
    }

    String userName = (String) req.getAttribute(ATTRIB_USERNAME_KEY);
    String body = MiscUtil.readBody(req);
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String hname = (String) enu.nextElement();
        String hval = req.getHeader(hname);
        log(String.format("HEADER (%s) : \"%s\"", hname, hval));
    }
    log("BODY:\n" + body);

    Connection dbCon = null;
    PreparedStatement st = null;
    boolean success = false;
    try {
        JSONObject obj = new JSONObject(body);
        String password = obj.getString("password");
        String email = obj.getString("email");
        dbCon = getDatabaseConnection(req);
        int modCnt = addUser(dbCon, userName, password, email);
        log("SUCCESS: " + modCnt + " " + userName);
        success = modCnt == 1;
    } catch (JSONException e) {
        log(e.getMessage(), e);
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } finally {
        MiscUtil.close(st);
        MiscUtil.close(dbCon);
    }
    if (success) {
        String weaveTimestamp = String.format("%.2f", System.currentTimeMillis() / 1000.0);
        resp.setHeader("X-Weave-Timestamp", weaveTimestamp);
        PrintWriter writer = resp.getWriter();
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        writer.append(userName);
    } else {
        super.doPut(req, resp);
    }
}

From source file:org.apache.shindig.social.opensocial.hibernate.utils.HttpLogFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    req = new BufferedServletRequestWrapper(req);
    try {/*from   w ww  .jav a  2 s .  c  o m*/
        JSONObject json = new JSONObject();
        json.put("requestURI", req.getRequestURI());
        json.put("contentType", req.getContentType());
        json.put("method", req.getMethod());
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            headerMap.put(headerName, headerValue);
        }
        json.put("headerMap", headerMap);
        InputStream in = req.getInputStream();
        String body = IOUtils.toString(in, "UTF-8");
        json.put("body", body);

        json.put("parameterMap", req.getParameterMap());
        json.put("timestamp", new Date().getTime());
        //
        String serialized = JsonSerializer.serialize(json);
        logger.info(serialized);
    } catch (Throwable e) {
        logger.error("Couldn't output a log.", e);
    }
    chain.doFilter(req, response);
}

From source file:org.getobjects.servlets.WOServletRequest.java

protected void loadHeadersFromServletRequest(final HttpServletRequest _rq) {
    final Enumeration e = _rq.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();

        final Enumeration ve = _rq.getHeaders(name);
        name = name.toLowerCase();/* w  w w  .j  a  v  a  2 s .co  m*/

        while (ve.hasMoreElements()) {
            final String v = (String) ve.nextElement();
            this.appendHeader(v, name);
        }
    }
}

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())//from   w  ww  .j a v  a2 s. c  o  m
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}

From source file:com.fbr.services.SecurityService.java

@Transactional
public HttpStatus checkAuthenticationAndAuthorization(HttpServletRequest httpRequest) {

    logger.debug("Request uri is {}" + httpRequest.getRequestURI());
    if (!LOGIN_EXCEPTION_URIS.contains(httpRequest.getRequestURI())) {

        String sessionId = httpRequest.getHeader("sessionId");
        Enumeration<String> headers = httpRequest.getHeaderNames();
        if (headers != null) {
            logger.debug("Headers are");
            while (headers.hasMoreElements()) {
                logger.debug(headers.nextElement());
            }/*from w ww  .  j  ava2 s .  c om*/
        }
        if (sessionId != null) {
            Date idleExpirationDate = DateUtils.addMinutes(new Date(), -idle_session_timeout);
            SessionDbType sessionDbType = sessionDao.validateSessionId(sessionId, idleExpirationDate);
            if (sessionDbType == null) {
                logger.debug("Session " + sessionId + " was not found in the database");
                return HttpStatus.UNAUTHORIZED;
            }
            logger.debug("Session " + sessionId + " is validated");
            sessionDbType.setLastAccessTime(new Date());
            sessionDao.update(sessionDbType);
            if (!isAuthorizedForApi(httpRequest.getMethod(), httpRequest.getRequestURI(),
                    httpRequest.getQueryString(), sessionDbType)) {
                logger.debug(httpRequest.getMethod() + " on " + httpRequest.getRequestURI()
                        + " for this user is not authorized");
                return HttpStatus.FORBIDDEN;
            }

            logger.debug("Session " + sessionId + "is Authorized");

        } else {
            logger.debug("sessionId was not found in the header");
            return HttpStatus.UNAUTHORIZED;
        }

    }
    return HttpStatus.OK;
}

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

private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException {
    URI targetUri;//from   w w  w. j ava2s  .com
    try {
        targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerVals = request.getHeaders(headerName);
        while (headerVals.hasMoreElements()) {
            String headerValue = headerVals.nextElement();
            headerValue = headerFilter.processRequestHeader(headerName, headerValue);
            if (headerValue != null) {
                commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
            }

        }
    }

    return commonsHttpMethod;
}

From source file:com.bluexml.side.framework.alfresco.shareLanguagePicker.connector.MyHttpRequestServletAdaptator.java

public MyHttpRequestServletAdaptator(HttpServletRequest request) {
    this.request = request;
    Enumeration<?> headerNames = request.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        headers.add(key, value);/*from   w  ww.  j  a  v a 2 s  .c  om*/
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

/**
 * dumpHeader iterates through all request headers and lists both the header
 * name and its contents to the designated logger.
 * //from ww w . j  a va  2 s.  c o m
 * @param req
 *          the HttpServletRequest object.
 * @return contentLength  
 *          the content length that was specified in the 
 *          request headers, possibly null
 */
private Integer dumpHeader(HttpServletRequest req, Boolean noAuthPeek) {
    Enumeration<String> headerNames = req.getHeaderNames();
    String headerName = null;
    Integer contentLength = null;

    String header = null;
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("Header: %n"));

    while (headerNames.hasMoreElements()) {

        headerName = headerNames.nextElement();
        header = req.getHeader(headerName);

        if (headerName.equals("Authorization") && noAuthPeek)
            header = "********";

        if (headerName.equals("Content-Length")) {
            contentLength = Integer.valueOf(header);
        }

        sb.append(String.format("     %s: %s%n", headerName, header));

    }

    logger.info(sb.toString());
    return contentLength;

}

From source file:nl.surfnet.coin.shared.filter.LoggingFilter.java

private void preHandle(HttpServletRequest request, String requestId) {
    // Log basic request information at debug level
    if (REQUEST_LOG.isDebugEnabled()) {
        REQUEST_LOG.debug("{} {} {}?{}", requestId, request.getMethod(), request.getRequestURL(),
                request.getQueryString());

        // Log headers with Trace level
        if (REQUEST_LOG.isTraceEnabled()) {
            @SuppressWarnings("unchecked")
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                Enumeration headerValues = request.getHeaders(headerName);
                while (headerValues.hasMoreElements()) {
                    Object value = headerValues.nextElement();
                    REQUEST_LOG.trace("{} Header: {}: {}", requestId, headerName, value);
                }//from   w ww .  j  a  v  a 2 s .c  o  m
            }
        }
    }
}