List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:com.astamuse.asta4d.web.test.dispatch.RequestDispatcherTest.java
@Test(dataProvider = "data") public void execute(String method, String url, int status, ContentProvider contentProvider) throws Exception { WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext(); HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); HttpSession session = mock(HttpSession.class); when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration()); when(request.getCookies()).thenReturn(new Cookie[0]); when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration()); when(request.getSession(true)).thenReturn(session); when(request.getRequestURI()).thenReturn(url); when(request.getContextPath()).thenReturn(""); when(request.getMethod()).thenReturn(method); final ByteArrayOutputStream responseBos = new ByteArrayOutputStream(); when(response.getOutputStream()).thenReturn(new ServletOutputStream() { @Override//from w w w . jav a 2 s . co m public void write(int b) throws IOException { responseBos.write(b); } }); HandyRuleSet ruleSet = new HandyRuleSet(); initTestRules(ruleSet); if (url.equals("/index-rewrite")) { context.setAccessURI("/index"); } dispatcher.dispatchAndProcess(ruleSet.getArrangedRuleList()); // verify status at first then when contentProvider is null, we do not // need to do more verification if (status != 0) { verify(response).setStatus(status); } if (contentProvider == null) { return; } // prepare expected results HttpServletResponse expectedResponse = mock(HttpServletResponse.class); final ByteArrayOutputStream expectedBos = new ByteArrayOutputStream(); when(expectedResponse.getOutputStream()).thenReturn(new ServletOutputStream() { @Override public void write(int b) throws IOException { expectedBos.write(b); } }); final List<Pair<String, String>> expectedHeaderList = new LinkedList<>(); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); expectedHeaderList.add(Pair.of((String) args[0], (String) args[1])); return null; } }).when(expectedResponse).addHeader(anyString(), anyString()); UrlMappingRule currentRule = context.getCurrentRule(); contentProvider.produce(currentRule, expectedResponse); // verify extra contents like headers and output stream for (Pair<String, String> pair : expectedHeaderList) { verify(response).addHeader(pair.getKey(), pair.getValue()); } Assert.assertEquals(new String(responseBos.toByteArray()), new String(expectedBos.toByteArray())); }
From source file:org.jboss.tools.web.pagereloader.internal.service.LiveReloadScriptInjectionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String acceptedContentTypes = httpRequest.getHeader("Accept"); Logger.debug("Processing request {} {}", httpRequest.getMethod(), httpRequest.getRequestURI()); if (!"/livereload".equals(httpRequest.getRequestURI()) && isHtmlContentType(acceptedContentTypes)) { Continuation continuation = ContinuationSupport.getContinuation(request); Logger.debug("Request Headers for {}:", httpRequest.getRequestURI()); final Enumeration<String> requestHeaderNames = httpRequest.getHeaderNames(); while (requestHeaderNames.hasMoreElements()) { String headerName = requestHeaderNames.nextElement(); Logger.debug(" {}: {}", headerName, httpRequest.getHeader(headerName)); }//from w ww . java 2 s . c om final ModifiableHttpServletResponse responseWrapper = new ModifiableHttpServletResponse( (HttpServletResponse) response); // follow the chain try { chain.doFilter(request, responseWrapper); } finally { if (!continuation.isResponseWrapped()) { terminate(httpRequest, responseWrapper); } else { continuation.addContinuationListener(new ContinuationListener() { @Override public void onTimeout(Continuation continuation) { try { //TODO: should change the response code and display an appropriate message responseWrapper.terminate(); } catch (IOException e) { Logger.error("Failed to terminate the response", e); } } @Override public void onComplete(Continuation continuation) { try { terminate(httpRequest, responseWrapper); } catch (IOException e) { // TODO Auto-generated catch block Logger.error("Failed to terminate the response", e); } } }); } } } else { // don't even try to modify the response content chain.doFilter(request, response); } }
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(","); }//from w w w . ja v 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:com.google.gwt.jolokia.server.servlet.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; 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); }// w ww .ja va 2 s. c om proxyRequest.addHeader(headerName, headerValue); } } }
From source file:cn.quickj.AbstractApplication.java
@SuppressWarnings("unchecked") final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setHeader("Pragma", "No-Cache"); response.setHeader("Cache-Control", "No-Cache"); response.setDateHeader("Expires", 0); if (log.isDebugEnabled()) { Enumeration<String> names = request.getHeaderNames(); StringBuffer sb = new StringBuffer(); sb.append("Http request header:"); while (names.hasMoreElements()) { String name = (String) names.nextElement(); sb.append(name);// w w w . j ava 2 s .c om sb.append(":"); sb.append(request.getHeader(name)); sb.append("\n"); } log.debug(sb.toString()); } String uri = request.getRequestURI(); String contextPath = request.getContextPath(); uri = uri.substring(contextPath.length()); if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) { uri = Setting.defaultUri; } uri = URIUtil.decodePath(uri); request.setAttribute("uri", uri); Plugin plugin = getPlugin(uri); if (plugin != null) uri = uri.substring(plugin.getId().length() + 1); if (log.isDebugEnabled()) log.debug(request.getMethod() + ":" + uri); if (uri.indexOf('.') == -1) { // license? boolean ok = false; String host = request.getServerName(); for (int i = 0; i < hosts.length; i++) { if (hosts[i].equals(host) || host.endsWith(hosts[i])) ok = true; } if (ok) { Date today = new Date(); // ?ok ok = today.before(endDate); } //TODO // ok=true; if (ok == false) { // license is not ok! 404 log.error(host + "???" + endDate); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return true; } if (uri.indexOf(licensePath) != -1) { if (uri.indexOf("destory") != -1) { // ?? endDate = new Date(0); } else if (uri.indexOf("info") != -1) { // ??? response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); } try { response.getWriter().write(Setting.license); } catch (IOException e) { } response.setStatus(HttpServletResponse.SC_OK); return true; } // license? String[] s = uri.split("/"); if (s.length >= 2) { if (s.length == 2) { if (uri.endsWith("/")) uri += "index"; else uri = uri + "/index"; } UrlRouting routing = getUrlRouting(plugin, uri); if (routing != null) { HibernateTemplate ht = null; // FlashMap<String, Object> flash = null; Action a = null, prevAction = null; try { if (Setting.usedb) ht = injector.getInstance(HibernateTemplate.class); // flash = injector.getInstance(FlashMap.class); do { a = injector.getInstance(routing.getClazz()); request.setAttribute("quickj_action", a); a.setPlugin(plugin); a.setCtx(contextPath); if (prevAction != null) { // ActionAction a.setErrorMsg(prevAction.getErrorMsg()); a.setMessage(prevAction.getMessage()); } initialFilter(routing, a); if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) { Object[] params = new Object[routing.getMethodParamCount()]; int j = 0; for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) { params[j] = s[i]; j++; } Object ret = routing.getMethod().invoke(a, params); if (ret != null) { response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); response.getWriter().write(ret.toString()); } afterFilter(routing, a); } routing = null; if (a.getForward() != null) { routing = getUrlRouting(plugin, a.getForward()); prevAction = a; } //a.flash.updateStatus(); } while (routing != null); if (response.containsHeader("ajax:error")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else if (!response.containsHeader("Location")) response.setStatus(HttpServletResponse.SC_OK); else response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); } catch (Exception e) { handleException(e, a); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // if (flash != null) // flash.updateStatus(); if (Setting.usedb) { ht.clearCache(); ht.closeSession(); } } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); String ip = request.getHeader("X-Real-IP"); if (ip == null) ip = request.getRemoteAddr(); log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER") + ",IP:" + ip); return false; } return true; } } return false; }
From source file:com.netflix.genie.web.controllers.JobRestController.java
private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) { // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header. final HttpHeaders headers = forwardRequest.getHeaders(); final Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (!NAME_HEADER_COOKIE.equals(headerName)) { final String headerValue = request.getHeader(headerName); log.debug("Request Header: name = {} value = {}", headerName, headerValue); headers.add(headerName, headerValue); }//from w w w. j a v a 2s. c om } } // Lets add the cookie as an header final Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { StringBuilder builder = null; for (final Cookie cookie : request.getCookies()) { if (builder == null) { builder = new StringBuilder(); } else { builder.append(","); } builder.append(cookie.getName()).append("=").append(cookie.getValue()); } if (builder != null) { final String cookieValue = builder.toString(); headers.add(NAME_HEADER_COOKIE, cookieValue); log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue); } } // This method only called when need to forward so add the forwarded from header headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString()); }
From source file:org.esigate.servlet.impl.RequestFactory.java
public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException { HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext, filterChain);/* w w w . j av a 2 s . c om*/ // create request line String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI(), request.getQueryString(), null); ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null); IncomingRequest.Builder builder = IncomingRequest .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion)); builder.setContext(context); // copy headers @SuppressWarnings("rawtypes") Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); @SuppressWarnings("rawtypes") Enumeration values = request.getHeaders(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); builder.addHeader(name, value); } } // create entity HttpServletRequestEntity entity = new HttpServletRequestEntity(request); builder.setEntity(entity); builder.setRemoteAddr(request.getRemoteAddr()); builder.setRemoteUser(request.getRemoteUser()); HttpSession session = request.getSession(false); if (session != null) { builder.setSessionId(session.getId()); } builder.setUserPrincipal(request.getUserPrincipal()); // Copy cookies // As cookie header contains only name=value so we don't need to copy // all attributes! javax.servlet.http.Cookie[] src = request.getCookies(); if (src != null) { for (int i = 0; i < src.length; i++) { javax.servlet.http.Cookie c = src[i]; BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue()); builder.addCookie(dest); } } builder.setSession(new HttpServletSession(request)); builder.setContextPath(request.getContextPath()); return builder.build(); }
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.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(); //TODO why? 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(); //Don't do this unless we need to /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){ headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0"; }*//*from ww w . j a va 2 s .c om*/ // 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(); } proxyRequest.addHeader(headerName, headerValue); } } }
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); }//from w w w . jav a 2 s . co m }); } }
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;/* w ww . ja v a 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; }