Java Code Examples for javax.servlet.ServletResponse#setContentLength()
The following examples show how to use
javax.servlet.ServletResponse#setContentLength() .
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: SpecUrlFilter.java From apicurio-registry with Apache License 2.0 | 6 votes |
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CharResponseWrapper wrappedResponse = new CharResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrappedResponse); byte[] bytes = wrappedResponse.getByteArray(); if (bytes != null && response.getContentType() != null && response.getContentType().contains("text/html")) { String specUrl = this.generateSpecUrl((HttpServletRequest) request); String out = new String(bytes, StandardCharsets.UTF_8); out = out.replace("SPEC_URL", specUrl); byte[] newBytes = out.getBytes(StandardCharsets.UTF_8); response.setContentLength(newBytes.length); response.getOutputStream().write(newBytes); } else if (bytes != null && bytes.length > 0) { response.getOutputStream().write(bytes); } }
Example 2
Source File: BaseHrefFilter.java From apicurio-registry with Apache License 2.0 | 6 votes |
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CharResponseWrapper wrappedResponse = new CharResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrappedResponse); byte[] bytes = wrappedResponse.getByteArray(); if (bytes != null && response.getContentType() != null && response.getContentType().contains("text/html")) { String out = new String(bytes, StandardCharsets.UTF_8); out = out.replace("<base href=\"/\">", "<base href=\"/ui/\">"); byte[] newBytes = out.getBytes(StandardCharsets.UTF_8); response.setContentLength(newBytes.length); response.getOutputStream().write(newBytes); } else if (bytes != null && bytes.length > 0) { response.getOutputStream().write(bytes); } }
Example 3
Source File: JrpipServlet.java From jrpip with Apache License 2.0 | 6 votes |
private void serviceInitRequest(ServletResponse response, InputStream is) throws IOException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n; while ((n = is.read(buffer)) >= 0) { outBuffer.write(buffer, 0, n); } String url = outBuffer.toString(JrpipServiceRegistry.ENCODE_STRING); synchronized (this.registeredUrls) { if (!this.registeredUrls.contains(url)) { JrpipServiceRegistry.getInstance().registerWebAppAtUrl(this.webapp, url); this.registeredUrls.add(url); } } int id = CLIENT_ID.incrementAndGet(); long vmAndClientId = vmId | (long) id; String clientCount = String.valueOf(vmAndClientId); response.setContentLength(clientCount.length()); response.getWriter().write(clientCount); }
Example 4
Source File: PspServlet.java From reladomo with Apache License 2.0 | 6 votes |
private void serviceInitRequest(ServletResponse response, InputStream is) throws IOException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n; while ((n = is.read(buffer)) >= 0) { outBuffer.write(buffer, 0, n); } String url = outBuffer.toString("ISO8859_1"); synchronized (this.registeredUrls) { if (!this.registeredUrls.contains(url)) { this.registeredUrls.add(url); } } int id = CLIENT_ID.incrementAndGet(); long vmAndClientId = vmId | (long) id; String clientCount = String.valueOf(vmAndClientId); response.setContentLength(clientCount.length()); response.getWriter().write(clientCount); }
Example 5
Source File: HttpUtils.java From utils with Apache License 2.0 | 6 votes |
/** * 向响应对象中输出字符串 * * @param response 响应对象 * @param content 内容 * @throws IOException 异常 */ public static void write(ServletResponse response, String content) throws IOException { response.setContentLength(-1); PrintWriter writer = null; ServletOutputStream sos = null; try { writer = response.getWriter(); writer.println(content); } catch (Exception e) { sos = response.getOutputStream(); sos.println(content); } finally { if (null != writer) { writer.flush(); writer.close(); } if (null != sos) { sos.flush(); sos.close(); } } }
Example 6
Source File: HttpUtils.java From utils with Apache License 2.0 | 6 votes |
/** * 向响应对象中输出字符串 * * @param response 响应对象 * @param data 数据 * @throws IOException 异常 */ public static void write(ServletResponse response, Object data) throws IOException { response.setContentLength(-1); response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("utf-8"); String json = JSON.toJSONString(data); PrintWriter writer = null; ServletOutputStream sos = null; try { writer = response.getWriter(); writer.println(json); } catch (Exception e) { sos = response.getOutputStream(); sos.println(json); } finally { if (null != writer) { writer.flush(); writer.close(); } if (null != sos) { sos.flush(); sos.close(); } } }
Example 7
Source File: BaseHrefFilter.java From apicurio-studio with Apache License 2.0 | 6 votes |
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CharResponseWrapper wrappedResponse = new CharResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrappedResponse); byte[] bytes = wrappedResponse.getByteArray(); if (bytes != null && response.getContentType().contains("text/html")) { String out = new String(bytes, StandardCharsets.UTF_8); out = out.replace("<base href=\"/\">", "<base href=\"/studio/\">"); byte[] newBytes = out.getBytes(StandardCharsets.UTF_8); response.setContentLength(newBytes.length); response.getOutputStream().write(newBytes); } else if (bytes != null && bytes.length > 0) { response.getOutputStream().write(bytes); } }
Example 8
Source File: ShutdownFilter.java From heroic with Apache License 2.0 | 6 votes |
@Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException { if (!stopping.get()) { chain.doFilter(request, response); return; } final HttpServletResponse httpResponse = (HttpServletResponse) response; final InternalErrorMessage info = new InternalErrorMessage("Heroic is shutting down", Status.SERVICE_UNAVAILABLE); httpResponse.setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); httpResponse.setContentType(CONTENT_TYPE); // intercept request try (final ByteArrayOutputStream output = new ByteArrayOutputStream(4096)) { final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.UTF_8); mapper.writeValue(writer, info); response.setContentLength(output.size()); output.writeTo(httpResponse.getOutputStream()); } }
Example 9
Source File: CommonAuthResponseWrapper.java From carbon-identity-framework with Apache License 2.0 | 5 votes |
private void writeContent() throws IOException { byte[] content = getContent(); ServletResponse response = getResponse(); OutputStream os = response.getOutputStream(); response.setContentLength(content.length); os.write(content); os.close(); }
Example 10
Source File: AbstractJettyServerTestCase.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest httpReq = (HttpServletRequest) req; assertEquals("Invalid HTTP method", method, httpReq.getMethod()); res.setContentLength(0); ((HttpServletResponse) res).setStatus(200); }
Example 11
Source File: Bug2928673.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (response instanceof HttpServletResponse) { final PrintWriter out = response.getWriter(); final HttpServletResponse wrapper = (HttpServletResponse) response; chain.doFilter(request, wrapper); final String origData = wrapper.getContentType(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Hello"); } if ("text/html".equals(wrapper.getContentType())) { final CharArrayWriter caw = new CharArrayWriter(); final int bodyIndex = origData.indexOf("</body>"); if (-1 != bodyIndex) { caw.write(origData.substring(0, bodyIndex - 1)); caw.write("\n<p>My custom footer</p>"); caw.write("\n</body></html>"); response.setContentLength(caw.toString().length()); out.write(caw.toString()); } else { out.write(origData); } } else { out.write(origData); } out.close(); } else { chain.doFilter(request, response); } }
Example 12
Source File: ResponseHandlerBase.java From development with Apache License 2.0 | 5 votes |
/** * Writes the entire stream from the method to the response stream. * * @param response * Response to send data to * @throws IOException * An IOException is thrown when we are having problems with * reading the streams */ protected void sendStreamToClient(ServletResponse response) throws IOException { InputStream streamFromServer = method.getResponseBodyAsStream(); OutputStream responseStream = null; if (streamFromServer != null) { byte[] buffer = new byte[1024]; int read = streamFromServer.read(buffer); while (read > 0) { if (responseStream == null) { responseStream = response.getOutputStream(); } responseStream.write(buffer, 0, read); read = streamFromServer.read(buffer); } streamFromServer.close(); } // pock: if we dont't have any content set the length to 0 (corrects the // 302 Moved Temporarily processing) if (responseStream == null) { response.setContentLength(0); } else { responseStream.flush(); responseStream.close(); } }
Example 13
Source File: TestFilter.java From seed with Mozilla Public License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException { String text = CONTENT + " " + param1Value; servletResponse.setContentType("text/plain"); servletResponse.setContentLength(text.length()); servletResponse.getWriter().write(text); }
Example 14
Source File: MCRURIResolverFilter.java From mycore with GNU General Public License v3.0 | 4 votes |
/** * adds debug information from MCRURIResolver to Servlet output. * * The information includes all URIs resolved by MCRURIResolver by the * current request. The filter is triggered by the log4j statement of the * MCRURIResolver. To switch it on set the logger to DEBUG level. * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { /* * isDebugEnabled() may return a different value when called a second * time. Since we initialize things in the first block, we need to make * sure to visit the second block only if we visited the first block, * too. */ final boolean debugEnabled = LOGGER.isDebugEnabled(); if (!debugEnabled) { //do not filter... filterChain.doFilter(request, response); } else { MyResponseWrapper wrapper = new MyResponseWrapper((HttpServletResponse) response); // process request filterChain.doFilter(request, wrapper); final String origOutput = wrapper.toString(); final String characterEncoding = wrapper.getCharacterEncoding(); if (!uriList.get().isEmpty() && origOutput.length() > 0 && (response.getContentType().contains("text/html") || response.getContentType().contains("text/xml"))) { final String insertString = "\n<!-- \n" + uriList.get() + "\n-->"; final byte[] insertBytes = insertString.getBytes(characterEncoding); response.setContentLength(origOutput.getBytes(characterEncoding).length + insertBytes.length); int pos = getInsertPosition(origOutput); try (ServletOutputStream out = response.getOutputStream()) { out.write(origOutput.substring(0, pos).getBytes(characterEncoding)); out.write(insertBytes); out.write(origOutput.substring(pos).getBytes(characterEncoding)); // delete debuglist uriList.remove(); LOGGER.debug("end filter: {}", origOutput.substring(origOutput.length() - 10)); } } else { LOGGER.debug("Sending original response"); byte[] byteArray = wrapper.output.toByteArray(); if (byteArray.length > 0) { try (ServletOutputStream out = response.getOutputStream()) { out.write(byteArray); } } } } }
Example 15
Source File: GZipServletFilter.java From para with Apache License 2.0 | 4 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) { // Client accepts zipped content if (log.isTraceEnabled()) { log.trace("{} Written with gzip compression", httpRequest.getRequestURL()); } // Create a gzip stream final ByteArrayOutputStream compressed = new ByteArrayOutputStream(); final GZIPOutputStream gzout = new GZIPOutputStream(compressed); // Handle the request final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout); wrapper.setDisableFlushBuffer(true); chain.doFilter(request, wrapper); wrapper.flush(); gzout.close(); // double check one more time before writing out // repsonse might have been committed due to error if (response.isCommitted()) { return; } // return on these special cases when content is empty or unchanged switch (wrapper.getStatus()) { case HttpServletResponse.SC_NO_CONTENT: case HttpServletResponse.SC_RESET_CONTENT: case HttpServletResponse.SC_NOT_MODIFIED: return; default: } // Saneness checks byte[] compressedBytes = compressed.toByteArray(); boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest); boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus()); if (shouldGzippedBodyBeZero || shouldBodyBeZero) { // No reason to add GZIP headers or write body if no content was written or status code specifies no // content response.setContentLength(0); return; } // Write the zipped body GZipResponseUtil.addGzipHeader(httpResponse); // Only write out header Vary as needed GZipResponseUtil.addVaryAcceptEncoding(wrapper); response.setContentLength(compressedBytes.length); response.getOutputStream().write(compressedBytes); } else { // Client does not accept zipped content - don't bother zipping if (log.isTraceEnabled()) { log.trace("{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL()); } chain.doFilter(request, response); } }
Example 16
Source File: TutorialFilter.java From projectforge-webapp with GNU General Public License v3.0 | 4 votes |
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException { final String uri = ((HttpServletRequest) req).getRequestURI(); if (uri.matches(".*/ProjectForge.*.html") == false) { chain.doFilter(req, resp); return; } final PrintWriter out = resp.getWriter(); final CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) resp); chain.doFilter(req, wrapper); final CharArrayWriter caw = new CharArrayWriter(); final String tutorialUrl = ((HttpServletResponse) resp).encodeURL(WicketUtils.getAbsoluteUrl("/wa/tutorial")); final String regexp = "(\\{actionLink\\|)([a-zA-Z0-9]*)\\|([a-zA-Z0-9_\\-]*)(\\})([^\\{]*)(\\{/actionLink\\})"; final Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); // Compiles regular expression into Pattern. final Matcher m = p.matcher(wrapper.toString()); final StringBuffer buf = new StringBuffer(); // final String html = m.replaceAll(tutorialUrl + "/Hurzel"); try { while (m.find() == true) { int i = 2; if (m.groupCount() != 6) { buf.append("{actionLink syntax error: " + m.groupCount() + ".}"); continue; } // {actionLink|createUser|linda}create{/actionLink} m.appendReplacement(buf, "<a target=\"tutorial\" href=\""); buf.append(tutorialUrl); final String type = m.group(i++); // createUser if (type == null) { buf.append("\">create</a>"); continue; } buf.append("?type=").append(type).append("&ref="); final String ref = m.group(i++); if (ref == null) { buf.append("\">create</a>"); continue; } buf.append(ref).append("\"><img src=\"images/actionlink_add.png\" style=\"vertical-align:middle;border:none;\" />"); i++; // } final String label = m.group(i++); if (label == null) { buf.append("\">create</a>"); continue; } buf.append(label); buf.append("</a>"); } m.appendTail(buf); } catch (final Exception ex) { log.error(ex.getMessage(), ex); } // html = html.replace("{actionLink}", tutorialUrl); // <link url="{actionLink}?type=createUser&ref=linda" target="tutorial">create</link> caw.write(buf.toString()); // caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>") - 1)); // caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font></center>"); // caw.write("\n</body></html>"); resp.setContentLength(caw.toString().length()); out.write(caw.toString()); out.close(); }