Java Code Examples for javax.servlet.http.HttpServletResponse#resetBuffer()
The following examples show how to use
javax.servlet.http.HttpServletResponse#resetBuffer() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestInputBuffer.java From Tomcat8-Source-Read with MIT License | 7 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); Reader r = req.getReader(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); Writer w = resp.getWriter(); try { // Copy one character at a time int c = r.read(); while (c != -1) { w.write(c); c = r.read(); } w.close(); } catch (MalformedInputException mie) { resp.resetBuffer(); w.write("FAILED"); } }
Example 2
Source File: CorsFilter.java From Tomcat8-Source-Read with MIT License | 6 votes |
/** * Handles a CORS request that violates specification. * * @param request The {@link HttpServletRequest} object. * @param response The {@link HttpServletResponse} object. * @param filterChain The {@link FilterChain} object. */ private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) { String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN); String method = request.getMethod(); String accessControlRequestHeaders = request.getHeader( REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.resetBuffer(); if (log.isDebugEnabled()) { // Debug so no need for i18n StringBuilder message = new StringBuilder("Invalid CORS request; Origin="); message.append(origin); message.append(";Method="); message.append(method); if (accessControlRequestHeaders != null) { message.append(";Access-Control-Request-Headers="); message.append(accessControlRequestHeaders); } log.debug(message.toString()); } }
Example 3
Source File: TestInputBuffer.java From tomcatsrc with Apache License 2.0 | 6 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); Reader r = req.getReader(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); Writer w = resp.getWriter(); try { // Copy one character at a time int c = r.read(); while (c != -1) { w.write(c); c = r.read(); } w.close(); } catch (MalformedInputException mie) { resp.resetBuffer(); w.write("FAILED"); } }
Example 4
Source File: CORSFilter.java From para with Apache License 2.0 | 6 votes |
/** * Handles a CORS request that violates specification. * * @param request The {@link HttpServletRequest} object. * @param response The {@link HttpServletResponse} object. * @param filterChain The {@link FilterChain} object. */ public void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) { String origin = request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN); String method = request.getMethod(); String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS); String message = "Invalid CORS request; Origin=" + origin + ";Method=" + method; if (accessControlRequestHeaders != null) { message = message + ";Access-Control-Request-Headers=" + accessControlRequestHeaders; } response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.resetBuffer(); log(message); }
Example 5
Source File: CorsFilter.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
/** * Handles a CORS request that violates specification. * * @param request * The {@link HttpServletRequest} object. * @param response * The {@link HttpServletResponse} object. * @param filterChain * The {@link FilterChain} object. */ private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) { String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN); String method = request.getMethod(); String accessControlRequestHeaders = request.getHeader( REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.resetBuffer(); if (log.isDebugEnabled()) { // Debug so no need for i18n StringBuilder message = new StringBuilder("Invalid CORS request; Origin="); message.append(origin); message.append(";Method="); message.append(method); if (accessControlRequestHeaders != null) { message.append(";Access-Control-Request-Headers="); message.append(accessControlRequestHeaders); } log.debug(message.toString()); } }
Example 6
Source File: TestInputBuffer.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); Reader r = req.getReader(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); Writer w = resp.getWriter(); try { // Copy one character at a time int c = r.read(); while (c != -1) { w.write(c); c = r.read(); } w.close(); } catch (MalformedInputException mie) { resp.resetBuffer(); w.write("FAILED"); } }
Example 7
Source File: TestOutputBuffer.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer w = resp.getWriter(); w.write("OK"); resp.resetBuffer(); w.write("OK"); }
Example 8
Source File: ShibcasAuthServlet.java From shib-cas-authn3 with Apache License 2.0 | 5 votes |
private void loadErrorPage(final HttpServletRequest request, final HttpServletResponse response) { final RequestDispatcher requestDispatcher = request.getRequestDispatcher("/no-conversation-state.jsp"); try { requestDispatcher.forward(request, response); } catch (final Exception e) { logger.error("Error rendering the empty conversation state (shib-cas-authn3) error view."); response.resetBuffer(); response.setStatus(404); } }
Example 9
Source File: TestOutputBuffer.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer w = resp.getWriter(); w.write("OK"); resp.resetBuffer(); w.write("OK"); }
Example 10
Source File: PluginHelper.java From odo with Apache License 2.0 | 5 votes |
public static void writeResponseContent(HttpServletResponse response, String content) throws IOException { // check to see if this is chunked boolean chunked = false; if (response.containsHeader(PluginHelper.STRING_TRANSFER_ENCODING) && response.getHeader(PluginHelper.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) { response.setHeader(PluginHelper.STRING_CONNECTION, PluginHelper.STRING_CHUNKED); chunked = true; } // check to see if this content is supposed to be compressed // if so recompress it boolean isEncoded = false; ByteArrayOutputStream out = new ByteArrayOutputStream(); if (response.getHeader("content-encoding") != null && response.getHeader("content-encoding").equals("gzip")) { // GZIP the data isEncoded = true; GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(content.getBytes()); gzip.close(); out.close(); } else if (response.getHeader("content-encoding") != null && response.getHeader("content-encoding").equals("deflate")) { // Deflate the data isEncoded = true; Deflater compressor = new Deflater(); compressor.setInput(content.getBytes()); compressor.finish(); byte[] buffer = new byte[1024]; while (!compressor.finished()) { int count = compressor.deflate(buffer); out.write(buffer, 0, count); } out.close(); compressor.end(); } // don't do this if we got a HTTP 304 since there is no data to send back if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) { if (!chunked) { // change the content length header to the new length if (content != null && !isEncoded) { response.setContentLength(content.getBytes().length); } else if (isEncoded) { response.setContentLength(out.toByteArray().length); } } OutputStream outputStreamClientResponse = response.getOutputStream(); response.resetBuffer(); if (content != null && !isEncoded) { outputStreamClientResponse.write(content.getBytes()); } else if (isEncoded) { outputStreamClientResponse.write(out.toByteArray()); } } }
Example 11
Source File: OAuthServlet.java From lams with GNU General Public License v2.0 | 5 votes |
/** Send the given parameters as a form-encoded response body. */ public static void sendForm(HttpServletResponse response, Iterable<? extends Map.Entry> parameters) throws IOException { response.resetBuffer(); response.setContentType(OAuth.FORM_ENCODED + ";charset=" + OAuth.ENCODING); OAuth.formEncode(parameters, response.getOutputStream()); }
Example 12
Source File: OAuthServlet.java From sakai with Educational Community License v2.0 | 5 votes |
/** Send the given parameters as a form-encoded response body. */ @SuppressWarnings("rawtypes") public static void sendForm(HttpServletResponse response, Iterable<? extends Map.Entry> parameters) throws IOException { response.resetBuffer(); response.setContentType(OAuth.FORM_ENCODED + ";charset=" + OAuth.ENCODING); OAuth.formEncode(parameters, response.getOutputStream()); }
Example 13
Source File: ShibcasAuthServlet.java From shib-cas-authn3 with Apache License 2.0 | 5 votes |
private void loadErrorPage(final HttpServletRequest request, final HttpServletResponse response) { final RequestDispatcher requestDispatcher = request.getRequestDispatcher("/no-conversation-state.jsp"); try { requestDispatcher.forward(request, response); } catch (final Exception e) { logger.error("Error rendering the empty conversation state (shib-cas-authn3) error view."); response.resetBuffer(); response.setStatus(404); } }
Example 14
Source File: TokenInterceptor.java From paascloud-master with Apache License 2.0 | 5 votes |
private void handleException(HttpServletResponse res) throws IOException { res.resetBuffer(); res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setContentType("application/json"); res.setCharacterEncoding("UTF-8"); res.getWriter().write("{\"code\":100009 ,\"message\" :\"解析token失败\"}"); res.flushBuffer(); }
Example 15
Source File: TestOutputBuffer.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer w = resp.getWriter(); w.write("OK"); resp.resetBuffer(); w.write("OK"); }
Example 16
Source File: FilterDispatchIntegrationTest.java From dagger-servlet with Apache License 2.0 | 4 votes |
@Test public final void testDispatchRequestToManagedPipelineWithInstance() throws ServletException, IOException { DaggerServletContextListener contextListener = new DaggerServletContextListener() { @Override protected Class<?>[] getBaseModules() { return new Class<?>[]{TestModule.class}; } @Override protected Class<?>[] getRequestScopedModules() { return new Class<?>[]{ServletRequestModule.class}; } @Override protected void configureServlets() { filter("/*").through(TestFilter.class); filter("*.html").through(TestFilter.class); filter("/*").through(new TestFilter()); // These filters should never fire filter("/index/*").through(TestFilter.class); filter("*.jsp").through(new TestFilter()); // Bind a servlet serve("*.html").with(TestServlet.class); } }; ServletContext servletContext = createMock("blah", ServletContext.class); contextListener.contextInitialized(new ServletContextEvent(servletContext)); final ObjectGraph objectGraph = contextListener.getObjectGraph(); final FilterPipeline pipeline = objectGraph.get(FilterPipeline.class); pipeline.initPipeline(null); // create ourselves a mock request with test URI HttpServletRequest requestMock = control.createMock(HttpServletRequest.class); expect(requestMock.getRequestURI()) .andReturn("/index.html") .anyTimes(); expect(requestMock.getContextPath()) .andReturn("") .anyTimes(); requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true); requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST); HttpServletResponse responseMock = control.createMock(HttpServletResponse.class); expect(responseMock.isCommitted()) .andReturn(false) .anyTimes(); responseMock.resetBuffer(); expectLastCall().anyTimes(); FilterChain filterChain = control.createMock(FilterChain.class); //dispatch request control.replay(); pipeline.dispatch(requestMock, responseMock, filterChain); pipeline.destroyPipeline(); control.verify(); TestServlet servlet = objectGraph.get(TestServlet.class); assertEquals(2, servlet.processedUris.size()); assertTrue(servlet.processedUris.contains("/index.html")); assertTrue(servlet.processedUris.contains(TestServlet.FORWARD_TO)); // 1 init/destory for the class binding and 2 inits/destroys for the 2 instance bindings assertTrue(inits == 3 && doFilters == 3 && destroys == 3, "lifecycle states did not" + " fire correct number of times-- inits: " + inits + "; dos: " + doFilters + "; destroys: " + destroys); }
Example 17
Source File: FilterDispatchIntegrationTest.java From dagger-servlet with Apache License 2.0 | 4 votes |
@Test public final void testDispatchRequestToManagedPipeline() throws ServletException, IOException { DaggerServletContextListener contextListener = new DaggerServletContextListener() { @Override protected Class<?>[] getBaseModules() { return new Class<?>[]{TestModule.class}; } @Override protected Class<?>[] getRequestScopedModules() { return new Class<?>[]{ServletRequestModule.class}; } @Override protected void configureServlets() { filter("/*").through(TestFilter.class); filter("*.html").through(TestFilter.class); filter("/*").through(TestFilter.class); // These filters should never fire filter("/index/*").through(TestFilter.class); filter("*.jsp").through(TestFilter.class); // Bind a servlet serve("*.html").with(TestServlet.class); } }; ServletContext servletContext = createMock("blah", ServletContext.class); contextListener.contextInitialized(new ServletContextEvent(servletContext)); final ObjectGraph objectGraph = contextListener.getObjectGraph(); final FilterPipeline pipeline = objectGraph.get(FilterPipeline.class); pipeline.initPipeline(null); // create ourselves a mock request with test URI HttpServletRequest requestMock = control.createMock(HttpServletRequest.class); expect(requestMock.getRequestURI()) .andReturn("/index.html") .anyTimes(); expect(requestMock.getContextPath()) .andReturn("") .anyTimes(); requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true); requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST); HttpServletResponse responseMock = control.createMock(HttpServletResponse.class); expect(responseMock.isCommitted()) .andReturn(false) .anyTimes(); responseMock.resetBuffer(); expectLastCall().anyTimes(); FilterChain filterChain = control.createMock(FilterChain.class); //dispatch request control.replay(); pipeline.dispatch(requestMock, responseMock, filterChain); pipeline.destroyPipeline(); control.verify(); TestServlet servlet = objectGraph.get(TestServlet.class); assertEquals(2, servlet.processedUris.size()); assertTrue(servlet.processedUris.contains("/index.html")); assertTrue(servlet.processedUris.contains(TestServlet.FORWARD_TO)); assertTrue(inits == 1 && doFilters == 3 && destroys == 1, "lifecycle states did not" + " fire correct number of times-- inits: " + inits + "; dos: " + doFilters + "; destroys: " + destroys); }
Example 18
Source File: ScanServlet.java From phoebus with Eclipse Public License 1.0 | 4 votes |
/** POST scan/{name}: Submit a new, named, scan * Returns ID of new scan */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // Require XML: "text/xml", "text/xml; charset=UTF-8", ... final String format = request.getContentType(); logger.log(Level.FINE, () -> "POST scan " + format); if (! format.contains("/xml")) { logger.log(Level.WARNING, "POST /scan got format '" + format + "'"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expecting XML content with scan, got format '" + format + "'"); return; } // Determine name of scan String scan_name = request.getPathInfo(); if (scan_name == null) scan_name = "Scan from " + request.getRemoteHost(); else { if (! scan_name.startsWith("/")) throw new Error("Path does not start with '/'"); scan_name = scan_name.substring(1); } // Queue unless "?queue=false" final String queue_parm = request.getParameter("queue"); final boolean queue = ! "false".equalsIgnoreCase(queue_parm); // Execute pre/post commands unless "?pre_post=false" final String pre_post_parm = request.getParameter("pre_post"); final boolean pre_post = ! "false".equalsIgnoreCase(pre_post_parm); // Read scan commands final String scan_commands = IOUtils.toString(request.getInputStream()); // Return <id> or <error> response.setContentType("text/xml"); final PrintWriter out = response.getWriter(); // Submit scan try { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Scan '" + scan_name + "':\n" + scan_commands); final long scan_id = scan_server.submitScan(scan_name, scan_commands, queue, pre_post); // Return scan ID out.print("<id>"); out.print(scan_id); out.println("</id>"); } catch (Exception ex) { logger.log(Level.WARNING, "POST /scan error", ex); response.resetBuffer(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println("<error>"); out.println("<message>" + scan_name + " failed to submit" + "</message>"); out.println("<trace>"); final StringWriter buf = new StringWriter(); ex.printStackTrace(new PrintWriter(buf)); out.println(buf.toString().replace("<", "<")); out.println("</trace>"); out.println("</error>"); response.flushBuffer(); } }
Example 19
Source File: DefaultServletRequestDispatcher.java From piranha with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void syncForward(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { try (DefaultWebApplicationRequest forwardedRequest = new DefaultWebApplicationRequest()) { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; response.resetBuffer(); forwardedRequest.setWebApplication(servletEnvironment.getWebApplication()); forwardedRequest.setContextPath(request.getContextPath()); forwardedRequest.setDispatcherType(FORWARD); forwardedRequest.setAsyncSupported(request.isAsyncSupported()); if (path != null) { setForwardAttributes(request, forwardedRequest, FORWARD_CONTEXT_PATH, FORWARD_PATH_INFO, FORWARD_QUERY_STRING, FORWARD_REQUEST_URI, FORWARD_SERVLET_PATH); forwardedRequest.setServletPath(getServletPath(path)); forwardedRequest.setQueryString(getQueryString(path)); } else { forwardedRequest.setServletPath("/" + servletEnvironment.getServletName()); } CurrentRequestHolder currentRequestHolder = updateCurrentRequest(request, forwardedRequest); try { servletEnvironment.getWebApplication().linkRequestAndResponse(forwardedRequest, servletResponse); servletEnvironment.getServlet().service(forwardedRequest, servletResponse); servletEnvironment.getWebApplication().unlinkRequestAndResponse(forwardedRequest, servletResponse); } finally { restoreCurrentRequest(currentRequestHolder, request); } response.flushBuffer(); } }
Example 20
Source File: CMSURLHandler.java From fenixedu-cms with GNU Lesser General Public License v3.0 | 4 votes |
public void handleRequest(Site site, HttpServletRequest req, HttpServletResponse res, String pageSlug) throws IOException, ServletException { if (site.getCanViewGroup().isMember(Authenticate.getUser()) || PermissionEvaluation.canAccess(Authenticate.getUser(),site)) { if (site.getPublished()) { try { String baseUrl = "/" + site.getBaseUrl(); if (pageSlug.startsWith(baseUrl)) { pageSlug = pageSlug.substring(baseUrl.length()); } if (pageSlug.endsWith("/") && !req.getRequestURI().equals(req.getContextPath() + "/")) { handleLeadingSlash(req, res, site); } else if (pageSlug.startsWith("/static/")) { handleStaticResource(req, res, site, pageSlug); } else if (pageSlug.startsWith("/rss")) { handleRSS(req, res, site, pageSlug); } else { renderer.renderCMSPage(req, res, site, pageSlug); } } catch (Exception e) { logger.error("Exception while rendering CMS page " + req.getRequestURI(), e); if (res.isCommitted()) { return; } res.reset(); res.resetBuffer(); renderer.errorPage(req, res, site, 500); } } else { if (Authenticate.isLogged()) { renderer.errorPage(req, res, site, 403); } else { renderer.errorPage(req, res, site, 401); } return; } } else { if (Authenticate.isLogged()) { renderer.errorPage(req, res, site, 403); } else { renderer.errorPage(req, res, site, 401); } return; } }