List of usage examples for javax.servlet.http HttpServletResponseWrapper HttpServletResponseWrapper
public HttpServletResponseWrapper(HttpServletResponse response)
From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java
private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override/* w ww . j a v a 2 s . co m*/ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }); server.start(); try { int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort(); MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http", "localhost", localPort, "fuse", "fuse", null); MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()).andReturn(path); EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() { private int i; @Override public int read() throws IOException { if (i >= contents.length) { return -1; } return (contents[i++] & 0xFF); } }); EasyMock.expect(request.getHeader("X-Location")).andReturn(location); final Map<String, String> headers = new HashMap<>(); HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class); HttpServletResponse response = new HttpServletResponseWrapper(rm) { @Override public void addHeader(String name, String value) { headers.put(name, value); } }; response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(request, rm); servlet.init(); servlet.doPut(request, response); EasyMock.verify(request, rm); Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location")); return headers; } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:org.apache.solr.security.GenericHadoopAuthPlugin.java
@Override public boolean doAuthenticate(ServletRequest request, ServletResponse response, FilterChain filterChain) throws Exception { final HttpServletResponse frsp = (HttpServletResponse) response; // Workaround until HADOOP-13346 is fixed. HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) { @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this" + "is providing a CloseShield on top of that") @Override//from w w w.j a va2 s . c om public PrintWriter getWriter() throws IOException { final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) { @Override public void close() { }; }; return pw; } }; authFilter.doFilter(request, rspCloseShield, filterChain); if (authFilter instanceof HadoopAuthFilter) { // delegation token mgmt. String requestContinuesAttr = (String) request.getAttribute(REQUEST_CONTINUES_ATTR); if (requestContinuesAttr == null) { log.warn("Could not find " + REQUEST_CONTINUES_ATTR); return false; } else { return Boolean.parseBoolean(requestContinuesAttr); } } return true; }
From source file:org.apache.solr.security.KerberosPlugin.java
@Override public boolean doAuthenticate(ServletRequest req, ServletResponse rsp, FilterChain chain) throws Exception { log.debug("Request to authenticate using kerberos: " + req); final HttpServletResponse frsp = (HttpServletResponse) rsp; // kerberosFilter may close the stream and write to closed streams, // see HADOOP-13346. To work around, pass a PrintWriter that ignores // closes/*from w w w . j av a2s . co m*/ HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) { @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this" + "is providing a CloseShield on top of that") @Override public PrintWriter getWriter() throws IOException { final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) { @Override public void close() { }; }; return pw; } }; kerberosFilter.doFilter(req, rspCloseShield, chain); String requestContinuesAttr = (String) req .getAttribute(RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR); if (requestContinuesAttr == null) { log.warn("Could not find " + RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR); return false; } else { return Boolean.parseBoolean(requestContinuesAttr); } }
From source file:org.dd4t.mvc.utils.RenderUtils.java
/** * Dispatch a url to a request dispatcher while buffering the output in a string * (and not directly to the response's writer). *//*from ww w .j a va 2 s . co m*/ public static String dispatchBufferedRequest(final HttpServletRequest request, final HttpServletResponse response, final String url) throws ServletException, IOException { long time = System.currentTimeMillis(); final RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(url); final HttpServletResponse responseWrapper = new HttpServletResponseWrapper(response) { private CharArrayWriter output = new CharArrayWriter(); @Override public String toString() { return output.toString(); } @Override public PrintWriter getWriter() { return new PrintWriter(output); } }; dispatcher.include(request, responseWrapper); time = System.currentTimeMillis() - time; LOG.debug("dispatchBufferedRequest {}, takes: {} ms.", url, time); return responseWrapper.toString(); }
From source file:org.docx4j.template.jsp.engine.JspTemplateImpl.java
private void doInterpret(String requestURL, Map<String, Object> variables, OutputStream output) throws IOException, ServletException { /**/*from ww w .ja v a2 s.c o m*/ * ServletContext?RequestDispatcher */ ServletContext sc = request.getSession().getServletContext(); /** * ???reqeustDispatcher */ RequestDispatcher rd = sc.getRequestDispatcher(requestURL); /** * ByteArrayOutputStream?,?? */ final ByteArrayOutputStream baos = new ByteArrayOutputStream(); /** * ServletOutputStreamwrite */ final ServletOutputStream outputStream = new ServletOutputStream() { public void write(int b) throws IOException { /** * ? */ baos.write(b); } @SuppressWarnings("unused") public boolean isReady() { return false; } }; /** * OutputStream PrintWriter * OutputStreamWriter ????? charset ???? */ final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding()), true); /** * ?HttpServletResponse??response */ HttpServletResponse resp = new HttpServletResponseWrapper(response) { /** * getOutputStream(ServletResponse)ServletOutputStream * ?response * ?byteArrayOutputStream */ public ServletOutputStream getOutputStream() { return outputStream; } /** * ?getWriter(ServletResponse)PrintWriter * ??? */ public PrintWriter getWriter() { return pw; } }; /** * ?jsp RequestDispatcher.include(ServletRequest request, * ServletResponse response) RequestDispatcher??response */ rd.include(request, resp); pw.flush(); /** * ByteArrayOutputStreamwriteTo?????ByteArray */ baos.writeTo(output); }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void basicFilterTest22(String servlet1Pattern, String servlet2Pattern, String filterPattern, String expected, String[] dispatchers) throws Exception { final AtomicReference<HttpServletRequestWrapper> httpServletRequestWrapper = new AtomicReference<HttpServletRequestWrapper>(); final AtomicReference<HttpServletResponseWrapper> httpServletResponseWrapper = new AtomicReference<HttpServletResponseWrapper>(); Servlet servlet1 = new BaseServlet() { private static final long serialVersionUID = 1L; @Override//from w ww. j a va 2s . com protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("index.jsp").forward(request, response); } }; Servlet servlet2 = new BaseServlet("a") { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ((httpServletRequestWrapper.get() != null) && !request.equals(httpServletRequestWrapper.get())) { throw new ServletException("not the same request"); } if ((httpServletResponseWrapper.get() != null) && !response.equals(httpServletResponseWrapper.get())) { throw new ServletException("not the same response"); } response.getWriter().print(content); } }; Filter filter = new TestFilter() { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.getWriter().write('b'); httpServletRequestWrapper.set(new HttpServletRequestWrapper((HttpServletRequest) request)); httpServletResponseWrapper.set(new HttpServletResponseWrapper((HttpServletResponse) response)); chain.doFilter(httpServletRequestWrapper.get(), httpServletResponseWrapper.get()); response.getWriter().write('b'); } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, servlet1Pattern); registrations.add(getBundleContext().registerService(Servlet.class, servlet1, props)); props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, servlet2Pattern); registrations.add(getBundleContext().registerService(Servlet.class, servlet2, props)); props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_NAME, "F22"); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_DISPATCHER, dispatchers); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, filterPattern); registrations.add(getBundleContext().registerService(Filter.class, filter, props)); String response = requestAdvisor.request("f22/a"); Assert.assertEquals(expected, response); }
From source file:ORG.oclc.os.ipUseThrottleFilter.ipUseThrottleFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String longAddr = null, shortAddr, s, transactionKey = null; int count;// w ww .j av a2 s .c om boolean ignorable = false; synchronized (simultaneousRequestsByShortIPAddr) { if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) { log.error("This system has exceeded the maxTotalSimultaneousRequests limit of " + maxTotalSimultaneousRequests); log.error(simultaneousRequestsByShortIPAddr); for (String str : simultaneousRequests) log.error(str); ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body><h1>Service Temporarily Unavailable</h1>"); writer.println( "The system is experiencing a severe load and is temporarily unable to accept new requests"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } if (addressInHeader != null) { @SuppressWarnings("unchecked") Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader); while (addrs.hasMoreElements()) { longAddr = addrs.nextElement(); if (longAddr == null) { if (++addressInHeaderErrorCount < 10) log.error("Expected a " + addressInHeader + " header but got null"); continue; } if (longAddr.lastIndexOf('.') >= 0) break; } } if (longAddr == null) longAddr = request.getRemoteAddr(); int i = longAddr.lastIndexOf('.'); if (i < 0) { log.error("bogus IP address: '" + longAddr + "'"); longAddr = "0.0.0.0"; } shortAddr = longAddr.substring(0, i); // trim off 4th number group // that lets us spot requests from clusters s = equivalentAddresses.get(shortAddr); // map one short addr to another? if (s != null) shortAddr = s; if (ignorableAddresses.contains(shortAddr)) { ignorable = true; } else { Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr); if (icount != null) count = icount; else count = 0; int maxSimultaneousRequests = (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4; if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1; if (count >= maxSimultaneousRequests) { log.error("IP addr " + shortAddr + ".* has exceeded " + maxSimultaneousRequests + " simultaneous requests!"); log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests); log.error("totalSimultaneousRequests=" + totalSimultaneousRequests); for (String str : simultaneousRequests) log.error(str); // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); // someday ((HttpServletResponse) response).setStatus(429); // too many requests response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println( "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>"); writer.println("You have exceeded the maximum simultaneous request value of " + maxSimultaneousRequests); writer.println("<p>This message and your IP address have been logged and reported</p>"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1); icount = totalRequests.get(shortAddr); if (icount != null) count = icount; else count = 0; totalRequests.put(shortAddr, count + 1); totalSimultaneousRequests++; transactionKey = new StringBuilder((new Date(System.currentTimeMillis())).toString()).append('|') .append(shortAddr).append('|').append(((HttpServletRequest) request).getQueryString()) .toString(); simultaneousRequests.add(transactionKey); } } try { HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); } finally { if (!ignorable) synchronized (simultaneousRequestsByShortIPAddr) { totalSimultaneousRequests--; simultaneousRequests.remove(transactionKey); count = simultaneousRequestsByShortIPAddr.get(shortAddr); if (count == 1) // prune them from the table simultaneousRequestsByShortIPAddr.remove(shortAddr); else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1); } } Calendar c = new GregorianCalendar(); int hour = c.get(Calendar.HOUR_OF_DAY); if (hour == 0 && nextReportingHour == 24) { // new day! // you could reset your daily limits table here nextReportingHour = 0; } if (hour >= nextReportingHour) { // generate the hourly report // you could reset your hourly limits table here nextReportingHour = hour + 1; if (log.isInfoEnabled()) { HashMap<String, Integer> map = new LinkedHashMap<String, Integer>(); List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet()); List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values()); TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues); Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]); int size = sortedArray.length; for (int i = 0; i < size; i++) map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]); Iterator<String> it = map.keySet().iterator(); String key; StringBuilder sb = new StringBuilder("Top 10 users in the last hour"); for (int i = 0; i < 10 && it.hasNext(); i++) { key = it.next(); sb.append("\n ").append(key).append(" : ").append(map.get(key)); } log.info(sb); } totalRequests.clear(); } }
From source file:org.wings.recorder.Recorder.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try {//from ww w . j a v a 2 s . c o m if (servletRequest instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; Map map = servletRequest.getParameterMap(); if (map.containsKey(RECORDER_SCRIPT)) { log.info("recorder_script " + map.get(RECORDER_SCRIPT)); String[] values = (String[]) map.get(RECORDER_SCRIPT); scriptName = values[0]; } if (map.containsKey(RECORDER_START)) { if (list != null) return; log.info(RECORDER_START); list = new LinkedList(); } else if (map.containsKey(RECORDER_STOP)) { if (list == null) return; log.info(RECORDER_STOP); writeCode(); list = null; } else if (list != null) { String resource = httpServletRequest.getPathInfo(); log.debug("PATH_INFO: " + resource); Request record; if ("GET".equalsIgnoreCase(httpServletRequest.getMethod())) record = new GET(resource); else record = new POST(resource); Enumeration parameterNames = httpServletRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); String[] values = httpServletRequest.getParameterValues(name); addEvent(record, name, values); } Enumeration headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); if (name.equalsIgnoreCase("cookie") || name.equalsIgnoreCase("referer")) continue; addHeader(record, name, httpServletRequest.getHeader(name)); } list.add(record); } } } finally { if (servletResponse instanceof HttpServletResponse) { filterChain.doFilter(servletRequest, new HttpServletResponseWrapper((HttpServletResponse) servletResponse) { public ServletOutputStream getOutputStream() throws IOException { final ServletOutputStream out = super.getOutputStream(); return new ServletOutputStream() { public void write(int b) throws IOException { out.write(b); } public void close() throws IOException { super.println("<hr/><div align=\"center\">"); super.println("<form method=\"get\" action=\"\">"); super.println("<input type=\"text\" name=\"recorder_script\" value=\"" + scriptName + "\">"); super.println( "<input type=\"submit\" name=\"recorder_start\" value=\"start\">"); super.println( "<input type=\"submit\" name=\"recorder_stop\" value=\"stop\">"); super.println("</div></form>"); super.close(); } }; } }); } else filterChain.doFilter(servletRequest, servletResponse); } }
From source file:servletunit.struts.MockStrutsTestCase.java
/** * Returns an HttpServletResponseWrapper object that can be used in * this test. Note that if {@link #setResponseWrapper} has not been * called, this method will return an instance of * javax.servlet.http.HttpServletResponseWrapper. *//*www. j a va2s. com*/ public HttpServletResponseWrapper getResponseWrapper() { if (logger.isDebugEnabled()) logger.debug("Entering"); init(); if (responseWrapper == null) { if (logger.isDebugEnabled()) logger.debug("Exiting"); return new HttpServletResponseWrapper(this.response); } else { if (logger.isDebugEnabled()) { logger.debug("wrapper class is '" + responseWrapper.getClass() + "'"); } if (logger.isDebugEnabled()) logger.debug("Exiting"); return responseWrapper; } }