List of usage examples for javax.servlet.http HttpServletResponse getContentType
public String getContentType();
From source file:org.impalaframework.web.servlet.ResourceServlet.java
private OutputStream selectOutputStream(HttpServletRequest request, HttpServletResponse response) throws IOException { String acceptEncoding = request.getHeader("Accept-Encoding"); String mimeType = response.getContentType(); if (gzipEnabled && StringUtils.hasText(acceptEncoding) && acceptEncoding.indexOf("gzip") > -1 && matchesCompressedMimeTypes(mimeType)) { log.debug("Enabling GZIP compression for the current response."); return new GZIPResponseStream(response); } else {/*from ww w .j a v a2s .c o m*/ return response.getOutputStream(); } }
From source file:org.madsonic.controller.CoverArtController.java
private void sendDefault(Integer size, HttpServletResponse response) throws IOException { if (response.getContentType() == null) { response.setContentType(StringUtil.getMimeType("png")); }//from w w w. j ava 2 s. c om InputStream in = null; try { in = getClass().getResourceAsStream("default_cover.png"); BufferedImage image = ImageIO.read(in); if (size != null) { image = scale(image, size, size); } ImageIO.write(image, "png", response.getOutputStream()); } finally { IOUtils.closeQuietly(in); } }
From source file:org.n52.ses.common.environment.SESMiniServlet.java
private void printResponse(HttpServletRequest request, HttpServletResponse response, String string) throws IOException { int contentLength = string.getBytes("UTF-8").length; if (firstResponsePrint.getAndSet(false)) { ConfigurationRegistry conf = ConfigurationRegistry.getInstance(); if (conf == null) { firstResponsePrint.getAndSet(true); } else {/*w ww .j av a 2 s . c om*/ minimumContentLengthForGzip = Integer .parseInt(conf.getPropertyForKey(ConfigurationRegistry.MINIMUM_GZIP_SIZE)); } } // compressed response if (contentLength > minimumContentLengthForGzip && clientSupportsGzip(request)) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream gzip = new GZIPOutputStream(response.getOutputStream(), contentLength); String type = response.getContentType(); if (!type.contains("charset")) { response.setContentType(type + "; charset=utf-8"); } gzip.write(string.getBytes(Charset.forName("UTF-8"))); gzip.flush(); gzip.finish(); } // uncompressed response else { response.setContentLength(contentLength); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.write(string); writer.flush(); } }
From source file:org.olat.core.gui.media.ServletUtil.java
/** * @param response/*from w ww. j a va 2 s . c o m*/ * @param result */ public static void serveStringResource(HttpServletRequest httpReq, HttpServletResponse response, String result) { setStringResourceHeaders(response); // log the response headers prior to sending the output boolean isDebug = log.isDebug(); if (isDebug) { log.debug( "\nResponse headers (some)\ncontent type:" + response.getContentType() + "\ncharacterencoding:" + response.getCharacterEncoding() + "\nlocale:" + response.getLocale()); } try { long rstart = 0; if (isDebug) { rstart = System.currentTimeMillis(); } // make a ByteArrayOutputStream to be able to determine the length. // buffer size: assume average length of a char in bytes is max 2 ByteArrayOutputStream baos = new ByteArrayOutputStream(result.length() * 2); // we ignore the accept-charset from the request and always write in // utf-8: // we have lots of different languages (content) in one application to // support, and more importantly, // a blend of olat translations and content by authors which can be in // different languages. OutputStreamWriter osw = new OutputStreamWriter(baos, "utf-8"); osw.write(result); osw.close(); // the data is now utf-8 encoded in the bytearray -> push it into the outputstream int encLen = baos.size(); response.setContentLength(encLen); OutputStream os; if (Settings.isDebuging()) { SlowBandWidthSimulator sbs = Windows .getWindows(CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(httpReq)) .getSlowBandWidthSimulator(); os = sbs.wrapOutputStream(response.getOutputStream()); } else { os = response.getOutputStream(); } byte[] bout = baos.toByteArray(); os.write(bout); os.close(); if (isDebug) { long rstop = System.currentTimeMillis(); log.debug("time to serve inline-resource " + result.length() + " chars / " + encLen + " bytes: " + (rstop - rstart)); } } catch (IOException e) { if (isDebug) { log.warn("client browser abort when serving inline", e); } } }
From source file:org.olat.core.gui.media.ServletUtil.java
public static void serveStringResource(HttpServletResponse response, StringOutput result) { setStringResourceHeaders(response);//from ww w .j av a 2 s . c om // log the response headers prior to sending the output boolean isDebug = log.isDebug(); if (isDebug) { log.debug( "\nResponse headers (some)\ncontent type:" + response.getContentType() + "\ncharacterencoding:" + response.getCharacterEncoding() + "\nlocale:" + response.getLocale()); } try { long rstart = 0; if (isDebug || true) { rstart = System.currentTimeMillis(); } // make a ByteArrayOutputStream to be able to determine the length. // buffer size: assume average length of a char in bytes is max 2 int encLen = result.length(); Reader reader = result.getReader(); //response.setContentLength(encLen); set the number of characters, must be number of bytes PrintWriter os = response.getWriter(); IOUtils.copy(reader, os); os.close(); if (isDebug) { log.debug("time to serve inline-resource " + result.length() + " chars / " + encLen + " bytes: " + (System.currentTimeMillis() - rstart)); } } catch (IOException e) { if (isDebug) { log.warn("client browser abort when serving inline", e); } } }
From source file:org.sakaiproject.portal.charon.handlers.PDAHandler.java
public Object bufferContent(HttpServletRequest req, HttpServletResponse res, Session session, String placementId, String toolContextPath, String toolPathInfo, ToolConfiguration siteTool) { log.debug("bufferContent starting"); // Produce the buffered response ByteArrayServletResponse bufferedResponse = new ByteArrayServletResponse(res); try {/*from w w w .j a v a 2 s. c o m*/ // Prepare the session for the tools. Handles session reset, reseturl // and helpurl for neo tools - we don't need the returned map Map discard = portal.includeTool(res, req, siteTool, true); boolean retval = doToolBuffer(req, bufferedResponse, session, placementId, toolContextPath, toolPathInfo); log.debug("bufferContent retval=" + retval); // Cleanup transient session bits - SAK-25857 ToolSession ts = session.getToolSession(siteTool.getId()); if (ts != null) { ts.removeAttribute(Portal.SAKAI_PORTAL_ALLOW_NEO); ts.removeAttribute(Portal.SAKAI_PORTAL_HELP_ACTION); ts.removeAttribute(Portal.SAKAI_PORTAL_RESET_ACTION); } if (!retval) return Boolean.FALSE; // If the tool did a redirect - tell our caller to just complete the response if (bufferedResponse.getRedirect() != null) return bufferedResponse; // Check the response contentType for a pattern match String commonToolId = siteTool.getToolId(); String pattern = ServerConfigurationService.getString(BYPASS_TYPE_PROP, DEFAULT_BYPASS_TYPE); pattern = ServerConfigurationService.getString(BYPASS_TYPE_PROP + "." + commonToolId, pattern); if (pattern.length() > 0) { String contentType = res.getContentType(); if (contentType == null) contentType = ""; Pattern p = Pattern.compile(pattern); Matcher mc = p.matcher(contentType.toLowerCase()); if (mc.find()) return bufferedResponse; } } catch (ToolException e) { e.printStackTrace(); return Boolean.FALSE; } catch (IOException e) { e.printStackTrace(); return Boolean.FALSE; } String responseStr = bufferedResponse.getInternalBuffer(); if (responseStr == null || responseStr.length() < 1) return Boolean.FALSE; String responseStrLower = responseStr.toLowerCase(); int headStart = responseStrLower.indexOf("<head"); headStart = findEndOfTag(responseStrLower, headStart); int headEnd = responseStrLower.indexOf("</head"); int bodyStart = responseStrLower.indexOf("<body"); bodyStart = findEndOfTag(responseStrLower, bodyStart); // Some tools (Blogger for example) have multiple // head-body pairs - browsers seem to not care much about // this so we will do the same - so that we can be // somewhat clean - we search for the "last" end // body tag - for the normal case there will only be one int bodyEnd = responseStrLower.lastIndexOf("</body"); // If there is no body end at all or it is before the body // start tag we simply - take the rest of the response if (bodyEnd < bodyStart) bodyEnd = responseStrLower.length() - 1; String tidAllow = ServerConfigurationService.getString(IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); if (tidAllow.indexOf(":debug:") >= 0) log.info("Frameless HS=" + headStart + " HE=" + headEnd + " BS=" + bodyStart + " BE=" + bodyEnd); if (bodyEnd > bodyStart && bodyStart > headEnd && headEnd > headStart && headStart > 1) { Map m = new HashMap<String, String>(); String headString = responseStr.substring(headStart + 1, headEnd); String bodyString = responseStr.substring(bodyStart + 1, bodyEnd); if (tidAllow.indexOf(":debug:") >= 0) { System.out.println(" ---- Head --- "); System.out.println(headString); System.out.println(" ---- Body --- "); System.out.println(bodyString); } m.put("responseHead", headString); m.put("responseBody", bodyString); log.debug("responseHead " + headString.length() + " bytes, responseBody " + bodyString.length() + " bytes"); return m; } log.debug("bufferContent could not find head/body content"); // log.debug(responseStr); return bufferedResponse; }
From source file:org.sakaiproject.portal.charon.handlers.SiteHandler.java
public Object bufferContent(HttpServletRequest req, HttpServletResponse res, Session session, String placementId, String toolContextPath, String toolPathInfo, ToolConfiguration siteTool) { log.debug("bufferContent starting"); // Produce the buffered response ByteArrayServletResponse bufferedResponse = new ByteArrayServletResponse(res); try {// www .ja va 2 s .c o m // Prepare the session for the tools. Handles session reset, reseturl // and helpurl for neo tools - we don't need the returned map Map discard = portal.includeTool(res, req, siteTool, true); boolean retval = doToolBuffer(req, bufferedResponse, session, placementId, toolContextPath, toolPathInfo); log.debug("bufferContent retval=" + retval); if (!retval) return Boolean.FALSE; // If the tool did a redirect - tell our caller to just complete the response if (bufferedResponse.getRedirect() != null) return bufferedResponse; // Check the response contentType for a pattern match String commonToolId = siteTool.getToolId(); String pattern = ServerConfigurationService.getString(LEGACY_BYPASS_TYPE_PROP, DEFAULT_BYPASS_TYPE); pattern = ServerConfigurationService.getString(BYPASS_TYPE_PROP, pattern); pattern = ServerConfigurationService.getString(LEGACY_BYPASS_TYPE_PROP + "." + commonToolId, pattern); pattern = ServerConfigurationService.getString(BYPASS_TYPE_PROP + "." + commonToolId, pattern); if (pattern.length() > 0) { String contentType = res.getContentType(); if (contentType == null) contentType = ""; Pattern p = Pattern.compile(pattern); Matcher mc = p.matcher(contentType.toLowerCase()); if (mc.find()) return bufferedResponse; } } catch (ToolException e) { e.printStackTrace(); return Boolean.FALSE; } catch (IOException e) { e.printStackTrace(); return Boolean.FALSE; } String responseStr = bufferedResponse.getInternalBuffer(); if (responseStr == null || responseStr.length() < 1) return Boolean.FALSE; String responseStrLower = responseStr.toLowerCase(); int headStart = responseStrLower.indexOf("<head"); headStart = findEndOfTag(responseStrLower, headStart); int headEnd = responseStrLower.indexOf("</head"); int bodyStart = responseStrLower.indexOf("<body"); bodyStart = findEndOfTag(responseStrLower, bodyStart); // Some tools (Blogger for example) have multiple // head-body pairs - browsers seem to not care much about // this so we will do the same - so that we can be // somewhat clean - we search for the "last" end // body tag - for the normal case there will only be one int bodyEnd = responseStrLower.lastIndexOf("</body"); // If there is no body end at all or it is before the body // start tag we simply - take the rest of the response if (bodyEnd < bodyStart) bodyEnd = responseStrLower.length() - 1; String tidAllow = ServerConfigurationService.getString(LEGACY_IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); tidAllow = ServerConfigurationService.getString(IFRAME_SUPPRESS_PROP, tidAllow); if (tidAllow.indexOf(":debug:") >= 0) log.info("Frameless HS=" + headStart + " HE=" + headEnd + " BS=" + bodyStart + " BE=" + bodyEnd); if (bodyEnd > bodyStart && bodyStart > headEnd && headEnd > headStart && headStart > 1) { Map m = new HashMap<String, String>(); String headString = responseStr.substring(headStart + 1, headEnd); // SAK-29908 // Titles come twice to view and tool title overwrites main title because // it is printed before. int titleStart = headString.indexOf("<title"); int titleEnd = headString.indexOf("</title"); titleEnd = findEndOfTag(headString, titleEnd); headString = (titleStart != -1 && titleEnd != -1) ? headString.substring(0, titleStart) + headString.substring(titleEnd + 1) : headString; // End SAK-29908 String bodyString = responseStr.substring(bodyStart + 1, bodyEnd); if (tidAllow.indexOf(":debug:") >= 0) { System.out.println(" ---- Head --- "); System.out.println(headString); System.out.println(" ---- Body --- "); System.out.println(bodyString); } m.put("responseHead", headString); m.put("responseBody", bodyString); log.debug("responseHead " + headString.length() + " bytes, responseBody " + bodyString.length() + " bytes"); return m; } log.debug("bufferContent could not find head/body content"); // log.debug(responseStr); return bufferedResponse; }
From source file:org.xwiki.portlet.controller.DispatchFilter.java
/** * Filters a render request.// w w w. j ava2s.co m * * @param request the request object * @param response the response object * @param chain the filter chain * @throws ServletException if processing the request fails * @throws IOException if writing the response fails */ private void doRender(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // The content type is not always set for static resources. The dispatched response needs to know the content // type before its writer or output stream are requested in order to determine if the output should be written // directly to the original response or stored for processing. String mimeType = config.getServletContext().getMimeType(request.getRequestURI()); if (mimeType != null && response.getContentType() == null) { response.setContentType(mimeType); } StreamFilterManager streamFilterManager = (StreamFilterManager) request .getAttribute(DispatchPortlet.ATTRIBUTE_STREAM_FILTER_MANAGER); DispatchedMimeResponse responseWrapper = new DispatchedMimeResponse(response, streamFilterManager.getKnownMimeTypes()); chain.doFilter(new DispatchedRequest(request, false), responseWrapper); if (responseWrapper.isOutputIntercepted()) { LOG.debug("Filtering " + request.getRequestURI()); streamFilterManager.filter(responseWrapper.getMimeType(), responseWrapper.getReader(), response.getWriter()); } }
From source file:spark.webserver.MatcherFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, // NOSONAR FilterChain chain) throws IOException, ServletException { // NOSONAR HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; // NOSONAR HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; String httpMethodStr = httpRequest.getMethod().toLowerCase(); // NOSONAR String uri = httpRequest.getRequestURI(); // NOSONAR String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER); String bodyContent = null;//from w w w. ja v a 2 s. c o m if (!isStaticFileRequest(servletRequest, servletResponse, chain)) { RequestWrapper req = new RequestWrapper(); ResponseWrapper res = new ResponseWrapper(); try { // BEFORE filters List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri, acceptType); for (RouteMatch filterMatch : matchSet) { Object filterTarget = filterMatch.getTarget(); if (filterTarget instanceof spark.Filter) { Request request = RequestResponseFactory.create(filterMatch, httpRequest); Response response = RequestResponseFactory.create(httpResponse); spark.Filter filter = (spark.Filter) filterTarget; req.setDelegate(request); res.setDelegate(response); filter.handle(req, res); String bodyAfterFilter = Access.getBody(response); if (bodyAfterFilter != null) { bodyContent = bodyAfterFilter; } } } // BEFORE filters, END HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr); RouteMatch match = null; match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType); Object target = null; if (match != null) { target = match.getTarget(); } else if (httpMethod == HttpMethod.head && bodyContent == null) { // See if get is mapped to provide default head mapping bodyContent = routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null ? "" : null; } else if (httpMethod == HttpMethod.options && bodyContent == null) { // CON-476: For an OPTIONS request, attempt to get all the // targets for the route and specify those in the response Set<HttpMethod> methods = routeMatcher.findMethodsForRequestedPath(uri, acceptType); if (!methods.isEmpty()) { httpResponse.setHeader("Allow", StringUtils.join(methods, ',')); bodyContent = ""; } } if (target != null) { try { String result = null; if (target instanceof Route) { Route route = ((Route) target); Request request = RequestResponseFactory.create(match, httpRequest); Response response = RequestResponseFactory.create(httpResponse); req.setDelegate(request); res.setDelegate(response); Object element = route.handle(req, res); result = route.render(element); } if (result != null) { bodyContent = result; } } catch (HaltException hEx) { // NOSONAR throw hEx; // NOSONAR } catch (Exception e) { Logger.error("", e); httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); bodyContent = INTERNAL_ERROR; } } // AFTER filters matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType); for (RouteMatch filterMatch : matchSet) { Object filterTarget = filterMatch.getTarget(); if (filterTarget instanceof spark.Filter) { Request request = RequestResponseFactory.create(filterMatch, httpRequest); Response response = RequestResponseFactory.create(httpResponse); req.setDelegate(request); res.setDelegate(response); spark.Filter filter = (spark.Filter) filterTarget; filter.handle(req, res); String bodyAfterFilter = Access.getBody(response); if (bodyAfterFilter != null) { bodyContent = bodyAfterFilter; } } } // AFTER filters, END } catch (HaltException hEx) { httpResponse.setStatus(hEx.getStatusCode()); if (hEx.getBody() != null) { bodyContent = hEx.getBody(); } else { bodyContent = ""; } } } boolean consumed = bodyContent != null; if (!consumed && hasOtherHandlers) { throw new NotConsumedException(); } if (!consumed && !isServletContext) { httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); bodyContent = String.format(NOT_FOUND, uri); consumed = true; } if (consumed) { // Write body content if (!httpResponse.isCommitted()) { if (httpResponse.getContentType() == null) { httpResponse.setContentType("text/html; charset=utf-8"); } httpResponse.getOutputStream().write(bodyContent.getBytes("utf-8")); } } else if (chain != null) { chain.doFilter(httpRequest, httpResponse); } }