List of usage examples for javax.servlet.http HttpServletRequest getHeaders
public Enumeration<String> getHeaders(String name);
Enumeration
of String
objects. From source file:org.overlord.gadgets.web.server.servlets.RestProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w.j a va 2s . c om @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Proxy inbound endpoint: " + req.getRequestURI()); // Connect to proxy URL. String urlStr = getProxyUrl(req); String queryString = req.getQueryString(); if (queryString != null) { urlStr = urlStr + "?" + queryString; } System.out.println("Proxying to: " + urlStr); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // Proxy all of the request headers. Enumeration<?> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = String.valueOf(headerNames.nextElement()); Enumeration<?> headerValues = req.getHeaders(headerName); while (headerValues.hasMoreElements()) { String headerValue = String.valueOf(headerValues.nextElement()); conn.addRequestProperty(headerName, headerValue); } } // Handle authentication RestProxyAuthProvider authProvider = getAuthProvider(); if (authProvider != null) { authProvider.provideAuthentication(conn); } // Now connect and proxy the response. InputStream proxyUrlResponseStream = null; try { proxyUrlResponseStream = conn.getInputStream(); resp.setStatus(conn.getResponseCode()); // Proxy the response headers for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) { String respHeaderName = entry.getKey(); if (respHeaderName != null && !respHeaderName.equalsIgnoreCase("transfer-encoding")) { for (String respHeaderValue : entry.getValue()) { resp.addHeader(respHeaderName, respHeaderValue); } } } // Proxy the response body. IOUtils.copy(proxyUrlResponseStream, resp.getOutputStream()); } finally { IOUtils.closeQuietly(proxyUrlResponseStream); conn.disconnect(); } }
From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java
@Override public void beforeHandler(ActionHandler actionHandler) { if (!this.monitor) { // ? return;/* w ww. jav a 2 s . co m*/ } Long userId = OnlineUserManager.getUserId(); if (userId == null) { // return; } HttpServletRequest request = actionHandler.getRequest(); String url = request.getRequestURI(); // ? if (!logInfoRemoteService.canRecord(url)) { return; } // LogInfoDto domain = new LogInfoDto(); domain.setRequestUrl(url); // ?? String cnName = OnlineUserManager.getCnName(); domain.setUserName(cnName); String remoteAddr = request.getRemoteAddr(); domain.setRemoteAddr(remoteAddr); // request headers JSONObject jsonObj = new JSONObject(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = request.getHeaders(headerName); StringBuilder sb = new StringBuilder(); while (headerValues.hasMoreElements()) { sb.append(headerValues.nextElement()); sb.append(","); } if (sb.length() > 0) { sb.substring(0, sb.length() - 1); } jsonObj.put(headerName, sb.toString()); } domain.setRequestHeader(jsonObj.toString()); // request data jsonObj = new JSONObject(); Map<String, String[]> paramMap = request.getParameterMap(); if (MapUtils.isNotEmpty(paramMap)) { Set<Entry<String, String[]>> set = paramMap.entrySet(); for (Entry<String, String[]> entry : set) { String key = entry.getKey(); String value = ArrayUtils.toString(entry.getValue()); jsonObj.put(key, value); } } domain.setRequestData(jsonObj.toString()); threadLocal.set(domain); }
From source file:pt.sapo.pai.vip.VipServlet.java
private void processRequest(HttpServletRequest request, HttpServletResponse response, Supplier<HttpRequestBase> supplier) throws ServletException, IOException { try (OutputStream out = response.getOutputStream(); CloseableHttpClient http = builder.build()) { Optional.ofNullable(servers[rand.nextInt(2)]).map(server -> server.split(":")) .map(parts -> Tuple.of(parts[0], Integer.valueOf(parts[1]))).ifPresent(server -> { try { HttpRequestBase method = supplier.get(); method.setURI(new URI(request.getScheme(), null, server._1, server._2, request.getRequestURI(), request.getQueryString(), null)); HttpResponse rsp = http.execute(method); Collections.list(request.getHeaderNames()) .forEach(name -> Collections.list(request.getHeaders(name)) .forEach(value -> method.setHeader(name, value))); response.setStatus(rsp.getStatusLine().getStatusCode()); response.setContentType(rsp.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); IOUtils.copy(rsp.getEntity().getContent(), out); } catch (IOException | URISyntaxException ex) { log.error(null, ex); }/* w w w . ja v a 2 s.com*/ }); } }
From source file:edu.ucmerced.cas.adaptors.casshib.web.flow.PrincipalFromHttpHeadersNonInteractiveCredentialsAction.java
protected Credentials constructCredentialsFromRequest(final RequestContext context) { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); final String remoteUser = request.getRemoteUser(); if (StringUtils.hasText(remoteUser)) { if (logger.isDebugEnabled()) { logger.debug("Remote User [" + remoteUser + "] found in HttpServletRequest"); }/* w w w . jav a 2s . c om*/ /** * Grab the Shibboleth attributes from the HTTP headers, create a * map of them, and include the, in the SimplePrincipal. */ HashMap<String, Object> attributes = new HashMap<String, Object>(); Enumeration en = request.getHeaderNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); if (name.startsWith("shibattr-") || name.startsWith("Shib-")) { ArrayList<String> valueList = new ArrayList<String>(); Enumeration en2 = request.getHeaders(name); while (en2.hasMoreElements()) { String value = (String) en2.nextElement(); if (value.length() > 0) { valueList.add(value); } } if (valueList.size() > 0) { if (name.startsWith("shibattr-")) attributes.put(name.substring("shibattr-".length()), (valueList.size() == 1 ? valueList.get(0) : valueList)); else attributes.put(name, (valueList.size() == 1 ? valueList.get(0) : valueList)); } } } return new PrincipalBearingCredentials(new SimplePrincipal(remoteUser, attributes)); } if (logger.isDebugEnabled()) { logger.debug("Remote User not found in HttpServletRequest."); } return null; }
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(); }//from ww w . j a v a 2 s . co m proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.adaptris.core.http.jetty.BasicJettyConsumer.java
protected void logHeaders(HttpServletRequest req) { if (additionalDebug()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter p = new PrintWriter(out); p.println("Received HTTP Headers"); p.println("URL " + req.getRequestURL()); p.println("URI " + req.getRequestURI()); p.println("Query " + req.getQueryString()); for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); Enumeration values = req.getHeaders(key); StringBuffer sb = new StringBuffer(); while (values.hasMoreElements()) { sb.append(values.nextElement()).append(","); }//w w w . jav a 2 s . c om String s = sb.toString(); p.println(key + ": " + s.substring(0, s.lastIndexOf(","))); } p.close(); log.trace(out.toString()); } }
From source file:cn.tiup.httpproxy.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. *//*from w w w . j av a 2s . c om*/ 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 (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 (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.apache.solr.servlet.SolrRequestParserTest.java
License:asdf
@Test public void testAddHttpRequestToContext() throws Exception { HttpServletRequest request = getMock("/solr/select", null, -1); expect(request.getMethod()).andReturn("GET").anyTimes(); expect(request.getQueryString()).andReturn("q=title:solr").anyTimes(); Map<String, String> headers = new HashMap<>(); headers.put("X-Forwarded-For", "10.0.0.1"); expect(request.getHeaderNames()).andReturn(new Vector<>(headers.keySet()).elements()).anyTimes(); for (Map.Entry<String, String> entry : headers.entrySet()) { Vector<String> v = new Vector<>(); v.add(entry.getValue());//ww w . jav a2s .co m expect(request.getHeaders(entry.getKey())).andReturn(v.elements()).anyTimes(); } replay(request); SolrRequestParsers parsers = new SolrRequestParsers(h.getCore().getSolrConfig()); assertFalse(parsers.isAddRequestHeadersToContext()); SolrQueryRequest solrReq = parsers.parse(h.getCore(), "/select", request); assertFalse(solrReq.getContext().containsKey("httpRequest")); parsers.setAddRequestHeadersToContext(true); solrReq = parsers.parse(h.getCore(), "/select", request); assertEquals(request, solrReq.getContext().get("httpRequest")); assertEquals("10.0.0.1", ((HttpServletRequest) solrReq.getContext().get("httpRequest")) .getHeaders("X-Forwarded-For").nextElement()); }
From source file:org.jetbrains.webdemo.handlers.ServerHandler.java
private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response, Map<String, String> postParameters) { final boolean hasoutbody = (request.getMethod().equals("POST")); try {/* www. j a v a 2s. co m*/ final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); final Enumeration<String> values = request.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); conn.addRequestProperty(header, value); } } conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setUseCaches(false); conn.setDoOutput(hasoutbody); if (postParameters != null && !postParameters.isEmpty()) { conn.setRequestMethod("POST"); try (OutputStream requestBody = conn.getOutputStream()) { boolean first = true; for (Map.Entry<String, String> entry : postParameters.entrySet()) { if (entry.getValue() == null) continue; if (first) { first = false; } else { requestBody.write('&'); } requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes()); requestBody.write('='); requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes()); } } } else { conn.setRequestMethod("GET"); } StringBuilder responseBody = new StringBuilder(); if (conn.getResponseCode() >= 400) { StringBuilder serverMessage = new StringBuilder(); try (InputStream errorStream = conn.getErrorStream()) { if (errorStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = errorStream.read(buffer); if (read <= 0) break; serverMessage.append(new String(buffer, 0, read)); } } } switch (conn.getResponseCode()) { case HttpServletResponse.SC_NOT_FOUND: responseBody.append("Kotlin compile server not found"); break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: responseBody.append("Kotlin compile server is temporary overloaded"); break; default: responseBody = serverMessage; break; } } else { try (InputStream inputStream = conn.getInputStream()) { if (inputStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = inputStream.read(buffer); if (read <= 0) break; responseBody.append(new String(buffer, 0, read)); } } } } writeResponse(request, response, responseBody.toString(), conn.getResponseCode()); } catch (SocketTimeoutException e) { writeResponse(request, response, "Compile server connection timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT); } catch (Exception e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "", "Can't forward request to Kotlin compile server"); writeResponse(request, response, "Can't send your request to Kotlin compile server", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.codemucker.testserver.capturing.CapturedRequest.java
public CapturedRequest(final HttpServletRequest req) { scheme = req.getScheme();//from www . ja v a2s . c o m host = req.getServerName(); port = req.getServerPort(); contextPath = req.getContextPath(); servletPath = req.getServletPath(); pathInfo = req.getPathInfo(); characterEncoding = req.getCharacterEncoding(); method = req.getMethod(); final Cookie[] cookies = req.getCookies(); // cookies if (cookies != null) { for (final Cookie cookie : cookies) { this.cookies.add(new CapturedCookie(cookie)); } } // headers for (@SuppressWarnings("unchecked") final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) { final String name = names.nextElement(); @SuppressWarnings("unchecked") final Enumeration<String> values = req.getHeaders(name); if (values != null) { for (; values.hasMoreElements();) { this.addHeader(new CapturedHeader(name, values.nextElement())); } } } // if we use the normal 'toString' on maps, and arrays, we get pretty // poor results // Use ArrayLists instead to get a nice output @SuppressWarnings("unchecked") final Map<String, String[]> paramMap = req.getParameterMap(); if (paramMap != null) { for (final String key : paramMap.keySet()) { final String[] vals = paramMap.get(key); this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals))); } } // handle multipart posts if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); try { @SuppressWarnings("unchecked") final List<FileItem> items = upload.parseRequest(req); for (final FileItem item : items) { fileItems.add(new CapturedFileItem(item)); } } catch (final FileUploadException e) { throw new RuntimeException("Error handling multipart content", e); } } }