List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:com.adito.boot.Util.java
/** * Dump all request headers to {@link System#err}. * /*from w w w . j a v a 2s. c om*/ * @param request request to get headers from */ public static void dumpRequestHeaders(HttpServletRequest request) { System.err.println("Request headers for " + request.getPathTranslated()); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { String n = (String) e.nextElement(); for (Enumeration e2 = request.getHeaders(n); e2.hasMoreElements();) { String v = (String) e2.nextElement(); System.err.println(" " + n + " = " + v); } } }
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; }/*from ww w . j av a 2 s. co 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:org.georchestra.security.HeadersManagementStrategy.java
/** * Copies the request headers from the original request to the proxy request. It may modify the * headers slightly//from w ww .ja v a2s .c o m */ @SuppressWarnings("unchecked") public synchronized void configureRequestHeaders(HttpServletRequest originalRequest, HttpRequestBase proxyRequest) { Enumeration<String> headerNames = originalRequest.getHeaderNames(); String headerName = null; StringBuilder headersLog = new StringBuilder("Request Headers:\n"); headersLog.append("==========================================================\n"); if (referer != null) { addHeaderToRequestAndLog(proxyRequest, headersLog, REFERER_HEADER_NAME, this.referer); } while (headerNames.hasMoreElements()) { headerName = headerNames.nextElement(); if (headerName.compareToIgnoreCase(CONTENT_LENGTH) == 0) { continue; } if (headerName.equalsIgnoreCase(COOKIE_ID)) { continue; } if (filter(originalRequest, headerName, proxyRequest)) { continue; } if (noAcceptEncoding && headerName.equalsIgnoreCase(ACCEPT_ENCODING)) { continue; } if (headerName.equalsIgnoreCase(HOST)) { continue; } // Don't forward 'sec-*' headers, those headers must be managed by security-proxy if (headerName.toLowerCase().startsWith(PROTECTED_HEADER_PREFIX)) { continue; } if (referer != null && headerName.equalsIgnoreCase(REFERER_HEADER_NAME)) { continue; } String value = originalRequest.getHeader(headerName); addHeaderToRequestAndLog(proxyRequest, headersLog, headerName, value); } // see https://github.com/georchestra/georchestra/issues/509: addHeaderToRequestAndLog(proxyRequest, headersLog, SEC_PROXY, "true"); handleRequestCookies(originalRequest, proxyRequest, headersLog); HttpSession session = originalRequest.getSession(); for (HeaderProvider provider : headerProviders) { for (Header header : provider.getCustomRequestHeaders(session, originalRequest)) { if ((header.getName().equalsIgnoreCase(SEC_USERNAME) || header.getName().equalsIgnoreCase(SEC_ROLES)) && proxyRequest.getHeaders(header.getName()) != null && proxyRequest.getHeaders(header.getName()).length > 0) { Header[] originalHeaders = proxyRequest.getHeaders(header.getName()); for (Header originalHeader : originalHeaders) { headersLog.append("\t" + originalHeader.getName()); headersLog.append("="); headersLog.append(originalHeader.getValue()); headersLog.append("\n"); } } else { proxyRequest.addHeader(header); headersLog.append("\t" + header.getName()); headersLog.append("="); headersLog.append(header.getValue()); headersLog.append("\n"); } } } headersLog.append("=========================================================="); logger.trace(headersLog.toString()); }
From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java
@Before @Override/*from w ww . j a v a2s . c o m*/ public void setUp() throws Exception { super.setUp(); Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp org.apache.catalina.Context context = tomcat.addContext("", System.getProperty("java.io.tmpdir")); privateAppFilter = new PrivateAppFilter(); privateAppFilter.setSecretKey(secretKey); privateAppFilter.setEnabled(true); FilterDef filterDef = new FilterDef(); filterDef.setFilter(privateAppFilter); filterDef.setFilterName(PrivateAppFilter.class.getName()); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(PrivateAppFilter.class.getName()); filterMap.addURLPattern("*"); context.addFilterMap(filterMap); context.addFilterDef(filterDef); Tomcat.addServlet(context, "hello-servlet", new HttpServlet() { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(req.getRequestURL()); IoUtils2.flush(req.getInputStream(), System.out); Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println(" " + header + ": " + req.getHeader(header)); } resp.addHeader("x-response", "hello"); resp.getWriter().println("Hello world!"); } }); context.addServletMapping("/*", "hello-servlet"); tomcat.start(); httpClient = new DefaultHttpClient(); httpHost = new HttpHost("localhost", getPort()); }
From source file:org.redhat.jboss.httppacemaker.ProxyServlet.java
/** Copy request headers from the servlet client to the proxy request. */ @SuppressWarnings("rawtypes") 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; 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)) { HttpHost host = URIUtils.extractHost(this.targetUri); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); }//ww w .ja v a 2s.c o m proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.temenos.interaction.core.web.RequestContextFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest servletRequest = (HttpServletRequest) request; String requestURI = servletRequest.getRequestURI(); requestURI = StringUtils.removeStart(requestURI, servletRequest.getContextPath() + servletRequest.getServletPath()); String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI); Map<String, List<String>> headersMap = new HashMap<>(); Enumeration<String> headerNames = servletRequest.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName)); headersMap.put(headerName, valuesList); }//from w ww.j a v a 2s.c om } RequestContext ctx; Principal userPrincipal = servletRequest.getUserPrincipal(); if (userPrincipal != null) { ctx = new RequestContext(baseURL, servletRequest.getRequestURI(), servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap); } else { ctx = new RequestContext(baseURL, servletRequest.getRequestURI(), servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap); } RequestContext.setRequestContext(ctx); try { chain.doFilter(request, response); } finally { RequestContext.clearRequestContext(); } }
From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.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(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) 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(); }// www.j a v a 2 s . c o m proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java
private String readRequestHead(HttpServletRequest request) { try {//w w w.j a va 2 s . c o m StringBuffer sb = new StringBuffer(); sb.append(request.getMethod()).append(" "); sb.append(request.getProtocol()).append(" "); sb.append(request.getPathInfo()).append("\n"); // Jetstream getHeaderNames has issues. Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); sb.append(name).append(": "); sb.append(request.getHeader(name)).append("\n"); } return sb.toString(); } catch (Throwable ex) { return null; } }
From source file:de.undercouch.gradle.tasks.download.DownloadTaskPluginTest.java
/** * Runs an embedded HTTP server and creates test files to serve * @throws Exception if the server could not be started *//*from w w w .java 2 s. c o m*/ @Before public void setUp() throws Exception { //run server on any free port server = new Server(0); //serve resources from temporary folder ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setBaseResource(Resource.newResource(folder.getRoot().getAbsolutePath())); //echo X-* headers back in response body ContextHandler echoHeadersHandler = new ContextHandler("/echo-headers") { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { response.setStatus(200); PrintWriter rw = response.getWriter(); rw.write("headers:\n"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); if (name.startsWith("X-")) { rw.write(String.format(" %s: %s\n", name, request.getHeader(name))); } } rw.close(); } }; HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resourceHandler, echoHeadersHandler, new DefaultHandler() }); server.setHandler(handlers); server.start(); //create temporary files contents = new byte[4096]; contents2 = new byte[4096]; for (int i = 0; i < contents.length; ++i) { contents[i] = (byte) (Math.random() * 255); contents2[i] = (byte) (Math.random() * 255); } File testFile = folder.newFile(TEST_FILE_NAME); FileUtils.writeByteArrayToFile(testFile, contents); File testFile2 = folder.newFile(TEST_FILE_NAME2); FileUtils.writeByteArrayToFile(testFile2, contents2); }
From source file:com.wavemaker.runtime.service.WaveMakerService.java
public String remoteRESTCall(String remoteURL, String params, String method, String contentType) { proxyCheck(remoteURL);/*www. ja va2 s. c o m*/ String charset = "UTF-8"; StringBuffer returnString = new StringBuffer(); try { if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null || params.equals("")) { } else { if (remoteURL.indexOf("?") != -1) { remoteURL += "&" + params; } else { remoteURL += "?" + params; } } URL url = new URL(remoteURL); if (this.logger.isDebugEnabled()) { this.logger.debug("Opening URL: " + url); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(method); connection.setDoInput(true); connection.setRequestProperty("Accept-Charset", "application/json"); connection.setRequestProperty("Accept-Encoding", "text/plain"); connection.setRequestProperty("Content-Language", charset); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Transfer-Encoding", "identity"); connection.setUseCaches(false); HttpServletRequest request = RuntimeAccess.getInstance().getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> headers = request.getHeaders(name); if (headers != null && !name.toLowerCase().equals("accept-encoding") && !name.toLowerCase().equals("accept-charset") && !name.toLowerCase().equals("content-type")) { while (headers.hasMoreElements()) { String headerValue = headers.nextElement(); connection.setRequestProperty(name, headerValue); if (this.logger.isDebugEnabled()) { this.logger.debug("HEADER: " + name + ": " + headerValue); } } } } // Re-wrap single quotes into double quotes String finalParams; if (contentType.toLowerCase().equals("application/json")) { finalParams = params.replace("\'", "\""); if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null && !method.equals("")) { URLEncoder.encode(finalParams, charset); } } else { finalParams = params; } connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length)); // set payload if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null || method.equals("")) { DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.writeBytes(finalParams); writer.flush(); writer.close(); } InputStream response = connection.getInputStream(); BufferedReader reader = null; int responseLen = 0; try { int i = 0; String field; HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse(); while ((field = connection.getHeaderField(i)) != null) { String key = connection.getHeaderFieldKey(i); if (key == null || field == null) { } else { if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("transfer-encoding") && field.toLowerCase().equals("chunked")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("content-length")) { // do NOT use this length as return header value responseLen = new Integer(field); } else { wmResponse.addHeader(key, field); } } i++; } reader = new BufferedReader(new InputStreamReader(response, charset)); for (String line; (line = reader.readLine()) != null;) { returnString.append(line); } } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } connection.disconnect(); return returnString.toString(); } catch (Exception e) { logger.error("ERROR in XHR proxy call: " + e.getMessage()); throw new WMRuntimeException(e); } }