List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:com.scooterframework.web.controller.ScooterRequestFilter.java
protected String requestInfo(boolean skipStatic, HttpServletRequest request) { String method = getRequestMethod(request); String requestPath = getRequestPath(request); String requestPathKey = RequestInfo.generateRequestKey(requestPath, method); String s = requestPathKey;// ww w .jav a 2s. c o m String queryString = request.getQueryString(); if (queryString != null) s += "?" + queryString; CurrentThreadCacheClient.cacheHttpMethod(method); CurrentThreadCacheClient.cacheRequestPath(requestPath); CurrentThreadCacheClient.cacheRequestPathKey(requestPathKey); if (skipStatic) return s; //request header Properties headers = new Properties(); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); if (value != null) headers.setProperty(name, value); } CurrentThreadCache.set(Constants.REQUEST_HEADER, headers); if (isLocalRequest(request)) { CurrentThreadCache.set(Constants.LOCAL_REQUEST, Constants.VALUE_FOR_LOCAL_REQUEST); } if (isFileUploadRequest(request)) { CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST, Constants.VALUE_FOR_FILE_UPLOAD_REQUEST); try { List<FileItem> files = new ArrayList<FileItem>(); ServletFileUpload fileUpload = EnvConfig.getInstance().getServletFileUpload(); List<?> items = fileUpload.parseRequest(request); for (Object fi : items) { FileItem item = (FileItem) fi; if (item.isFormField()) { ActionControl.storeToRequest(item.getFieldName(), item.getString()); } else if (!item.isFormField() && !"".equals(item.getName())) { files.add(item); } } CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST_FILES, files); } catch (Exception ex) { CurrentThreadCacheClient.storeError(new FileUploadException(ex)); } } return s; }
From source file:info.magnolia.debug.DumpHeadersFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { long nr = count++; LoggingResponse wrappedResponse = new LoggingResponse(response); log.info("{} uri: {}", Long.toString(nr), request.getRequestURI()); log.info("{} session: {}", Long.toString(nr), Boolean.valueOf(request.getSession(false) != null)); StringBuffer params = new StringBuffer(); for (Enumeration paramEnum = request.getParameterNames(); paramEnum.hasMoreElements();) { String name = (String) paramEnum.nextElement(); params.append(name).append(" = ").append(StringUtils.join(request.getParameterValues(name), ",")); if (paramEnum.hasMoreElements()) { params.append("; "); }// ww w.j a v a 2 s .co m } log.info("{} parameters: {}", Long.toString(nr), params); log.info("{} method: {}", Long.toString(nr), request.getMethod()); for (Enumeration en = request.getHeaderNames(); en.hasMoreElements();) { String name = (String) en.nextElement(); log.info("{} header: {}={}", new String[] { String.valueOf(nr), name, request.getHeader(name) }); } chain.doFilter(request, wrappedResponse); log.info("{} response status: {}", Long.toString(nr), Integer.toString(wrappedResponse.getStatus())); log.info("{} response length: {}", Long.toString(nr), Long.toString(wrappedResponse.getLength())); log.info("{} response mime type: {}", Long.toString(nr), wrappedResponse.getContentType()); for (Iterator iter = wrappedResponse.getHeaders().keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); log.info(request.getRequestURI() + " response: " + name + " = " + wrappedResponse.getHeaders().get(name)); } }
From source file:ezbake.security.client.EzbakeSecurityClient.java
/** * Attempt to read the proxy princiapl from the HTTP headers. * * @param request the servlet request for the current request * @return the proxy principal that was contained in the HTTP headers * @throws EzSecurityTokenException/*from ww w . j a v a2 s . com*/ */ public ProxyPrincipal requestPrincipalFromRequest(HttpServletRequest request) throws EzSecurityTokenException { if (log.isTraceEnabled()) { Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); log.trace("Header: " + headerName + " = " + request.getHeader(headerName)); } } // Convert the headers into a map Map<String, List<String>> headers = new HashMap<>(); for (String headerName : Collections.list(request.getHeaderNames())) { if (headers.containsKey(headerName)) { headers.get(headerName).add(request.getHeader(headerName)); } else { headers.put(headerName.toUpperCase(), Lists.newArrayList(request.getHeader(headerName))); } } return requestPrincipalFromRequest(headers); }
From source file:com.glaf.mail.web.rest.MailReceiveReource.java
@GET @POST//from ww w.jav a 2s.com @Path("/view") public void view(@Context HttpServletRequest request, @Context UriInfo uriInfo) { String messageId = request.getParameter("messageId"); if (messageId != null) { messageId = RequestUtils.decodeString(messageId); Map<String, Object> dataMap = JsonUtils.decode(messageId); String taskId = (String) dataMap.get("taskId"); String itemId = (String) dataMap.get("itemId"); if (taskId != null && itemId != null) { MailItem mailItem = mailDataFacede.getMailItem(taskId, itemId); if (mailItem != null) { mailItem.setReceiveStatus(1); mailItem.setReceiveDate(new Date()); mailItem.setReceiveIP(RequestUtils.getIPAddress(request)); String contentType = request.getContentType(); mailItem.setContentType(contentType); logger.debug("contentType:" + contentType); java.util.Enumeration<String> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); logger.debug(name + "=" + request.getHeader(name)); } String userAgent = request.getHeader("user-agent"); if (userAgent != null) { if (userAgent.indexOf("Chrome") != -1) { mailItem.setBrowser("Chrome"); } else if (userAgent.indexOf("MSIE") != -1) { mailItem.setBrowser("IE"); } else if (userAgent.indexOf("Firefox") != -1) { mailItem.setBrowser("Firefox"); } if (userAgent.indexOf("Windows") != -1) { mailItem.setClientOS("Windows"); } } mailDataFacede.updateMail(taskId, mailItem); } } } }
From source file:airlift.servlet.rest.RestServlet.java
@Override protected final void doOptions(HttpServletRequest _httpServletRequest, HttpServletResponse _httpServletResponse) throws ServletException, IOException { java.util.Enumeration<String> headerNames = _httpServletRequest.getHeaderNames(); logInfo("reporting request header info ..."); while (headerNames.hasMoreElements() == true) { String headerName = headerNames.nextElement(); logInfo(headerName + ":" + _httpServletRequest.getHeader(headerName)); }//from w ww . j a v a 2 s . c o m _httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); //Instead of returning this Content-Type, Depth, User-Agent, //X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control //we simply say whatever you ask for we allow. We really //should make this configurable. _httpServletResponse.addHeader("Access-Control-Allow-Headers", _httpServletRequest.getHeader("Access-Control-Request-Headers")); _httpServletResponse.addHeader("Access-Control-Max-Age", "86400"); _httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS"); super.doOptions(_httpServletRequest, _httpServletResponse); }
From source file:com.ibm.sbt.service.basic.ProxyService.java
@SuppressWarnings("unchecked") protected boolean prepareForwardingHeaders(HttpRequestBase method, HttpServletRequest request) throws ServletException { Object timedObject = ProxyProfiler.getTimedObject(); // Forward any headers that should be forwarded. Except cookies. StringBuffer xForwardedForHeader = new StringBuffer(); for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement(); // Ignore cookie - treat them separately if (headerName.equalsIgnoreCase("cookie")) { // $NON-NLS-1$ continue; }//www.j av a 2 s . c o m String headerValue = request.getHeader(headerName); // This is to be investigated - Should the X-Forwarded-For being passed? Ryan. // if(headerName.equalsIgnoreCase("X-Forwarded-For") || headerName.equalsIgnoreCase("host")) { // addXForwardedForHeader(method, headerValue, xForwardedForHeader); // continue; // } // Ensure that the header is allowed if (isHeaderAllowed(headerName)) { method.addHeader(headerName, headerValue); if (getDebugHook() != null) { getDebugHook().getDumpRequest().addHeader(headerName, headerValue); } } } String xForward = xForwardedForHeader.toString(); if (StringUtil.isNotEmpty(xForward)) { method.addHeader("X-Forwarded-For", xForward); if (getDebugHook() != null) { getDebugHook().getDumpRequest().addHeader("X-Forwarded-For", xForward); } } ProxyProfiler.profileTimedRequest(timedObject, "prepareForwardingHeaders"); return true; }
From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java
/** * Retrieves all of the headers from the servlet request and sets them on * the proxy request// ww w. j a v a 2s. 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 */ private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest, ProxyHttpConnector proxyHttpConnector) { Collection<String> removableHeaders = proxyHttpConnector.getRemovableHeadersSet(); // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = GenericUtils.cast(httpServletRequest.getHeaderNames()); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME) || stringHeaderName.equalsIgnoreCase("Cookie") || removableHeaders.contains(stringHeaderName.toLowerCase())) { 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 = GenericUtils .cast(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(proxyHttpConnector); } else if (stringHeaderName.equalsIgnoreCase("Referer")) { stringHeaderValue = stringHeaderValue.replaceFirst("://[^/]*/[^/]*/", "://" + getProxyHostAndPort(proxyHttpConnector) + proxyHttpConnector.getBaseDir() + (proxyHttpConnector.getBaseDir().endsWith("/") ? "" : "/")); } Engine.logEngine.debug( "(ReverseProxyServlet) Forwarding header: " + stringHeaderName + "=" + stringHeaderValue); Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java
/** * It does the Kerberos authentication using the negotiation way. It * establishes a negotiation with the browser sending HTTP error messages. * /*from w ww. j a v a 2 s .c o m*/ * @param request HTTP request * @param response HTTP response * * @return the method result in HTTP error format */ public int authNegotiate(HttpServletRequest request, HttpServletResponse response) { //Implement Kerberos negotiatiation and authentication int result = HttpServletResponse.SC_UNAUTHORIZED; //read Authorization header boolean isAuthorization = false; //reset challenge challenge = null; Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); if (headerName.toLowerCase().equals(HEADER_AUTHORIZATION)) { isAuthorization = true; challenge = request.getHeader(headerName); logger.debug("Authorization header read: " + challenge); break; } } // Instantiate the authentication process class try { //Check if the header sent by the client is Authorization or not if (!isAuthorization) { logger.debug("Sending.... " + HEADER_WWW_AUTHENTICATE); response.addHeader(HEADER_WWW_AUTHENTICATE, NEG_TOKEN); // Return return HttpServletResponse.SC_UNAUTHORIZED; } else { if (challenge == null) { // Log error logger.error("The browser did not send the challenge properly"); // Return return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } //Check if serverCreds and subject are properly set if ((serverCreds == null) || (serverSubject == null)) { // Log error logger.error("The GSA authentication servlet cannot get Server credentials"); // Return return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } //Initialize Spnego server spnegoServer = new GssSpNegoServer(serverCreds, spnegoAuth.getManager(), serverSubject); boolean isComplete = false; try { isComplete = spnegoServer.processSpNego(challenge); logger.debug("isComplete? " + isComplete); if (!isComplete) { logger.debug("Sending.... " + HEADER_WWW_AUTHENTICATE); // Raise error response.addHeader(HEADER_WWW_AUTHENTICATE, NEG_TOKEN + " " + spnegoServer.getResponseToken()); return HttpServletResponse.SC_UNAUTHORIZED; } else { if (spnegoServer.isFailed()) { logger.error("Error during the negotiation process"); return HttpServletResponse.SC_UNAUTHORIZED; } else { //Negotiation result is OK //Add cookies before returning //Get client subject userSubject = spnegoServer.getClientSubject(); //Preparing Unique id username = getPrincipalStr(userSubject); id = username; logger.debug("username is ... " + id); result = HttpServletResponse.SC_OK; } } } catch (Exception ex) { logger.error("Exception during the negotiation: " + ex.getMessage(), ex); return HttpServletResponse.SC_UNAUTHORIZED; } finally { } } catch (Exception e) { // Log error logger.error("Exception during the negotiation: " + e.getMessage(), e); return HttpServletResponse.SC_UNAUTHORIZED; } return result; }
From source file:com.fujitsu.dc.engine.rs.AbstractService.java
/** * Service.//from w w w .j a v a 2 s . c o m * @param cell Cell?? * @param scheme URI * @param svcName ??? * @param req Request * @param res Response * @param is * @return Response */ public final Response run(final String cell, final String scheme, final String svcName, final HttpServletRequest req, final HttpServletResponse res, final InputStream is) { StringBuilder msg = new StringBuilder(); msg.append("[" + DcEngineConfig.getVersion() + "] " + ">>> Request Started "); msg.append(" method:"); msg.append(req.getMethod()); msg.append(" method:"); msg.append(req.getRequestURL()); msg.append(" url:"); msg.append(cell); msg.append(" scheme:"); msg.append(scheme); msg.append(" svcName:"); msg.append(svcName); log.info(msg); // ? ???? Enumeration<String> multiheaders = req.getHeaderNames(); for (String headerName : Collections.list(multiheaders)) { Enumeration<String> headers = req.getHeaders(headerName); for (String header : Collections.list(headers)) { log.debug("RequestHeader['" + headerName + "'] = " + header); } } this.setServiceName(svcName); // ?URL?? String targetCell = cell; if (cell == null) { targetCell = getCell(); } String targetScheme = scheme; if (scheme == null) { targetScheme = getScheme(); } String targetServiceName = svcName; String baseUrl; try { baseUrl = parseRequestUri(req, res); } catch (MalformedURLException e) { // URL??????? return makeErrorResponse("Server Error", DcEngineException.STATUSCODE_SERVER_ERROR); } Response response = null; DcEngineContext dcContext = null; try { try { dcContext = new DcEngineContext(); } catch (DcEngineException e) { return errorResponse(e); } // ??? try { this.sourceManager = this.getServiceCollectionManager(); dcContext.setSourceManager(this.sourceManager); this.serviceSubject = this.sourceManager.getServiceSubject(); } catch (DcEngineException e) { return errorResponse(e); } // ?? dcContext.loadGlobalObject(baseUrl, targetCell, targetScheme, targetScheme, targetServiceName); // ??? String source = ""; try { String sourceName = this.sourceManager.getScriptNameForServicePath(targetServiceName); source = this.sourceManager.getSource(sourceName); } catch (DcEngineException e) { return errorResponse(e); } catch (Exception e) { log.info("User Script not found to targetCell(" + targetCell + ", targetScheme(" + targetScheme + "), targetServiceName(" + targetServiceName + ")"); log.info(e.getMessage(), e); return errorResponse(new DcEngineException("404 Not Found (User Script)", DcEngineException.STATUSCODE_NOTFOUND)); } // JSGI try { response = dcContext.runJsgi(source, req, res, is, this.serviceSubject); } catch (DcEngineException e) { return errorResponse(e); } catch (Exception e) { log.warn(" unknown Exception(" + e.getMessage() + ")"); return errorResponse(new DcEngineException("404 Not Found (Service Excute Error)", DcEngineException.STATUSCODE_NOTFOUND)); } } finally { IOUtils.closeQuietly(dcContext); } return response; }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java
public void displayRequestHeaders(HttpServletRequest request) { Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { M_log.debug("HEADER NAME: " + headerNames.nextElement()); }/*from w w w. j a v a 2 s .co m*/ }