List of usage examples for javax.servlet.http HttpServletRequest getHeaders
public Enumeration<String> getHeaders(String name);
Enumeration
of String
objects. From source file:com.google.acre.servlet.ProxyPassServlet.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request//from w w w .ja 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, HttpRequestBase 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)) 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 = this.metawebAPIHostAndPort; } // Set the same header on the proxy request httpMethodProxyRequest.addHeader(stringHeaderName, stringHeaderValue); } } }
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 v a 2s . 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:com.fuseim.webapp.ProxyServlet.java
/** * Copy a request header from the servlet client to the proxy request. This is easily overwritten * to filter out certain headers if desired. *//* w ww . j a v a2 s . co m*/ protected void copyRequestHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest, String headerName) { //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) return; if (headerName.equalsIgnoreCase(HttpHeaders.ACCEPT_ENCODING)) return; if (hopByHopHeaders.containsHeader(headerName)) return; @SuppressWarnings("unchecked") Enumeration<String> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { //sometimes more than one value String headerValue = 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 (!doPreserveHost && headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = getTargetHost(servletRequest); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } else if (!doPreserveCookies && headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { headerValue = getRealCookie(headerValue); } proxyRequest.addHeader(headerName, headerValue); } }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;/*from w ww . j ava 2s . c o m*/ ExtendedHttpMethod postMethod; // for this create ui server and port, properties. InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort); HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) postMethod = new ExtendedGetMethod(); else postMethod = new ExtendedPostMethod(); JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getRemoteHost()); capturedData.setRequestHeader(httpRequest); capturedData.setTargetURL(this.prot + inetAddress.getHostName()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // copy headers Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if ("host".equals(lhdr)) { Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val.startsWith("127.0.0.1")) { postMethod.addRequestHeader(hdr, sslEndPoint); } } continue; } Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { postMethod.addRequestHeader(hdr, val); } } } if (postMethod instanceof ExtendedPostMethod) ((ExtendedPostMethod) postMethod) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); httpRequest.getProtocol(); hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG, settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " " + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, "")); hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true)); hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint, new DefaultPropertyExpansionContext(project)); if (sslEndPoint.indexOf("/") < 0) postMethod.setPath("/"); else postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length())); monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod); } capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(postMethod.getResponseBody()); capturedData.setResponseHeader(postMethod); capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody())); monitor.fireAfterProxy(request, response, postMethod, capturedData); StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); postMethod.releaseConnection(); synchronized (this) { monitor.addMessageExchange(capturedData); } capturedData = null; }
From source file:freeciv.servlet.ProxyServlet.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request/*from w w w . ja v a2s . 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 */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(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)) 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 = getProxyHostAndPort(); } Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:org.mule.transport.servlet.ServletMuleMessageFactory.java
protected void copyHeaders(HttpServletRequest request, Map<String, Object> messageProperties) { for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String realKey = key;/*from ww w . j av a 2 s . co m*/ if (key.startsWith(HttpConstants.X_PROPERTY_PREFIX)) { realKey = key.substring(2); } // Workaround for containers that strip the port from the Host header. // This is needed so Mule components can figure out what port they're on. if (HttpConstants.HEADER_HOST.equalsIgnoreCase(key)) { realKey = HttpConstants.HEADER_HOST; String value = request.getHeader(key); int port = request.getLocalPort(); if (!value.contains(":") && port != 80 && port != 443) { value = value + ":" + port; } messageProperties.put(realKey, value); } else { Enumeration<?> valueEnum = request.getHeaders(key); List<?> values = EnumerationUtils.toList(valueEnum); if (values.size() > 1) { messageProperties.put(realKey, values.toArray()); } else { messageProperties.put(realKey, values.get(0)); } } } }
From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.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(); if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) 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(); // 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(); }/*from w w w.jav a2s . c o m*/ proxyRequest.addHeader(headerName, headerValue); } } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException { long resLength = resource.length(); boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null; // Get the output stream (or writer) OutputStream out = null;// w w w . j av a2s . co m try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } // see if there are any range headers Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range); if (reqRanges == null || !reqRanges.hasMoreElements()) { // if there were no ranges, send entire entity Resource data = resource; if (!include) { // look for a gziped content. if (_minGzipLength > 0) { String accept = request.getHeader(HttpFields.__AcceptEncoding); if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz")) { Resource gz = getResource(pathInContext + ".gz"); if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) { response.setHeader(HttpFields.__ContentEncoding, "gzip"); data = gz; resLength = data.length(); } } } writeHeaders(response, resource, resLength); } data.writeTo(out, 0, resLength); return; } // Parse the satisfiable ranges List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength); // if there are no satisfiable ranges, send 416 response if (ranges == null || ranges.size() == 0) { writeHeaders(response, resource, resLength); response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable); response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength)); resource.writeTo(out, 0, resLength); return; } // if there is only a single valid range (must be satisfiable // since were here now), send that range with a 216 response if (ranges.size() == 1) { InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0); long singleLength = singleSatisfiableRange.getSize(resLength); writeHeaders(response, resource, singleLength); response.setStatus(HttpResponse.__206_Partial_Content); response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength)); resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response, resource, -1); ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource); String encoding = metaData.getMimeType(); MultiPartResponse multi = new MultiPartResponse(response.getOutputStream()); response.setStatus(HttpResponse.__206_Partial_Content); // If the request has a "Request-Range" header then we need to // send an old style multipart/x-byteranges Content-Type. This // keeps Netscape and acrobat happy. This is what Apache does. String ctp; if (request.getHeader(HttpFields.__RequestRange) != null) ctp = "multipart/x-byteranges; boundary="; else ctp = "multipart/byteranges; boundary="; response.setContentType(ctp + multi.getBoundary()); InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream(); long pos = 0; for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength); multi.startPart(encoding, new String[] { header }); long start = ibr.getFirst(resLength); long size = ibr.getSize(resLength); if (in != null) { // Handle non cached resource if (start < pos) { in.close(); in = resource.getInputStream(); pos = 0; } if (pos < start) { in.skip(start - pos); pos = start; } IO.copy(in, out, size); pos += size; } else // Handle cached resource (resource).writeTo(out, start, size); } if (in != null) in.close(); multi.close(); return; }
From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java
@Override 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(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { continue; }/* w ww. j a v a 2 s .c o m*/ if (hopByHopHeaders.containsHeader(headerName)) { continue; } if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { 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)) { HttpHost host = getTargetHost(servletRequest); 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:com.squid.kraken.v4.api.core.ServiceUtils.java
/** * Retrieve a {@link AccessToken}.//from ww w. j a va 2 s. c o m * * @param request * an HttpServletRequest containing an 'access_token' param. * @return the AccessToken associated to this token or * <tt>null</null> if none found. * @throws TokenExpiredException * if the token has expired. */ public AccessToken getToken(HttpServletRequest request) { // try to find from a request param String tokenId = (String) request.getParameter(TOKEN_PARAM); if (tokenId == null) { // try to find from a cookie Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(SQUIDAPITOKEN)) { tokenId = cookies[i].getValue(); } } } } if (tokenId == null) { // try with Bearer header Enumeration<String> headers = request.getHeaders(AUTHORIZATION); while (headers.hasMoreElements()) { String auth = headers.nextElement(); int idx = auth.indexOf(BEARER_HEADER); if (idx > -1) { tokenId = auth.substring(BEARER_HEADER.length()); } } } try { AccessToken token = getToken(tokenId); if (token != null) { return token; } else { // no token id found throw new InvalidTokenAPIException("Auth failed : invalid " + TOKEN_PARAM, isNoErrorEnabled(request)); } } catch (TokenExpiredException e) { throw new InvalidTokenAPIException("Auth failed : expired " + TOKEN_PARAM, isNoErrorEnabled(request)); } }