List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java
/** * Time the processing that is performed by all subsequent filters in the * current filter stack, including the ultimately invoked servlet. * * @param request The servlet request we are processing * @param result The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs *//* w w w . j av a 2 s .com*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; // Render the generic servlet request properties StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis()))); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); Enumeration locales = request.getLocales(); boolean first = true; while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); if (first) first = false; else writer.print(", "); writer.print(locale.toString()); } writer.println(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); writer.print(" parameter=" + name + "="); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) writer.print(", "); writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { writer.println("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie cookies[] = hrequest.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } names = hrequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); } writer.println("============================================="); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); log.info(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(request, response); }
From source file:org.opendaylight.vtn.webapi.utils.VtnServiceWebUtil.java
/** * Prepare header json./*from w w w.j av a 2s . co m*/ * * @param request * the request * @return the json object * @throws VtnServiceWebAPIException */ public static JsonObject prepareHeaderJson(final HttpServletRequest request) throws VtnServiceWebAPIException { LOG.trace("Start VtnServiceWebUtil#prepareHeaderJson()"); final JsonObject headerJson = new JsonObject(); /* * check if Authorization header is available or not * If available then decode username and password, if * not available then check for header fields for * username and password */ final String authrizationHeader = request.getHeader(ApplicationConstants.HTTP_AUTHERIZATION); if (authrizationHeader != null && authrizationHeader.startsWith(ApplicationConstants.AUTHERIZATION_BASIC)) { // Authorization: Basic base64credentials String base64Credentials = authrizationHeader .substring(ApplicationConstants.AUTHERIZATION_BASIC.length()).trim(); String credentials = new String(Base64.decodeBase64(base64Credentials)); // credentials = username:password final String[] values = credentials.split(ApplicationConstants.COLON); if (values.length == 2) { headerJson.addProperty(SessionEnum.USERNAME.getSessionElement(), values[0]); headerJson.addProperty(SessionEnum.PASSWORD.getSessionElement(), values[1]); } } else { final Enumeration<?> headerEnum = request.getHeaderNames(); if (null != headerEnum) { while (headerEnum.hasMoreElements()) { final String nextElement = (String) headerEnum.nextElement(); if (SessionEnum.USERNAME.getSessionElement().equals(nextElement) || SessionEnum.PASSWORD.getSessionElement().equals(nextElement)) { headerJson.addProperty(nextElement, request.getHeader(nextElement)); } } } } /* * Set user-name and password, if request came from NEC OpenFlow Plugin */ setOpenStackAuthentications(request, headerJson); headerJson.addProperty(SessionEnum.IPADDRESS.getSessionElement(), request.getRemoteAddr()); headerJson.addProperty(ApplicationConstants.TYPE, ApplicationConstants.SESSION_TYPE); final JsonObject sessionJson = new JsonObject(); sessionJson.add(ApplicationConstants.SESSION, headerJson); LOG.debug("Session Json : " + sessionJson); LOG.trace("Complete VtnServiceWebUtil#prepareHeaderJson()"); return sessionJson; }
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;/*from w w w .ja v a 2 s. c o m*/ } 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.addsimplicity.anicetus.web.TelemetryServletFilter.java
@SuppressWarnings("unchecked") private void setRequestOnSession(TelemetryHttpSession session, HttpServletRequest request) { session.setMethod(request.getMethod()); session.setProtocol(request.getProtocol()); if (request.getContentType() != null) { session.setContentType(request.getContentType(), HeaderType.Request); }/* w w w . j a v a2 s. com*/ session.setRequestURL(request.getRequestURI()); Enumeration<String> pnames = request.getParameterNames(); while (pnames.hasMoreElements()) { String name = pnames.nextElement(); session.setParameter(name, request.getParameter(name)); } Enumeration<String> hnames = request.getHeaderNames(); while (hnames.hasMoreElements()) { String name = hnames.nextElement(); String value = request.getHeader(name); if (value != null) { session.setHeader(name, request.getHeader(name), HeaderType.Request); } } String parent = request.getHeader(s_PARENT_NAME); if (parent == null) { parent = request.getParameter(s_PARENT_NAME); } if (parent != null) { try { UUID parentId = UUID.fromString(parent); session.setParentId(parentId); } catch (IllegalArgumentException iae) { // TODO - Exception handler } } }
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
private void logRequestHeaders(HttpServletRequest request) { Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headers = request.getHeaders(headerName); while (headers.hasMoreElements()) { String header = headers.nextElement(); LOGGER.debug("request header: {} = {}", headerName, header); }/*ww w . j a v a 2 s.c o m*/ } }
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 www .j a v a 2 s . co 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); } } }
From source file:org.osaf.cosmo.dav.servlet.StandardRequestHandler.java
@SuppressWarnings("unchecked") private void dumpRequest(HttpServletRequest req) { if (!log.isTraceEnabled()) return;//from w w w .j a v a2 s .com StringBuffer sb = new StringBuffer("\n------------------------ Dump of request -------------------\n"); try { Enumeration names = req.getHeaderNames(); sb.append("Request headers:\n"); while (names.hasMoreElements()) { String key = (String) names.nextElement(); String val = req.getHeader(key); sb.append(" ").append(key).append(" = \"").append(val).append("\"\n"); } names = req.getParameterNames(); String title = "Request parameters"; sb.append(title).append(" - global info and uris:").append("\n"); sb.append("getMethod = ").append(req.getMethod()).append("\n"); sb.append("getRemoteAddr = ").append(req.getRemoteAddr()).append("\n"); sb.append("getRequestURI = ").append(req.getRequestURI()).append("\n"); sb.append("getRemoteUser = ").append(req.getRemoteUser()).append("\n"); sb.append("getRequestedSessionId = ").append(req.getRequestedSessionId()).append("\n"); sb.append("HttpUtils.getRequestURL(req) = ").append(req.getRequestURL()).append("\n"); sb.append("contextPath=").append(req.getContextPath()).append("\n"); sb.append("query=").append(req.getQueryString()).append("\n"); sb.append("contentlen=").append(req.getContentLength()).append("\n"); sb.append("request=").append(req).append("\n"); sb.append(title).append(":\n"); while (names.hasMoreElements()) { String key = (String) names.nextElement(); String val = req.getParameter(key); sb.append(" ").append(key).append(" = \"").append(val).append("\"").append("\n"); ; } sb.append("Request attributes:\n"); for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); Object val = req.getAttribute(key); sb.append(" ").append(key).append(" = \"").append(val).append("\"").append("\n"); ; } } catch (Throwable t) { t.printStackTrace(); } sb.append("------------------------ End dump of request -------------------"); log.trace(sb); }
From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpointTest.java
@Test(dataProvider = "testTokenErrorResponseDataProvider", groups = "testWithConnection") public void testTokenErrorResponse(String errorCode, Object headerObj, int expectedStatus, String expectedErrorCode) throws Exception { ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj; Map<String, String[]> requestParams = new HashMap<>(); requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { GrantType.PASSWORD.toString() }); 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(AUTHORIZATION_HEADER); when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() { {/*ww w .j ava 2 s . com*/ 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.getErrorMsg()).thenReturn("Token Response error"); when(oAuth2AccessTokenRespDTO.getErrorCode()).thenReturn(errorCode); when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders); 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, new MultivaluedHashMap<String, String>()); } 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"); assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found"); }
From source file:org.ms123.common.jetty.LoginFilter.java
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { long before = System.currentTimeMillis(); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String pathInfo = request.getPathInfo(); infob("\n\n<==========================================> "); info("doFilter -> " + pathInfo); infob("date: " + new Date()); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); debug("\t" + headerName + " = " + request.getHeader(headerName)); }// w w w . j a v a2 s . co m if (pathInfo == null) { info("==== NOK:pathInfo is null"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); infob("<##############################################\n\n"); return; } String[] arr = pathInfo.split("/"); String namespace = null; if (arr.length < 2) { namespace = "RPC"; } else { if (arr[1].equals("repo")) { namespace = arr[2]; } else { namespace = arr[1]; } } for (int i = 0; i < arr.length; i++) { debug("\tpathinfo[" + i + "]:" + arr[i]); } debug("\tNamespace:" + namespace); if (pathInfo.indexOf("/checkcredentials") != -1) { String cred = request.getParameter("credentials"); if (checkCredentials(namespace, cred, true)) { response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } infob("<##############################################\n\n"); return; } String auth = request.getHeader("Authorization"); debug("auth:" + auth); String credentials = null; if (auth != null || request.getParameter("credentials") != null) { String a = null; if (auth != null && auth.toLowerCase().startsWith("basic ")) { a = auth.trim().split(" ")[1]; } else { a = request.getParameter("credentials"); } credentials = Base64.decode(a); int ind = credentials.indexOf(":"); if (ind != -1) { String username = credentials.substring(0, ind); req.setAttribute(USERNAME, username); } } String firstSegment = arr[1]; String method = request.getMethod(); boolean isStaticResource = false; boolean ok = false; if (method != null && "get".equals(method.toLowerCase())) { if (arr.length > 3 && "sw".equals(arr[1]) && "website".equals(arr[3])) { ok = true; } else if ("sw".equals(firstSegment) || "repo".equals(firstSegment)) { if (isStaticResource(pathInfo)) { ok = true; isStaticResource = true; } } else if (pathInfo.equals("/robots.txt")) { ok = true; } else if (pathInfo.startsWith("/openfire")) { ok = true; } else if (pathInfo.startsWith("/sw/common") || pathInfo.startsWith("/sw/website") || pathInfo.startsWith("/sw/legacy") || pathInfo.startsWith("/sw/resource")) { ok = true; } } else if (request.getHeader("Origin") != null && method != null && "options".equals(method.toLowerCase())) { ok = true; } if (request.getParameter("rpc") != null || request.getRequestURI().startsWith("/rpc")) { ok = false; } if (request.getParameter("ws") != null || request.getRequestURI().startsWith("/ws")) { ok = false; } Map<String, Object> accessRule = null; if (isStaticResource && isRepoRequest(pathInfo)) { List<Map<String, Object>> rules = getAccessRules(namespace); accessRule = getMatchingAccessRule(namespace, pathInfo, rules); if (accessRule != null) { ok = false; } } info(pathInfo + ";" + credentials + "/ok:" + ok + "/accessRule:" + accessRule); if (ok || checkCredentials(namespace, credentials, false)) { if (accessRule != null) { String username = (String) req.getAttribute(USERNAME); if (!m_permissionService.isFileAccesPermitted(username, (List) accessRule.get(PermissionService.PERMITTED_USERS), (List) accessRule.get(PermissionService.PERMITTED_ROLES))) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } info(">>>> OK," + Thread.currentThread().getName()); RequestMapper rm = new RequestMapper(request); ThreadContext.loadThreadContext(rm, response); info(request.getPathInfo() + "|" + request.getMethod() + "|Uri:" + request.getRequestURI()); info(request.getRequestURL() + "|Url:" + request.getServletPath() + "|QS:" + request.getQueryString()); chain.doFilter(rm, response); info(">>>> End FILTER:" + ThreadContext.getThreadContext().get(ThreadContext.SESSION_MANAGER) + "/" + new Date().getTime()); Date startTime = ThreadContext.getThreadContext().getStartTime(); ThreadContext.getThreadContext().finalize(null); ThreadContext.getThreadContext().remove(); displayInfo("Finish", startTime); } else { info("==== NOK"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } infob("<##############################################\n\n"); }
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>"); }/* w ww. j a v a 2 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(); } }