List of usage examples for javax.servlet.http HttpServletResponseWrapper HttpServletResponseWrapper
public HttpServletResponseWrapper(HttpServletResponse response)
From source file:de.terrestris.shogun.security.ShogunAuthProcessingFilter.java
/** * React on unsuccessful authentication. * We again intercept the response and return a JSON object with a flag indicating unsuccessful login. * * @see WebContent/client/login.js/*from ww w.j av a2 s .c o m*/ */ @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { super.unsuccessfulAuthentication(request, response, failed); HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response); Writer out = responseWrapper.getWriter(); out.write("{success:false}"); out.close(); }
From source file:de.betterform.agent.web.filter.XFormsFilter.java
/** * The actual filtering method//from w ww .j av a 2s .c o m * todo: add request attribute to set baseURI * * @see http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html#doFilter(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse,%20javax.servlet.FilterChain) */ public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain) throws IOException, ServletException { //ensure correct Request encoding if (srvRequest.getCharacterEncoding() == null) { srvRequest.setCharacterEncoding(defaultRequestEncoding); } HttpServletRequest request = (HttpServletRequest) srvRequest; HttpServletResponse response = (HttpServletResponse) srvResponse; HttpSession session = request.getSession(true); /* if header "betterform-internal is present this means that the internal http client of the processor is the originator of the incoming request. Since this may not be processed we skip these requests by simply calling the servlet chain. As the contenttype may not be present for such requests we have to determine the mimetype by the file ending of the requested resource. */ //Check if MEDIATYPE is set if so we will handle response as XForms if (request.getHeader(BetterFORMConstants.BETTERFORM_INTERNAL) != null) { LOG.warn("Request from internal betterForm HTTP Client arrived in XFormsFilter"); String requestURI = request.getRequestURI(); String mimeType = webFactory.getServletContext().getMimeType(requestURI); if (LOG.isDebugEnabled()) { LOG.debug("request URI: " + requestURI); LOG.debug("mimeType: " + mimeType); } if (mimeType != null) { srvResponse.setContentType(mimeType); } else { LOG.warn("no contenttype set for internal request"); // throw new ServletException("Contenttype of " + requestURI + " unknown. Please configure your webcontainer appropriately."); } filterChain.doFilter(srvRequest, srvResponse); return; } if (request.getParameter("source") != null) { srvResponse.setContentType("text/plain"); // override setContentType to keep "text/plain" as content type. HttpServletResponseWrapper resp = new HttpServletResponseWrapper((HttpServletResponse) srvResponse) { public void setContentType(String s) { return; } }; filterChain.doFilter(srvRequest, resp); return; } if (request.getParameter("isUpload") != null) { //Got an upload... handleUpload(request, response, session); //TODO: XFORMS PROCESSING: do we need to exit? } else if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE) != null) { doSubmissionReplaceAll(request, response); } else if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE_XFORMS) != null) { doSubmissionReplaceAllXForms(request, response, session); } else { /* do servlet request */ LOG.info("Passing to Chain"); BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper( (HttpServletResponse) srvResponse); filterChain.doFilter(srvRequest, bufResponse); LOG.info("Returned from Chain"); //handleResponse(srvResponse, request, response, session, bufResponse, webFactory); // response is contains no betterFORM relevant content so it is not buffered and cannot be processed if (!bufResponse.isBuffered()) { return; } // response is already committed to the client, so nothing is to // be done if (bufResponse.isCommitted()) { return; } //pass to request object request.setAttribute(WebFactory.USER_AGENT, XFormsFilter.USERAGENT); /* dealing with response from chain */ if (handleResponseBody(request, bufResponse)) { byte[] data = prepareData(bufResponse); if (data.length > 0) { request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data)); } } if (handleRequestAttributes(request)) { bufResponse.getOutputStream().close(); LOG.info("Start Filter XForm"); processXForms(request, response, session); LOG.info("End Render XForm"); } else { srvResponse.getOutputStream().write(bufResponse.getData()); srvResponse.getOutputStream().close(); } } }
From source file:com.farmafene.samples.mtom.tools.DumpFilter.java
@Override public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; final BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); if (this.dumpRequest) { LOGGER.warn("REQUEST ---> {}", new String(bufferedRequest.getBuffer())); }/*from ww w . ja v a 2 s. c o m*/ final HttpServletResponse response = (HttpServletResponse) servletResponse; final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); final HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) { @Override public PrintWriter getWriter() { return pw.getWriter(); } @Override public ServletOutputStream getOutputStream() { return pw.getStream(); } }; filterChain.doFilter(bufferedRequest, wrappedResp); final byte[] bytes = pw.toByteArray(); response.getOutputStream().write(bytes); if (this.dumpResponse) { LOGGER.warn("RESPONSE ---> {}", new String(bytes)); } }
From source file:org.apache.solr.servlet.SolrDispatchFilter.java
/** * Wrap the response's output stream with a close shield, as if by a {@link CloseShieldOutputStream}. If this is a * retry, we will assume that the stream has already been wrapped and do nothing. * * @param response The response to wrap. * @param retry If this response corresponds to an original request or a retry. * @return A response object with an {@link OutputStream} that will ignore calls to close. *//*from w w w . j a va 2 s . c om*/ private ServletResponse closeShield(ServletResponse response, boolean retry) { if (testMode && !retry) { return new HttpServletResponseWrapper((HttpServletResponse) response) { ServletOutputStream stream; @Override public ServletOutputStream getOutputStream() throws IOException { // Lazy stream creation if (stream == null) { stream = new ServletOutputStreamWrapper(super.getOutputStream()) { @Override public void close() { assert false : "Attempted close of response output stream."; } }; } return stream; } }; } else { return response; } }
From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.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//from w w w . j av a 2 s . com 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 = server.getConnectors()[0].getLocalPort(); List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central"); RuntimeProperties props = new MockRuntimeProperties(); MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null); MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer); 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); EasyMock.expect(request.getParameter("profile")).andReturn(profile); EasyMock.expect(request.getParameter("version")).andReturn(version); 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.start(); 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:net.ymate.framework.core.util.WebUtils.java
/** * @param request HttpServletRequest * @param response HttpServletResponse * @param jspFile JSP/*from w w w .j ava 2 s .co m*/ * @param charsetEncoding ? * @return JSPHTML?? * @throws ServletException ? * @throws IOException ? */ public static String includeJSP(HttpServletRequest request, HttpServletResponse response, String jspFile, String charsetEncoding) throws ServletException, IOException { final OutputStream _output = new ByteArrayOutputStream(); final PrintWriter _writer = new PrintWriter(new OutputStreamWriter(_output)); final ServletOutputStream _servletOutput = new ServletOutputStream() { @Override public void write(int b) throws IOException { _output.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { _output.write(b, off, len); } }; HttpServletResponse _response = new HttpServletResponseWrapper(response) { @Override public ServletOutputStream getOutputStream() { return _servletOutput; } @Override public PrintWriter getWriter() { return _writer; } }; charsetEncoding = StringUtils.defaultIfEmpty(charsetEncoding, response.getCharacterEncoding()); _response.setCharacterEncoding(StringUtils.defaultIfEmpty(charsetEncoding, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); request.getRequestDispatcher(jspFile).include(request, _response); _writer.flush(); return _output.toString(); }
From source file:net.ymate.platform.mvc.web.view.impl.JspView.java
public void render(final OutputStream output) throws Exception { // JSP?????UTF-8 this.processPath(); final ServletOutputStream _oStream = new ServletOutputStream() { @Override/*from w w w . ja v a 2s . c o m*/ public void write(int b) throws IOException { output.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { output.write(b, off, len); } }; final PrintWriter _printWriter = new PrintWriter(new OutputStreamWriter(output)); HttpServletResponse _newResponse = new HttpServletResponseWrapper(WebContext.getResponse()) { @Override public ServletOutputStream getOutputStream() { return _oStream; } @Override public PrintWriter getWriter() { return _printWriter; } }; _newResponse.setCharacterEncoding(WebMVC.getConfig().getCharsetEncoding()); WebContext.getRequest().getRequestDispatcher(this.path).include(WebContext.getRequest(), _newResponse); _printWriter.flush(); }
From source file:net.ymate.platform.webmvc.view.impl.JspView.java
public void render(final OutputStream output) throws Exception { __doProcessPath();/* ww w . ja v a2s.c o m*/ // JSP?(???), ?UTF-8 final ServletOutputStream _oStream = new ServletOutputStream() { public void write(int b) throws IOException { output.write(b); } public void write(byte[] b, int off, int len) throws IOException { output.write(b, off, len); } }; final PrintWriter _printWriter = new PrintWriter(new OutputStreamWriter(output)); // HttpServletRequest _request = WebContext.getRequest(); HttpServletResponse _response = WebContext.getResponse(); HttpServletResponse _newResponse = new HttpServletResponseWrapper(_response) { public ServletOutputStream getOutputStream() { return _oStream; } public PrintWriter getWriter() { return _printWriter; } }; _request.getRequestDispatcher(__path).include(_request, _newResponse); _printWriter.flush(); }
From source file:org.ajax4jsf.webapp.BaseFilter.java
/** * Method catches upload files request. Request parameter * <b>org.ajax4jsf.Filter.UPLOAD_FILES_ID</b> indicates if request * generated by rich-upload component. If it was detected custom parsing * request should be done. Processing information about percent of * completion and file size will be put into session scope. * //from w ww . j a va 2 s .c o m * @param request * @param response * @return * @throws IOException * @throws ServletException */ protected void processUploadsAndHandleRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; Map<String, String> queryParamMap = parseQueryString(httpRequest.getQueryString()); String uid = queryParamMap.get(FileUploadConstants.UPLOAD_FILES_ID); if (uid != null) { if (isMultipartRequest(httpRequest)) { MultipartRequest multipartRequest = new MultipartRequest(httpRequest, createTempFiles, maxRequestSize, uid); Object oldAttributeValue = httpRequest .getAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME); httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, multipartRequest); try { if (isFileSizeRestricted(request, maxRequestSize)) { boolean sendError = Boolean.parseBoolean(queryParamMap.get(SEND_HTTP_ERROR)); if (sendError) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); System.err.println("ERROR " + HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE + "request entity is larger than the server is willing or able to process."); return; } else { printResponse(response, "<html id=\"_richfaces_file_upload_size_restricted\"></html>"); } } else if (!checkFileCount(httpRequest, queryParamMap.get("id"))) { printResponse(response, "<html id=\"_richfaces_file_upload_forbidden\"></html>"); } else { handleRequest(multipartRequest, multipartRequest.isFormUpload() ? response : new HttpServletResponseWrapper((HttpServletResponse) response) { @Override public void setContentType(String type) { super.setContentType(BaseXMLFilter.TEXT_HTML + ";charset=UTF-8"); } }, chain); if (!multipartRequest.isDone()) { printResponse(response, "<html id=\"_richfaces_file_upload_stopped\"></html>"); } } } finally { httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, oldAttributeValue); multipartRequest.clearRequestData(); } } else { handleRequest(request, response, chain); } } else { handleRequest(request, response, chain); } }
From source file:org.apache.karaf.cave.server.maven.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//from ww w. j a v a2 s.c o 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); CaveMavenServlet servlet = new CaveMavenServlet(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); } @Override public boolean isFinished() { // TODO Auto-generated method stub return false; } @Override public boolean isReady() { // TODO Auto-generated method stub return true; } @Override public void setReadListener(ReadListener readListener) { // TODO Auto-generated method stub } }); 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); } } }